<?php
/**
 * SAC 2026 - BANK ENGINE v10.0 (AUTO-CLOSE/OPEN)
 * Arquitecto: Andres Mathison
 * Esta API gestiona automáticamente los asientos de cierre y apertura.
 */
require_once 'config.php';

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

$role = $_SESSION['user_role'];

/**
 * MOTOR DE AUTO-CONCILIACIÓN MENSUAL
 * Verifica y genera asientos de cierre/apertura si faltan.
 */
function ensureMonthlyMarkers($pdo) {
    $now = new DateTime();
    $currentMonth = (int)$now->format('m');
    $currentYear = (int)$now->format('Y');

    // Retroceder un mes para verificar el cierre del anterior
    $prevDate = clone $now;
    $prevDate->modify('first day of last month');
    $pM = (int)$prevDate->format('m');
    $pY = (int)$prevDate->format('Y');

    $refCierre = "CIERRE-" . str_pad($pM, 2, '0', STR_PAD_LEFT) . "-$pY";
    $refInicio = "INICIO-" . str_pad($currentMonth, 2, '0', STR_PAD_LEFT) . "-$currentYear";

    // 1. Verificar si ya existen
    $stmt = $pdo->prepare("SELECT reference FROM bank_transactions WHERE reference IN (?, ?)");
    $stmt->execute([$refCierre, $refInicio]);
    $existing = $stmt->fetchAll(PDO::FETCH_COLUMN);

    // 2. Si falta el cierre del mes anterior, calcular y generar
    if (!in_array($refCierre, $existing)) {
        // Calcular saldo exacto hasta el último segundo del mes anterior
        $lastDayPrev = $prevDate->format('Y-m-t');
        
        // Sumamos todo lo anterior a ese mes (excluyendo otros cierres/inicios para no duplicar)
        $stmtBalance = $pdo->prepare("SELECT 
                                        SUM(CASE WHEN type = 'Ingreso' THEN amount_usd ELSE -amount_usd END) as saldo_usd,
                                        SUM(CASE WHEN type = 'Ingreso' THEN amount_bs ELSE -amount_bs END) as saldo_bs
                                      FROM bank_transactions 
                                      WHERE date <= ? AND category != 'Cierre/Apertura'");
        $stmtBalance->execute([$lastDayPrev]);
        $balance = $stmtBalance->fetch();
        
        $sUsd = (float)($balance['saldo_usd'] ?? 0);
        $sBs = (float)($balance['saldo_bs'] ?? 0);

        // Insertar Cierre (Ultimo día del mes pasado)
        $insC = $pdo->prepare("INSERT INTO bank_transactions (date, description, amount_usd, amount_bs, type, category, reference) VALUES (?, ?, ?, ?, 'Ingreso', 'Cierre/Apertura', ?)");
        $insC->execute([$lastDayPrev, "CIERRAME AUTOMÁTICO - PERIODO $pM/$pY", $sUsd, $sBs, $refCierre]);
        
        // Insertar Inicio (Día 1 del mes actual)
        $firstDayCur = $now->format('Y-m-01');
        $insI = $pdo->prepare("INSERT INTO bank_transactions (date, description, amount_usd, amount_bs, type, category, reference) VALUES (?, ?, ?, ?, 'Ingreso', 'Cierre/Apertura', ?)");
        $insI->execute([$firstDayCur, "INICIO AUTOMÁTICO - PERIODO $currentMonth/$currentYear", $sUsd, $sBs, $refInicio]);
    }
}

try {
    // Ejecutar mantenimiento preventivo de asientos
    if (in_array($role, ['admin', 'programmer', 'board'])) {
        ensureMonthlyMarkers($pdo);
    }

    if (in_array($role, ['admin', 'programmer', 'board'])) {
        $stmt = $pdo->query("SELECT id, date, description, category, type, amount_usd as amount, amount_bs as amountBs, reference FROM bank_transactions ORDER BY date DESC, id DESC");
    } else {
        // Propietarios ven solo ingresos, omitiendo asientos administrativos de cierre
        $stmt = $pdo->query("SELECT id, date, 'Recaudación Condominio' as description, 'Ingresos' as category, type, amount_usd as amount FROM bank_transactions WHERE type = 'Ingreso' AND category != 'Cierre/Apertura' ORDER BY date DESC LIMIT 100");
    }
    response($stmt->fetchAll());
} catch (PDOException $e) {
    response(["error" => "Error en motor de banco"], 500);
}
?>