<?php
/**
 * SAC 2026 - BANK RECONCILIATION ENGINE v1.0
 * Arquitecto: Andres Mathison
 * Objetivo: Realizar cruce de referencias entre CSV de Banplus y reportes de vecinos.
 */
require_once 'config.php';

if (!isset($_SESSION['user_id'])) response(["error" => "No autorizado"], 401);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $content = file_get_contents($file['tmp_name']);
    $lines = explode("\n", $content);
    
    if (count($lines) < 3) response(["error" => "Archivo CSV insuficiente"], 400);

    // 1. Obtener reportes de pago PENDIENTES de propietarios
    $stmtPending = $pdo->query("SELECT d.id as debt_id, d.fee_id, d.property_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.pending_payment_json IS NOT NULL");
    $pendingReports = $stmtPending->fetchAll();
    
    $reportsMap = [];
    foreach ($pendingReports as $pr) {
        $json = json_decode($pr['pending_payment_json'], true);
        if ($json && isset($json['reference'])) {
            $ref = trim($json['reference']);
            $reportsMap[$ref] = [
                "debt_id" => $pr['debt_id'],
                "fee_id" => $pr['fee_id'],
                "property_id" => $pr['property_id'],
                "propertyCode" => $pr['prop_code'],
                "amount" => $json['amount'],
                "amountBs" => $json['amountBs'],
                "fullName" => $json['fullName'] ?? 'Titular',
                "date" => $json['date']
            ];
        }
    }

    // 2. Procesar CSV Bancario
    $matches = [];
    $unmatched_bank = [];
    $matchedRefs = [];

    $cleanNum = function($str) {
        $str = trim($str);
        if (empty($str)) return 0.0;
        $str = str_replace(".", "", $str);
        $str = str_replace(",", ".", $str);
        return (float)$str;
    };

    for ($i = 2; $i < count($lines); $i++) {
        $line = trim($lines[$i]);
        if (empty($line)) continue;

        $cols = explode(";", $line);
        if (count($cols) < 5) continue;

        $fecha = $cols[0];
        $ref = ltrim(trim($cols[1]), "'");
        $desc = strtoupper(trim($cols[2]));
        $debito = $cleanNum($cols[3]);
        $credito = $cleanNum($cols[4]);
        
        $bankLine = [
            "date" => $fecha,
            "ref" => $ref,
            "desc" => $desc,
            "credit" => $credito,
            "debit" => $debito
        ];

        if (isset($reportsMap[$ref]) && $credito > 0) {
            $matches[] = [
                "bank_line" => $bankLine,
                "report_data" => $reportsMap[$ref]
            ];
            $matchedRefs[] = $ref;
        } else {
            // Ignorar comisiones en el listado de "no identificados" si su referencia ya fue matcheada
            // o si es una comision P2C obvia
            if (strpos($desc, 'COMISION') === false || !in_array($ref, $matchedRefs)) {
                $unmatched_bank[] = $bankLine;
            }
        }
    }

    // 3. Reportes que están en el sistema pero NO en el banco (Posibles falsos)
    $unmatched_reports = [];
    foreach ($reportsMap as $ref => $data) {
        if (!in_array($ref, $matchedRefs)) {
            $unmatched_reports[] = array_merge($data, ["ref" => $ref]);
        }
    }

    response([
        "success" => true,
        "summary" => [
            "matched" => count($matches),
            "unmatched_bank" => count($unmatched_bank),
            "unmatched_reports" => count($unmatched_reports)
        ],
        "matches" => $matches,
        "unmatched_bank" => $unmatched_bank,
        "unmatched_reports" => $unmatched_reports
    ]);

} else {
    response(["error" => "No file"], 400);
}
?>