<?php
/**
 * SAC 2026 - STATEMENT PROCESSING UTILITY
 * Arquitecto: Andres Mathison
 * Esta utilidad permite parsear un CSV de Banesco y devolverlo como JSON limpio.
 */
require_once 'config.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['statement'])) {
    $file = $_FILES['statement'];
    $handle = fopen($file['tmp_name'], 'r');
    
    $metadata = [];
    $movements = [];
    $section = '';

    while (($line = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $firstCol = trim($line[0] ?? '');
        
        if (strpos($firstCol, '# METADATOS') !== false) {
            $section = 'meta';
            continue;
        }
        if (strpos($firstCol, '# DETALLE DE MOVIMIENTOS') !== false) {
            $section = 'movements';
            continue;
        }

        if ($section === 'meta' && count($line) >= 2) {
            $metadata[$line[0]] = $line[1];
        }

        if ($section === 'movements') {
            if ($firstCol === 'Fecha' || empty($firstCol)) continue;
            if (stripos($line[2], 'SALDO INICIAL') !== false) continue;

            $movements[] = [
                "fecha" => $line[0],
                "referencia" => $line[1],
                "concepto" => $line[2],
                "cargo" => (float)$line[3],
                "abono" => (float)$line[4],
                "saldo" => (float)$line[5]
            ];
        }
    }
    fclose($handle);

    response([
        "success" => true,
        "metadata" => $metadata,
        "movements" => $movements
    ]);
} else {
    response(["error" => "Archivo no recibido"], 400);
}
?>