<?php
/**
 * SAC 2026 - BNC RECONCILIATION CORE v1.0
 * Arquitecto: Andres Mathison
 * Objetivo: Cruce de datos entre SAC 2026 y estado de cuenta BNC TXT.
 * Identifica omisiones en el sistema administrativo.
 */
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'];
    $month = (int)$_POST['month'];
    $year = (int)$_POST['year'];
    
    $content = file_get_contents($file['tmp_name']);
    $lines = explode("\n", $content);
    
    // 1. Obtener movimientos registrados en SAC para ese mes/año (BNC)
    $stmt = $pdo->prepare("
        SELECT reference, amount_bs, date 
        FROM bank_movements 
        WHERE bank = 'BNC' 
        AND MONTH(date) = ? 
        AND YEAR(date) = ?
    ");
    $stmt->execute([$month, $year]);
    $sacMovements = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 2. Obtener pagos registrados en SAC que vinieron de BNC
    $stmt = $pdo->prepare("
        SELECT reference, amount_bs, date 
        FROM payments 
        WHERE method LIKE '%BNC%' 
        AND MONTH(date) = ? 
        AND YEAR(date) = ?
    ");
    $stmt->execute([$month, $year]);
    $sacPayments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Combinar para tener el rastro completo en SAC
    $sacRefs = [];
    foreach ($sacMovements as $m) $sacRefs[] = (string)$m['reference'];
    foreach ($sacPayments as $p) $sacRefs[] = (string)$p['reference'];
    
    $sacRefs = array_unique($sacRefs);

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

    // 3. Procesar TXT BNC
    foreach ($lines as $line) {
        $line = trim($line);
        if (preg_match('/^(\d{2}\/\d{2}\/\d{4})\s+(.+?)\s+(-?[\d\.,]+)\s+(-?[\d\.,]+)$/', $line, $matches)) {
            $date = $matches[1];
            $fullDesc = trim($matches[2]);
            $monto = $cleanNum($matches[3]);

            $ref = "S/R";
            if (preg_match('/#(\d+)/', $fullDesc, $refMatches)) $ref = $refMatches[1];
            elseif (preg_match('/REF:\s*(\d+)/', $fullDesc, $refMatches)) $ref = $refMatches[1];

            $bncMovements[] = [
                "date" => $date,
                "ref" => $ref,
                "desc" => $fullDesc,
                "amount" => abs($monto),
                "type" => ($monto > 0) ? 'INGRESO' : 'EGRESO'
            ];
        }
    }

    // 4. Realizar el Cruce (Conciliación)
    $missing = [];
    $matchedCount = 0;

    foreach ($bncMovements as $bm) {
        $found = false;
        foreach ($sacRefs as $sr) {
            // Match por referencia completa o últimos 8 dígitos
            if ($bm['ref'] === $sr || (strlen($bm['ref']) >= 8 && strlen($sr) >= 8 && substr($bm['ref'], -8) === substr($sr, -8))) {
                $found = true;
                break;
            }
        }

        if ($found) {
            $matchedCount++;
        } else {
            // Omitir comisiones del reporte de omisiones si se desea un reporte más limpio, 
            // pero aquí las incluiremos para auditoría total.
            $missing[] = $bm;
        }
    }

    response([
        "success" => true,
        "summary" => [
            "total_processed" => count($bncMovements),
            "matched" => $matchedCount,
            "unmatched" => count($missing)
        ],
        "missing" => $missing
    ]);

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