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

// 1. Validar datos
if (!isset($_FILES['pdf_file']) || !isset($_POST['invoice_id'])) {
    echo json_encode(['success' => false, 'message' => 'Faltan datos']);
    exit;
}

$invoiceExternalId = $_POST['invoice_id']; 
$clientName = $_POST['client_name'] ?? 'Cliente';
$amount = $_POST['amount'] ?? 0;
$date = $_POST['date'] ?? date('Y-m-d');

try {
    // 2. Preparar carpeta
    $timestamp = strtotime($date);
    $folderYear = date('Y', $timestamp);
    $folderMonth = date('m', $timestamp);
    $uploadDir = "../uploads/$folderYear/$folderMonth/";

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    // 3. Guardar el archivo físico
    $fileName = "Factura_" . $clientName . "_" . uniqid() . ".pdf";
    $fileName = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $fileName);
    
    $targetPath = $uploadDir . $fileName;
    $dbPath = "uploads/$folderYear/$folderMonth/$fileName";

    if (move_uploaded_file($_FILES['pdf_file']['tmp_name'], $targetPath)) {
        
        // 4. INSERTAR O ACTUALIZAR EN TRANSACTIONS (Corregido de 'finances' a 'transactions' y 'ingreso' a 'income')
        $stmt = $pdo->prepare("SELECT id FROM transactions WHERE linked_invoice_id = ?");
        $stmt->execute([$invoiceExternalId]);
        $existing = $stmt->fetch();

        if ($existing) {
            $update = $pdo->prepare("UPDATE transactions SET receipt_file = ? WHERE id = ?");
            $update->execute([$dbPath, $existing['id']]);
        } else {
            $insert = $pdo->prepare("INSERT INTO transactions (transaction_type, description, amount, transaction_date, receipt_file, linked_invoice_id) VALUES ('income', ?, ?, ?, ?, ?)");
            $description = "Pago de Factura " . $invoiceExternalId;
            $insert->execute([$description, $amount, $date, $dbPath, $invoiceExternalId]);
        }

        echo json_encode(['success' => true, 'path' => $dbPath]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error al mover archivo']);
    }

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>