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

    include_once 'db_connection.php';
    require_once '../files/guardiankey.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 (empty($data['id'])) {
        throw new Exception('ID REQUERIDO');
    }
    if (!isset($data['type'], $data['description'], $data['amount'], $data['transaction_date'])) {
        throw new Exception('DATOS INCOMPLETOS');
    }

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

    if ($id === false || $amount === false) {
        throw new Exception('ID O MONTO INVALIDO');
    }

    $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])) {
        
        $stmt_select = $pdo->prepare("
            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
            WHERE f.id = ?
        ");
        $stmt_select->execute([$id]);
        $updated_transaction = $stmt_select->fetch(PDO::FETCH_ASSOC);

        $response['success'] = true;
        $response['message'] = 'TRANSACCION ACTUALIZADA';
        $response['transaction'] = $updated_transaction;
        
    } else {
        throw new Exception('FALLO LA EJECUCION DE ACTUALIZACION');
    }
} catch (PDOException $e) {
    error_log("Error PDO en finances-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    error_log("General Error en 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;
?>