<?php
/**
 * SAC 2026 - BULK APPROVAL RECON v1.0
 * Arquitecto: Andres Mathison
 * Valida masivamente reportes previamente conciliados por referencia bancaria.
 */
require_once 'config.php';

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

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

if (!isset($data['matches']) || !is_array($data['matches'])) {
    response(["error" => "Datos de conciliación faltantes"], 400);
}

try {
    $pdo->beginTransaction();

    foreach ($data['matches'] as $match) {
        $report = $match['report_data'];
        $bank = $match['bank_line'];
        
        $debtId = $report['debt_id'];
        $montoBs = (float)$report['amountBs'];
        $montoUsd = (float)$report['amount'];
        $ref = $bank['ref'];
        $pDate = $bank['date']; // Usamos la fecha real del banco
        $propCode = $report['propertyCode'];

        // 1. REGISTRO EN LIBRO DE BANCO
        $bankIn = $pdo->prepare("INSERT INTO bank_transactions (date, description, amount_usd, amount_bs, type, category, reference) VALUES (?, ?, ?, ?, 'Ingreso', 'Ingresos', ?)");
        $bankIn->execute([$pDate, "CONCILIACIÓN AUTO: UNIDAD $propCode", $montoUsd, $montoBs, $ref]);

        // 2. REGISTRO EN RECIBO
        $pdo->prepare("INSERT INTO payments (debt_id, amount_usd, method, reference, payment_date) VALUES (?, ?, 'Conciliado', ?, ?)")
            ->execute([$debtId, $montoUsd, $ref, $pDate]);

        // 3. ACTUALIZACIÓN DE ESTATUS DE DEUDA
        $stmtSum = $pdo->prepare("SELECT SUM(amount_usd) FROM payments WHERE debt_id = ?");
        $stmtSum->execute([$debtId]);
        $totalPagado = (float)$stmtSum->fetchColumn();

        $stmtTotal = $pdo->prepare("SELECT amount_usd FROM property_debts WHERE id = ?");
        $stmtTotal->execute([$debtId]);
        $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, $debtId]);
    }

    $pdo->commit();
    logSystemAction("VALÍDÓ MASIVAMENTE " . count($data['matches']) . " reportes vía conciliación bancaria.", "AUDITORIA");
    response(["success" => true]);

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