<?php
ob_start();

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

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

    // --- DETECCION: ¿ES SUBIDA DE ARCHIVO O ACTUALIZACION DE DATOS? ---

    // CASO 1: SUBIDA DE ARCHIVO (FormData desde el Modal de PC)
    if (isset($_FILES['receipt_file']) && isset($_POST['id'])) {
        
        $id = filter_var($_POST['id'], FILTER_VALIDATE_INT);
        if (!$id) throw new Exception('ID INVALIDO PARA SUBIDA');

        $meses = [
            1 => 'enero', 2 => 'febrero', 3 => 'marzo', 4 => 'abril', 
            5 => 'mayo', 6 => 'junio', 7 => 'julio', 8 => 'agosto', 
            9 => 'septiembre', 10 => 'octubre', 11 => 'noviembre', 12 => 'diciembre'
        ];
        $mesActual = $meses[date('n')];
        
        $uploadDir = "../uploads/transactions/" . $mesActual . "/"; // Mapeado a 'transactions'
        
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $extension = pathinfo($_FILES['receipt_file']['name'], PATHINFO_EXTENSION);
        $fileName = "doc_" . $id . "_" . uniqid() . "." . $extension;
        $targetPath = $uploadDir . $fileName;
        
        $dbPath = "uploads/transactions/" . $mesActual . "/" . $fileName; // Mapeado a 'transactions'

        if (move_uploaded_file($_FILES['receipt_file']['tmp_name'], $targetPath)) {
            // Actualizar BD (Mapeado a 'transactions')
            $sql = "UPDATE transactions SET receipt_file = ? WHERE id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$dbPath, $id]);

            if (!empty($_POST['amount'])) {
                $amount = filter_var($_POST['amount'], FILTER_VALIDATE_FLOAT);
                $stmt2 = $pdo->prepare("UPDATE transactions SET amount = ? WHERE id = ?");
                $stmt2->execute([$amount, $id]);
            }

            $response['success'] = true;
            $response['message'] = 'COMPROBANTE SUBIDO CORRECTAMENTE';
            $response['filepath'] = $dbPath;
        } else {
            throw new Exception('ERROR AL MOVER EL ARCHIVO');
        }

    } 
    // CASO 2: ACTUALIZACION DE DATOS (JSON Original)
    else {
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);

        if ($data) {
            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);
            $type_en = ($type === 'gasto') ? 'expense' : 'income'; // Mapeo a ENUM de DB

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

            // Mapeado a 'transactions' y 'transaction_type'
            $sql = "UPDATE transactions SET transaction_type = ?, description = ?, amount = ?, transaction_date = ?, client_id = ? WHERE id = ?";
            $stmt = $pdo->prepare($sql);

            if ($stmt->execute([$type_en, $description, $amount, $transaction_date, $client_id, $id])) {
                $stmt_select = $pdo->prepare("
                    SELECT t.id, t.transaction_type as type, t.description, t.amount, t.transaction_date, t.client_id, CONCAT(c.first_name, ' ', c.last_name) as client_name
                    FROM transactions t LEFT JOIN clients c ON t.client_id = c.id
                    WHERE t.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');
            }
        } else {
            if (empty($_POST) && empty($_FILES) && $_SERVER['CONTENT_LENGTH'] > 0) {
                 throw new Exception('EL ARCHIVO EXCEDE EL LIMITE DEL SERVIDOR');
            }
        }
    }

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

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