<?php
/**
 * SAC 2026 - RESERVE FUND HISTORY v1.0
 * Kernel V4.1.00
 * Calculates monthly accumulation of the reserve fund.
 */
require_once 'config.php';

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

$startDate = $_GET['start'] ?? null;
$endDate = $_GET['end'] ?? null;

try {
    // 1. Get Initial Balance from Settings
    $stmtSettings = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'initial_reserve_bs'");
    $stmtSettings->execute();
    $initialReserveBs = (float)($stmtSettings->fetchColumn() ?: 0);

    // 2. Get Monthly Accumulation
    $query = "SELECT 
                f.month,
                f.year,
                f.exchange_rate,
                f.reserve_fund_percent,
                SUM(i.amount_usd) as total_items_usd,
                (SUM(i.amount_usd) * (f.reserve_fund_percent / 100)) as monthly_reserve_usd,
                ( (SUM(i.amount_usd) * (f.reserve_fund_percent / 100)) * f.exchange_rate ) as monthly_reserve_bs
              FROM monthly_fees f
              JOIN monthly_fee_items i ON f.id = i.fee_id
              GROUP BY f.year, f.month
              ORDER BY f.year ASC, f.month ASC";
    
    $stmt = $pdo->query($query);
    $history = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $runningTotalBs = $initialReserveBs;
    $reportData = [];

    // Add Initial Balance as first entry
    $reportData[] = [
        "period" => "Saldo Inicial",
        "monthly_bs" => 0,
        "monthly_usd" => 0,
        "accumulated_bs" => $initialReserveBs,
        "accumulated_usd" => 0 // Will calculate based on current rate later if needed
    ];

    foreach ($history as $row) {
        $period = $row['month'] . '/' . $row['year'];
        
        // Filter by date if provided
        $itemDate = date('Y-m-d', strtotime($row['year'] . '-' . $row['month'] . '-01'));
        
        $runningTotalBs += (float)$row['monthly_reserve_bs'];
        
        $reportData[] = [
            "period" => $period,
            "monthly_bs" => (float)$row['monthly_reserve_bs'],
            "monthly_usd" => (float)$row['monthly_reserve_usd'],
            "accumulated_bs" => $runningTotalBs,
            "accumulated_usd" => (float)$row['monthly_reserve_usd'] // This is just the monthly part in USD
        ];
    }

    // Filter the final report data by the requested range if applicable
    if ($startDate && $endDate) {
        // We keep the running total logic but filter the output
        $filteredData = [];
        foreach ($reportData as $item) {
            if ($item['period'] === "Saldo Inicial") {
                $filteredData[] = $item;
                continue;
            }
            $parts = explode('/', $item['period']);
            $itemDate = $parts[1] . '-' . str_pad($parts[0], 2, '0', STR_PAD_LEFT) . '-01';
            if ($itemDate >= substr($startDate, 0, 7) . '-01' && $itemDate <= substr($endDate, 0, 7) . '-31') {
                $filteredData[] = $item;
            }
        }
        $reportData = $filteredData;
    }

    response([
        "initial_balance_bs" => $initialReserveBs,
        "history" => $reportData,
        "kernel_version" => "V4.1.00"
    ]);

} catch (PDOException $e) {
    response(["error" => "Fallo en reporte de reserva: " . $e->getMessage()], 500);
}
?>