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

    require_once __DIR__ . '/../core/api.php';
    global $pdo;

    $stmt_finances = $pdo->query("
        SELECT 
            t.id, 
            t.transaction_type as type, 
            t.description, 
            t.amount, 
            t.transaction_date, 
            t.client_id,
            t.provider_name,
            CONCAT(c.first_name, ' ', c.last_name) as client_name
        FROM transactions t
        LEFT JOIN clients c ON t.client_id = c.id
        ORDER BY t.transaction_date DESC, t.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_transactions rf
        LEFT JOIN clients c ON rf.client_id = c.id
        WHERE rf.type = 'expense' 
        ORDER BY rf.recurrence_day_of_month ASC, rf.description ASC
    ");
    $recurring_expenses = $stmt_recurring->fetchAll(PDO::FETCH_ASSOC);

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