<?php
// db/search-growth-periods.php
header('Content-Type: application/json; charset=utf-8');

// CORRECCIÓN ÚNICA: Iniciar sesión
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// MANTENEMOS TU ESTRUCTURA ORIGINAL
require_once __DIR__ . '/../core/api.php';

$user_id = $_SESSION['user_id'] ?? 1;
$q = $_GET['q'] ?? '';

$months_es = [
    1 => 'Enero', 2 => 'Febrero', 3 => 'Marzo', 4 => 'Abril', 5 => 'Mayo', 6 => 'Junio',
    7 => 'Julio', 8 => 'Agosto', 9 => 'Septiembre', 10 => 'Octubre', 11 => 'Noviembre', 12 => 'Diciembre'
];

if (strlen($q) < 1) {
    $results = [];
    for ($i = 0; $i < 6; $i++) {
        $time = strtotime("-$i months");
        $key = date('Y-m', $time);
        $label = $months_es[intval(date('m', $time))] . ' ' . date('Y', $time);
        $results[] = ['id' => $key, 'name' => $label, 'type' => 'period'];
    }
    echo json_encode($results);
    exit;
}

$results = [];
$years = [date('Y'), date('Y', strtotime('-1 year'))];

foreach ($years as $y) {
    foreach ($months_es as $mNum => $mName) {
        $term = $mName . " " . $y;
        if (stripos($term, $q) !== false) {
            $key = $y . '-' . str_pad((string)$mNum, 2, '0', STR_PAD_LEFT);
            $results[] = [
                'id' => $key, 
                'name' => $term, 
                'type' => 'period',
                'detail' => 'Reporte Mensual'
            ];
        }
    }
}

echo json_encode($results);
?>