<?php
/**
 * SAC 2026 - RECONCILIATION ENGINE v1.0 (BANCO VS BANCO)
 * Arquitecto: Andres Mathison
 * Objetivo: Identificar operaciones físicas NO registradas en el sistema.
 */
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 todas las transacciones internas del sistema para el cruce
    // Traemos el universo filtrado por mes/año si se especifica para mayor precisión
    $month = isset($_POST['month']) ? (int)$_POST['month'] : null;
    $year = isset($_POST['year']) ? (int)$_POST['year'] : null;

    $params = [];
    $query = "SELECT reference, amount_bs, type FROM bank_transactions WHERE category != 'Cierre/Apertura'";
    if ($month && $year) {
        $query .= " AND MONTH(date) = ? AND YEAR(date) = ?";
        $params = [$month, $year];
    }
    
    $stmtInternal = $pdo->prepare($query);
    $stmtInternal->execute($params);
    $internalRows = $stmtInternal->fetchAll();
    
    // Crear un mapa de búsqueda rápida por Referencia y Monto
    $internalMap = [];
    foreach ($internalRows as $ir) {
        $key = trim($ir['reference']) . "_" . round(abs((float)$ir['amount_bs']), 2);
        $internalMap[$key] = true;
    }

    // 2. Procesar CSV Externo
    $missingInSystem = [];
    $totalFound = 0;
    $totalMissing = 0;

    $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 = str_replace("'", "", trim($cols[1]));
        $desc = strtoupper(trim($cols[2]));
        $debito = $cleanNum($cols[3]);
        $credito = $cleanNum($cols[4]);
        
        $montoNominal = ($credito > 0) ? $credito : $debito;
        $searchKey = $ref . "_" . round($montoNominal, 2);

        if (isset($internalMap[$searchKey])) {
            $totalFound++;
        } else {
            // No existe en el sistema SAC 2026
            $missingInSystem[] = [
                "date" => $fecha,
                "ref" => $ref,
                "desc" => $desc,
                "amount" => $montoNominal,
                "type" => ($credito > 0) ? 'INGRESO' : 'EGRESO'
            ];
            $totalMissing++;
        }
    }

    logSystemAction("EJECUTÓ CONCILIACIÓN BANCO VS BANCO. Detectadas $totalMissing omisiones.", "AUDITORIA");

    response([
        "success" => true,
        "summary" => [
            "total_processed" => count($lines) - 2,
            "matched" => $totalFound,
            "unmatched" => $totalMissing
        ],
        "missing" => $missingInSystem
    ]);

} else {
    response(["error" => "No se recibió el archivo de conciliación"], 400);
}
?>