<?php
function jsonResponse($status, $payload)
{
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($payload, JSON_UNESCAPED_UNICODE);
    exit;
}

function getPdo($config, $key)
{
    $db = $config[$key];
    $dsn = "mysql:host={$db['host']};dbname={$db['db']};charset=utf8mb4";
    $pdo = new PDO($dsn, $db['user'], $db['pass'], [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
    return $pdo;
}

function requireDate($date)
{
    $dt = DateTime::createFromFormat('Y-m-d', $date);
    if ($dt === false || $dt->format('Y-m-d') !== $date) {
        jsonResponse(400, ['success' => false, 'message' => 'Date invalide']);
    }
    return $date;
}

function requireType($type)
{
    $map = ['Bus' => 'Bus', 'Taxi' => 'Taxi', 'bus' => 'Bus', 'taxi' => 'Taxi'];
    if (!isset($map[$type])) {
        jsonResponse(400, ['success' => false, 'message' => 'Type invalide']);
    }
    return $map[$type];
}

function requireCategory($category, $allowed)
{
    if (!in_array($category, $allowed, true)) {
        jsonResponse(400, ['success' => false, 'message' => 'Catégorie invalide']);
    }
    return $category;
}

function requireMonthYear($month, $year)
{
    if ($month === null || $year === null) {
        jsonResponse(400, ['success' => false, 'message' => 'Mois et année requis']);
    }
    if (!preg_match('/^\d{2}$/', $month) || (int)$month < 1 || (int)$month > 12) {
        jsonResponse(400, ['success' => false, 'message' => 'Mois invalide']);
    }
    if (!preg_match('/^\d{4}$/', $year) || (int)$year < 2000 || (int)$year > 2100) {
        jsonResponse(400, ['success' => false, 'message' => 'Année invalide']);
    }
    return [$month, $year];
}
