<?php
/**
 * SAC 2026 - NUCLEAR DELETE PAYMENT v13.0
 * ANULACIÓN INTEGRAL: RECIBO + BANCO + CRÉDITO
 */
require_once 'config.php';

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

$data = $REQUEST_DATA;
if (!isset($data['paymentId'])) {
    response(["error" => "ID de pago no recibido"], 400);
}

try {
    $pdo->beginTransaction();

    $paymentId = (int)$data['paymentId'];

    // 1. Obtener toda la información del pago antes de borrar
    $stmtPay = $pdo->prepare("SELECT p.*, d.fee_id, d.property_id, d.amount_usd as debt_total_usd, prop.code as prop_code
                             FROM payments p
                             JOIN property_debts d ON p.debt_id = d.id
                             JOIN properties prop ON d.property_id = prop.id
                             WHERE p.id = ?");
    $stmtPay->execute([$paymentId]);
    $payInfo = $stmtPay->fetch();

    if (!$payInfo) throw new Exception("El registro de pago ya no existe.");

    $ref = $payInfo['reference'];
    $montoUsd = (float)$payInfo['amount_usd'];
    $propertyId = (int)$payInfo['property_id'];
    $debtId = (int)$payInfo['debt_id'];

    // 2. REVERSIÓN EN LIBRO DIARIO BANCARIO
    // Buscamos el ingreso asociado a esta referencia y unidad
    if (!empty($ref) && $ref !== 'EFECTIVO' && $ref !== 'AUTO-APPLY') {
        // Borrar el ingreso
        $pdo->prepare("DELETE FROM bank_transactions WHERE reference = ? AND type = 'Ingreso' AND description LIKE ?")
            ->execute([$ref, "%".$payInfo['prop_code']."%"]);
            
        // Borrar la comisión asociada si existiera (mismo ref, tipo egreso, categoria comisiones)
        $pdo->prepare("DELETE FROM bank_transactions WHERE reference = ? AND type = 'Egreso' AND category = 'Comisiones'")
            ->execute([$ref]);
    }

    // 3. REVERSIÓN DE SALDO A FAVOR (CRÉDITO)
    // Si este pago generó un excedente, debemos ver si hay rastro en credit_movements
    $stmtCredit = $pdo->prepare("SELECT amount_usd FROM credit_movements WHERE source_reference = ? AND property_id = ? AND type = 'Generado'");
    $stmtCredit->execute([$ref, $propertyId]);
    $excedenteGenerado = (float)($stmtCredit->fetchColumn() ?: 0);

    if ($excedenteGenerado > 0) {
        // Restar el excedente del balance actual de la propiedad
        $pdo->prepare("UPDATE properties SET credit_balance = GREATEST(0, credit_balance - ?) WHERE id = ?")
            ->execute([$excedenteGenerado, $propertyId]);
        
        // Marcar el movimiento de crédito como anulado (opcionalmente borrarlo)
        $pdo->prepare("DELETE FROM credit_movements WHERE source_reference = ? AND property_id = ?")->execute([$ref, $propertyId]);
    }

    // 4. ELIMINAR EL REGISTRO DE PAGO
    $pdo->prepare("DELETE FROM payments WHERE id = ?")->execute([$paymentId]);

    // 5. RECALCULAR DEUDA MES
    $stmtSum = $pdo->prepare("SELECT SUM(amount_usd) FROM payments WHERE debt_id = ?");
    $stmtSum->execute([$debtId]);
    $nuevoTotalPagado = (float)($stmtSum->fetchColumn() ?? 0);
    
    $montoMesUsd = (float)$payInfo['debt_total_usd'];
    $nuevoStatus = ($nuevoTotalPagado >= ($montoMesUsd - 0.01)) ? 'Pagado' : ($nuevoTotalPagado > 0 ? 'Parcial' : 'Pendiente');

    $pdo->prepare("UPDATE property_debts SET paid_amount = ?, status = ? WHERE id = ?")
        ->execute([$nuevoTotalPagado, $nuevoStatus, $debtId]);

    $pdo->commit();
    
    logSystemAction("ANULÓ PAGO ID: $paymentId (Ref: $ref) de Unidad " . $payInfo['prop_code'] . ". Reversión bancaria completada.", "PAGOS");
    response(["success" => true]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    response(["error" => $e->getMessage()], 500);
}
?>