<?php
require 'db.php';

$stmt = $pdo->query("
    SELECT DISTINCT 
        MONTH(inv_date) AS month,
        YEAR(inv_date) AS year
    FROM transactions
");

$existingMonths = [];
$years = [];

// Collect existing months & years
while ($row = $stmt->fetch()) {

    if (!in_array($row['month'], $existingMonths)) {
        $existingMonths[] = (int)$row['month'];
    }

    if (!in_array($row['year'], $years)) {
        $years[] = (int)$row['year'];
    }
}

// Sort years ASC (or DESC if you prefer)
sort($years);

// Build months Jan → Dec (only if exists)
$months = [];
for ($m = 1; $m <= 12; $m++) {
    if (in_array($m, $existingMonths)) {
        $months[] = [
            'value' => $m,
            'label' => date('F', mktime(0, 0, 0, $m, 1))
        ];
    }
}

echo json_encode([
    'months' => $months,
    'years'  => $years
]);
