<?php
/**
 * SAC 2026 - APPROVAL CORE ENGINE v1.0
 * Arquitecto: Andres Mathison
 * Ejecuta la lógica nuclear de register_payment basándose en un reporte previo.
 * Incluye Sincronización Bancaria y Comisiones.
 */
require_once 'config.php';

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

$data = json_decode(file_get_contents("php://input"), true);

if (!isset($data['feeId']) || !isset($data['propertyId'])) {
    response(["error" => "Faltan punteros de aprobación"], 400);
}

try {
    $pdo->beginTransaction();

    // 1. Extraer el reporte pendiente
    $stmtDebt = $pdo->prepare("SELECT d.id, d.pending_payment_json, p.code as prop_code 
                              FROM property_debts d 
                              JOIN properties p ON d.property_id = p.id
                              WHERE d.fee_id = ? AND d.property_id = ?");
    $stmtDebt->execute([$data['feeId'], $data['propertyId']]);
    $debt = $stmtDebt->fetch();

    if (!$debt || !$debt['pending_payment_json']) {
        throw new Exception("No existe un reporte pendiente para esta unidad.");
    }

    $report = json_decode($debt['pending_payment_json'], true);
    
    // 2. Variables del Reporte
    $montoBs = (float)$report['amountBs'];
    $montoUsd = (float)$report['amount'];
    $method = $report['method'];
    $ref = $report['reference'];
    $pDate = $report['date'];
    $propCode = $debt['prop_code'];

    // 3. INTEGRACIÓN CON LIBRO DE BANCO (Si no es efectivo)
    if (stripos($method, 'Efectivo') === false) {
        // Ingreso
        $bankIn = $pdo->prepare("INSERT INTO bank_transactions (date, description, amount_usd, amount_bs, type, category, reference) VALUES (?, ?, ?, ?, 'Ingreso', 'Ingresos', ?)");
        $bankIn->execute([$pDate, "LIQUIDACIÓN REPORTE UNIDAD: $propCode", $montoUsd, $montoBs, $ref]);

        // Comisión Bancaria Automática
        $stmtSet = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'bank_comm_income'");
        $stmtSet->execute();
        $pct = (float)($stmtSet->fetchColumn() ?: 1.5);
        if ($pct > 0) {
            $commBs = round(($montoBs * $pct) / 100, 2);
            $appliedRate = ($montoUsd > 0) ? ($montoBs / $montoUsd) : 45.0;
            $commUsd = round($commBs / $appliedRate, 2);
            $pdo->prepare("INSERT INTO bank_transactions (date, description, amount_usd, amount_bs, type, category, reference) VALUES (?, ?, ?, ?, 'Egreso', 'Comisiones', ?)")
                ->execute([$pDate, "COMISIÓN VALIDACIÓN UNIDAD: $propCode", $commUsd, $commBs, $ref]);
        }
    }

    // 4. REGISTRO EN RECIBO Y ACTUALIZACIÓN DE ESTATUS
    $pdo->prepare("INSERT INTO payments (debt_id, amount_usd, method, reference, payment_date) VALUES (?, ?, ?, ?, ?)")
        ->execute([$debt['id'], $montoUsd, $method, $ref, $pDate]);

    // Recalcular pagado real
    $stmtSum = $pdo->prepare("SELECT SUM(amount_usd) FROM payments WHERE debt_id = ?");
    $stmtSum->execute([$debt['id']]);
    $totalPagado = (float)$stmtSum->fetchColumn();

    $stmtTotal = $pdo->prepare("SELECT amount_usd FROM property_debts WHERE id = ?");
    $stmtTotal->execute([$debt['id']]);
    $deudaMes = (float)$stmtTotal->fetchColumn();

    $newStatus = ($totalPagado >= ($deudaMes - 0.01)) ? 'Pagado' : 'Parcial';

    $pdo->prepare("UPDATE property_debts SET paid_amount = ?, status = ?, pending_payment_json = NULL WHERE id = ?")
        ->execute([$totalPagado, $newStatus, $debt['id']]);

    $pdo->commit();
    logSystemAction("VALIDÓ REPORTE DE PAGO: Unidad $propCode por $$montoUsd", "PAGOS");
    response(["success" => true]);

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