<?php
/**
 * SAC 2026 - MASTER BILL PAYMENT DELETE v1.0
 * Kernel V4.0.91
 * REVERSIÓN NUCLEAR: Elimina abono, revierte banco y recalcula factura.
 */
require_once 'config.php';

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

$data = $REQUEST_DATA;

if (!isset($data['id']) || !isset($data['bill_id'])) {
    response(["error" => "Parámetros de anulación incompletos"], 400);
}

try {
    $pdo->beginTransaction();

    $paymentId = (int)$data['id'];
    $billId = (int)$data['bill_id'];

    // 1. Obtener rastro antes de borrar
    $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("El registro del abono ya no existe.");

    $originalRef = $oldPay['reference'];

    // 2. ELIMINAR REGISTRO DE ABONO
    $stmtDel = $pdo->prepare("DELETE FROM pending_bill_payments WHERE id = ?");
    $stmtDel->execute([$paymentId]);

    // 3. REVERTIR LIBRO DE BANCO (Egreso y Comisión)
    // Buscamos el egreso principal
    $pdo->prepare("DELETE FROM bank_transactions 
                   WHERE reference = ? 
                   AND type = 'Egreso' 
                   AND category = 'Proveedores'")
        ->execute([$originalRef]);

    // Buscamos la comisión asociada
    $pdo->prepare("DELETE FROM bank_transactions 
                   WHERE reference = ? 
                   AND type = 'Egreso' 
                   AND category = 'Comisiones'")
        ->execute([$originalRef]);

    // 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 original de la factura para determinar estatus
    $stmtBillTotal = $pdo->prepare("SELECT amount_usd FROM pending_bills WHERE id = ?");
    $stmtBillTotal->execute([$billId]);
    $totalBillUsd = (float)$stmtBillTotal->fetchColumn();

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

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

    $pdo->commit();
    logSystemAction("ANULÓ ABONO PROVEEDOR ID: $paymentId. Reversión bancaria y de balance completada.", "BALANCE");
    response(["success" => true]);

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