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

$currentMonth = $_GET['month'] ?? date('n');
$currentYear  = $_GET['year'] ?? date('Y');
$currentMonth = 5;
try {
    // Fetch all entries for the current month/year
    $results = DB::query("
        SELECT 
            transaction_date,
            revenue_collected,
            no_declaration,
            no_containers
        FROM fast_track
         WHERE MONTH(transaction_date) = '$currentMonth' AND YEAR(transaction_date) = '$currentYear'
        ORDER BY transaction_date ASC
    ", $currentMonth, $currentYear);

    // Group data by ISO week
    $weeks = [];

    foreach ($results as $row) {
        $date = $row['transaction_date'];
        $week = date('W', strtotime($date)); // ISO week number
        $yearWeekKey = date('o', strtotime($date)) . '-W' . $week;

        if (!isset($weeks[$yearWeekKey])) {
            $weeks[$yearWeekKey] = [
                'week_number' => $week,
                'dates' => [],
                'total_collected' => 0,
                'total_declarations' => 0,
                'total_containers' => 0
            ];
        }

        $weeks[$yearWeekKey]['dates'][] = $date;
        $weeks[$yearWeekKey]['total_collected'] += (float) $row['revenue_collected'];
        $weeks[$yearWeekKey]['total_declarations'] += (int) $row['no_declaration'];
        $weeks[$yearWeekKey]['total_containers'] += (int) $row['no_containers'];
    }

    // Build structured response
    $response = [];
    foreach ($weeks as $weekData) {
        $startDate = min($weekData['dates']);
        $endDate   = max($weekData['dates']);

        $response[] = [
            'week_number'        => $weekData['week_number'],
            'week_range'         => date('d/m/y', strtotime($startDate)) . ' - ' . date('d/m/y', strtotime($endDate)),
            'total_collected'    => $weekData['total_collected'],
            'total_declarations' => $weekData['total_declarations'],
            'total_containers'   => $weekData['total_containers']
        ];
    }

    header('Content-Type: application/json');
    echo json_encode($response);
} catch (Exception $e) {
    echo json_encode(["error" => "Database error: " . $e->getMessage()]);
}
