<?php
/**
 * SAC 2026 - MASTER BILL PAYMENT UPDATE v1.0
 * Kernel V4.0.90
 * SINCRONIZACIÓN NUCLEAR: Modifica el abono, recalcula la factura y actualiza el banco.
 */
require_once 'config.php';

checkAccess(['admin', 'programmer', 'board']);

$data = $REQUEST_DATA;

if (!isset($data['id']) || !isset($data['amount_bs'])) {
    response(["error" => "Datos incompletos"], 400);
}

try {
    $pdo->beginTransaction();

    $paymentId = (int)$data['id'];
    $billId = (int)$data['bill_id'];
    $newAmountBs = (float)$data['amount_bs'];
    $newReference = $data['reference'];
    $newDate = $data['payment_date'];

    // 1. Obtener rastro original
    $stmtOld = $pdo->prepare("SELECT reference, amount_bs, amount_usd FROM pending_bill_payments WHERE id = ?");
    $stmtOld->execute([$paymentId]);
    $oldPay = $stmtOld->fetch();
    
    if (!$oldPay) throw new Exception("Registro de pago no encontrado.");

    // Estimación de USD basada en tasa histórica del registro o 45 actual
    $appliedRate = ($oldPay['amount_usd'] > 0) ? ($oldPay['amount_bs'] / $oldPay['amount_usd']) : 45.0;
    $newAmountUsd = round($newAmountBs / $appliedRate, 2);

    // 2. ACTUALIZAR PAGO INDIVIDUAL
    $stmtUpd = $pdo->prepare("UPDATE pending_bill_payments SET 
        amount_bs = ?, 
        amount_usd = ?, 
        reference = ?, 
        payment_date = ? 
        WHERE id = ?");
    $stmtUpd->execute([$newAmountBs, $newAmountUsd, $newReference, $newDate, $paymentId]);

    // 3. ACTUALIZAR LIBRO DE BANCO (Crucial para auditoría)
    // Buscamos el egreso que coincida con la referencia y monto anterior
    $stmtBank = $pdo->prepare("UPDATE bank_transactions SET 
        amount_bs = ?, 
        amount_usd = ?, 
        reference = ?, 
        date = ? 
        WHERE reference = ? AND type = 'Egreso' AND category = 'Proveedores'");
    $stmtBank->execute([$newAmountBs, $newAmountUsd, $newReference, $newDate, $oldPay['reference']]);

    // 4. RECALCULAR BALANCE DE LA FACTURA
    $stmtSum = $pdo->prepare("SELECT SUM(amount_bs) as total_bs, SUM(amount_usd) as total_usd 
                             FROM pending_bill_payments WHERE bill_id = ?");
    $stmtSum->execute([$billId]);
    $sums = $stmtSum->fetch();
    
    $paidBs = (float)($sums['total_bs'] ?? 0);
    $paidUsd = (float)($sums['total_usd'] ?? 0);

    // Obtener monto total de la factura para estatus
    $stmtBillTotal = $pdo->prepare("SELECT amount_usd FROM pending_bills WHERE id = ?");
    $stmtBillTotal->execute([$billId]);
    $totalBillUsd = (float)$stmtBillTotal->fetchColumn();

    $newStatus = 'Parcial';
    if ($paidUsd >= ($totalBillUsd - 0.01)) {
        $newStatus = 'Pagado';
    } elseif ($paidUsd <= 0) {
        $newStatus = 'Pendiente';
    }

    $stmtUpdBill = $pdo->prepare("UPDATE pending_bills SET 
        paid_amount_bs = ?, 
        paid_amount_usd = ?, 
        status = ?,
        payment_reference = IF(? = 'Pagado', ?, payment_reference),
        paid_date = IF(? = 'Pagado', ?, paid_date)
        WHERE id = ?");
    $stmtUpdBill->execute([$paidBs, $paidUsd, $newStatus, $newStatus, $newReference, $newStatus, $newDate, $billId]);

    $pdo->commit();
    logSystemAction("EDITÓ ABONO PROVEEDOR ID: $paymentId. Sincronización realizada.", "BALANCE");
    response(["success" => true]);

} catch (Exception $e) {
    if ($pdo && $pdo->inTransaction()) $pdo->rollBack();
    response(["error" => "Fallo Nuclear al actualizar egreso: " . $e->getMessage()], 500);
}
?>