<?php
// db/finances-update.php
ob_start();
error_reporting(0);
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 (empty($data['id'])) {
        throw new Exception('ID de la transacción no proporcionado.');
    }
     if (!isset($data['type'], $data['description'], $data['amount'], $data['transaction_date'])) {
        throw new Exception('Datos incompletos. Tipo, descripción, monto y fecha son requeridos.');
    }

    $id = $data['id'];
    $type = $data['type'];
    $description = trim($data['description']);
    $amount = filter_var($data['amount'], FILTER_VALIDATE_FLOAT);
    $transaction_date = $data['transaction_date'];
    $client_id = !empty($data['client_id']) ? filter_var($data['client_id'], FILTER_VALIDATE_INT) : null;

    $sql = "UPDATE finances SET type = ?, description = ?, amount = ?, transaction_date = ?, client_id = ? WHERE id = ?";
    $stmt = $pdo->prepare($sql);

    if ($stmt->execute([$type, $description, $amount, $transaction_date, $client_id, $id])) {
        $response = ['success' => true, 'message' => 'Transacción actualizada con éxito.'];
    } else {
        throw new Exception('Falló la ejecución de la consulta de actualización.');
    }
} catch (PDOException $e) {
    error_log("PDO Error en finances-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'Error de Base de Datos: ' . $e->getMessage()];
} catch (Exception $e) {
    error_log("General Error en finances-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => $e->getMessage()];
}

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