<?php
/**
 * SAC 2026 - BANPLUS DETAILED ANALYTICS v4.0 (CROSS-REF EDITION)
 * Arquitecto: Andres Mathison
 * Objetivo: Procesar CSV detallado con motor de detección de comisiones faltantes.
 */
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" => "Estructura CSV insuficiente"], 400);

    // 1. Extraer Metadatos
    $headerLine = $lines[0];
    $metadata = ["account" => "S/A", "owner" => "S/A"];
    if (preg_match('/Cuenta:\s*(\d+)/', $headerLine, $matches)) $metadata['account'] = $matches[1];
    if (preg_match('/Titular:\s*(.+?)(?=\s*Fecha|$)/', $headerLine, $matches)) $metadata['owner'] = trim($matches[1]);

    // 2. Primer paso: Lectura y carga en memoria
    $rawMovements = [];
    $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) < 9) continue;

        $ref = ltrim(trim($cols[1]), "'");
        $rawMovements[] = [
            "date" => $cols[0],
            "ref" => $ref,
            "trans" => strtoupper(trim($cols[3])),
            "motivo" => strtoupper(trim($cols[5])),
            "debit" => $cleanNum($cols[6]),
            "credit" => $cleanNum($cols[7]),
            "balance" => $cleanNum($cols[8]),
            "channel" => strtoupper(trim($cols[10] ?? 'N/A'))
        ];
    }

    // 3. Segundo paso: Inteligencia de Detección de Comisiones
    $movements = [];
    $stats = [
        "COMISION_BANCARIA" => ["total" => 0, "count" => 0],
        "INGRESOS_OPERATIVOS" => ["total" => 0, "count" => 0],
        "EGRESOS_VARIOS" => ["total" => 0, "count" => 0],
        "OTROS" => ["total" => 0, "count" => 0]
    ];

    foreach ($rawMovements as $m) {
        $isCommission = strpos($m['motivo'], 'COMISION') !== false;
        $monto = ($m['credit'] > 0) ? $m['credit'] : $m['debit'];
        $tipoMov = ($m['credit'] > 0) ? 'INGRESO' : 'EGRESO';
        
        $hasMissingCommission = false;
        // Si es una operación principal, buscamos si tiene comisión en el mismo extracto
        if (!$isCommission && ($m['credit'] > 0 || $m['debit'] > 0)) {
            $foundComm = false;
            foreach ($rawMovements as $other) {
                if ($other['ref'] === $m['ref'] && strpos($other['motivo'], 'COMISION') !== false) {
                    $foundComm = true; break;
                }
            }
            $hasMissingCommission = !$foundComm;
        }

        $catKey = "OTROS";
        if ($isCommission) $catKey = "COMISION_BANCARIA";
        elseif ($m['credit'] > 0) $catKey = "INGRESOS_OPERATIVOS";
        else $catKey = "EGRESOS_VARIOS";

        $movements[] = [
            "date" => $m['date'],
            "ref" => $m['ref'],
            "desc" => $m['trans'] . " - " . $m['motivo'],
            "debit" => $m['debit'],
            "credit" => $m['credit'],
            "balance" => $m['balance'],
            "channel" => $m['channel'],
            "category" => $catKey,
            "type" => $tipoMov,
            "hasMissingCommission" => $hasMissingCommission
        ];

        $stats[$catKey]["total"] += $monto;
        $stats[$catKey]["count"]++;
    }

    $finalBalance = count($movements) > 0 ? $movements[0]['balance'] : 0;
    $lastRow = end($movements);
    $initialBalance = $lastRow['balance'] + $lastRow['debit'] - $lastRow['credit'];

    response([
        "success" => true,
        "metadata" => $metadata,
        "stats" => $stats,
        "audit" => ["initial" => $initialBalance, "final" => $finalBalance],
        "movements" => $movements
    ]);
}
?>