<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../core/api.php'; 

// 1. Validaciones de Seguridad
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Método no permitido']);
    exit;
}

// 2. Recibir Datos
$invoice_db_id = $_POST['invoice_id'] ?? null;
$invoice_str_id = $_POST['invoice_number'] ?? '';
$amount = $_POST['amount'] ?? 0;
$client_id = $_POST['client_id'] ?? null;

if (empty($client_id) || $client_id === 'null') {
    $client_id = null;
}

if (!$invoice_db_id || !isset($_FILES['pdf_file'])) {
    echo json_encode(['success' => false, 'message' => 'Faltan datos o el archivo PDF']);
    exit;
}

try {
    $pdo->beginTransaction();

    // --- PASO A: Guardar PDF ---
    $meses = ['January'=>'enero','February'=>'febrero','March'=>'marzo','April'=>'abril','May'=>'mayo','June'=>'junio','July'=>'julio','August'=>'agosto','September'=>'septiembre','October'=>'octubre','November'=>'noviembre','December'=>'diciembre'];
    $mes_ingles = date('F');
    $mes_carpeta = $meses[$mes_ingles] ?? strtolower($mes_ingles);

    $uploadDir = __DIR__ . '/../uploads/finances/' . $mes_carpeta . '/';
    
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $fileName = "comprobante_{$invoice_str_id}_" . time() . ".pdf";
    $filePath = $uploadDir . $fileName;
    
    $dbFilePath = "uploads/finances/{$mes_carpeta}/" . $fileName;

    if (!move_uploaded_file($_FILES['pdf_file']['tmp_name'], $filePath)) {
        throw new Exception("No se pudo guardar el archivo PDF en el servidor.");
    }

    // --- PASO B: Actualizar Factura ---
    $stmtInvoice = $pdo->prepare("UPDATE invoices SET status = 'paid', updated_at = NOW() WHERE id = :id");
    $stmtInvoice->execute([':id' => $invoice_db_id]);

    // --- PASO C: Insertar en Finanzas (TRANSACTIONS - Corregido de 'finances' y 'ingreso' a 'income') ---
    $description = "Ingreso por factura pagada #" . $invoice_str_id;
    
    $sqlFinance = "INSERT INTO transactions (
        user_id,
        transaction_type, 
        description, 
        amount, 
        transaction_date, 
        client_id, 
        receipt_file, 
        created_at
    ) VALUES (
        :user_id,
        'income', 
        :description, 
        :amount, 
        CURDATE(), 
        :client_id, 
        :receipt_file, 
        NOW()
    )";

    $stmtFinance = $pdo->prepare($sqlFinance);
    $stmtFinance->execute([
        ':user_id' => $_SESSION['user_id'] ?? 1,
        ':description' => $description,
        ':amount' => $amount,
        ':client_id' => $client_id,
        ':receipt_file' => $dbFilePath
    ]);

    $pdo->commit();

    echo json_encode([
        'success' => true, 
        'message' => 'Factura pagada y registrada correctamente.',
        'pdf_url' => $dbFilePath
    ]);

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    if (isset($filePath) && file_exists($filePath)) {
        unlink($filePath);
    }
    error_log("Error Backend: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>