<?php
// db/recurring-finances-update.php
ob_start();
error_reporting(0); // Desactivar errores en producción
ini_set('display_errors', 0);

include_once 'db_connection.php';

$response = [];

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

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Error: JSON inválido recibido.');
    }
    if (!isset($data['id'], $data['description'], $data['amount'], $data['recurrence_day_of_month'], $data['start_date'])) {
        throw new Exception('Datos incompletos para actualizar el gasto recurrente. ID, descripción, monto, día de recurrencia y fecha de inicio son requeridos.');
    }

    $id = filter_var($data['id'], FILTER_VALIDATE_INT);
    if ($id === false) {
        throw new Exception('ID de gasto recurrente inválido.');
    }

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

    if ($amount === false || $recurrence_day_of_month === false || $recurrence_day_of_month < 1 || $recurrence_day_of_month > 31) {
        throw new Exception('Monto o día de recurrencia inválido.');
    }

    $sql = "UPDATE recurring_finances 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])) {
        $response = ['success' => true, 'message' => 'Gasto recurrente actualizado con éxito.'];
    } else {
        throw new Exception('Falló la ejecución de la consulta de actualización del gasto recurrente.');
    }

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

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