<?php
// db/finances-read.php (Ejemplo de cómo DEBERÍA ser)
ob_start();
error_reporting(0);
ini_set('display_errors', 0);

include_once 'db_connection.php';

$response = ['success' => false, 'message' => 'Error desconocido.', 'transactions' => [], 'recurring_expenses' => []];

try {
    // Fetch regular transactions
    $stmt_finances = $pdo->query("
        SELECT 
            f.id, 
            f.type, 
            f.description, 
            f.amount, 
            f.transaction_date, 
            f.client_id,
            CONCAT(c.first_name, ' ', c.last_name) as client_name
        FROM finances f
        LEFT JOIN clients c ON f.client_id = c.id
        ORDER BY f.transaction_date DESC, f.id DESC
    ");
    $transactions = $stmt_finances->fetchAll(PDO::FETCH_ASSOC);

    // Fetch recurring expenses
    $stmt_recurring = $pdo->query("
        SELECT 
            rf.id, 
            rf.type, 
            rf.description, 
            rf.amount, 
            rf.recurrence_day_of_month,
            rf.start_date,
            rf.end_date,
            rf.client_id,
            CONCAT(c.first_name, ' ', c.last_name) as client_name
        FROM recurring_finances rf
        LEFT JOIN clients c ON rf.client_id = c.id
        WHERE rf.type = 'gasto' -- Recurring incomes are not currently handled by the frontend logic.
        ORDER BY rf.recurrence_day_of_month ASC, rf.description ASC
    ");
    $recurring_expenses = $stmt_recurring->fetchAll(PDO::FETCH_ASSOC);

    $response = ['success' => true, 'message' => 'Datos financieros cargados.', 'transactions' => $transactions, 'recurring_expenses' => $recurring_expenses];

} catch (PDOException $e) {
    error_log("PDO Error en finances-read.php: " . $e->getMessage());
    $response['message'] = 'Error de Base de Datos al cargar: ' . $e->getMessage();
} catch (Exception $e) {
    error_log("General Error en finances-read.php: " . $e->getMessage());
    $response['message'] = 'Error general al cargar: ' . $e->getMessage();
}

ob_end_clean();
header('Content-Type: application/json');
echo json_encode($response);
exit;
?>