<?php
require_once '../../connections/meekro/db.class.php';

$currentMonth = $_GET['month'] ?? date('n');
$currentYear  = $_GET['year'] ?? date('Y');

try {
    // Fetch the overall totals
    $totals = DB::queryFirstRow("
        SELECT 
            SUM(no_declaration) AS total_declarations,
            SUM(no_containers) AS total_containers,
            SUM(revenue_generated) AS total_generated,
            SUM(revenue_collected) AS total_collected
        FROM fast_track
        WHERE YEAR(transaction_date) = '$currentYear'
    ");

    // Fetch monthly totals
    $monthly = DB::query("
        SELECT 
            DATE_FORMAT(transaction_date, '%b') AS month,
            SUM(revenue_collected) AS total_collected,
            SUM(no_declaration) AS total_declarations,
            SUM(no_containers) AS total_containers
        FROM fast_track
        WHERE YEAR(transaction_date) = '$currentYear'
        GROUP BY month
        ORDER BY month ASC
    ");

    // Output response as JSON
    header('Content-Type: application/json');
    echo json_encode([
        "totals" => $totals,
        "monthly" => $monthly
    ]);

} catch (Exception $e) {
    echo json_encode(["error" => "Database error: " . $e->getMessage()]);
}
?>
