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

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 '../core/api.php';

    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('ERROR AL PROCESAR DATOS');
    }
    if (!isset($data['id'], $data['description'], $data['amount'], $data['recurrence_day_of_month'], $data['start_date'])) {
        throw new Exception('DATOS INCOMPLETOS');
    }

    $id = filter_var($data['id'], FILTER_VALIDATE_INT);
    if ($id === false) throw new Exception('ID INVALIDO');

    $description = filter_var(trim($data['description']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $amount = filter_var($data['amount'], FILTER_VALIDATE_FLOAT);
    $recurrence_day_of_month = filter_var($data['recurrence_day_of_month'], FILTER_VALIDATE_INT);
    $start_date = filter_var($data['start_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $end_date = !empty($data['end_date']) ? filter_var($data['end_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
    $client_id = isset($data['client_id']) ? filter_var($data['client_id'], FILTER_VALIDATE_INT) : null;

    if ($amount === false) throw new Exception('MONTO INVALIDO');
    if ($recurrence_day_of_month === false || $recurrence_day_of_month < 1 || $recurrence_day_of_month > 31) {
        throw new Exception('DIA DE RECURRENCIA INVALIDO');
    }

    $sql = "UPDATE recurring_transactions SET description = ?, amount = ?, recurrence_day_of_month = ?, start_date = ?, end_date = ?, client_id = ? WHERE id = ?";
    $stmt = $pdo->prepare($sql);

    if ($stmt->execute([$description, $amount, $recurrence_day_of_month, $start_date, $end_date, $client_id, $id])) {
        
        $stmt_select = $pdo->prepare("
            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.id = ?
        ");
        $stmt_select->execute([$id]);
        $updated_recurring_expense = $stmt_select->fetch(PDO::FETCH_ASSOC);

        $response['success'] = true;
        $response['message'] = 'GASTO RECURRENTE ACTUALIZADO';
        $response['recurring_expense'] = $updated_recurring_expense;

    } else {
        throw new Exception('FALLO LA EJECUCION DE ACTUALIZACION');
    }

} catch (PDOException $e) {
    error_log("PDO Error en recurring-finances-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    error_log("General Error en recurring-finances-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

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