<?php 
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO', 'transactions' => [], 'recurring_expenses' => []];

try {
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    $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);

    $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' 
        ORDER BY rf.recurrence_day_of_month ASC, rf.description ASC
    ");
    $recurring_expenses = $stmt_recurring->fetchAll(PDO::FETCH_ASSOC);

    // No se incluye mensaje de éxito en operaciones de lectura (UX)
    $response = ['success' => true, 'transactions' => $transactions, 'recurring_expenses' => $recurring_expenses];

} catch (PDOException $e) {
    error_log("Error PDO en finances-read.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("Error general en finances-read.php: " . $e->getMessage());
    $response['message'] = 'ERROR INESPERADO';
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;
?>