<?php
function json_response($data, int $status = 200): never {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}
function input_json(): array {
    $raw = file_get_contents('php://input');
    if (!$raw) return [];
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}
function bearer_token(): ?string {
    $h = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    return preg_match('/Bearer\s+(\S+)/i', $h, $m) ? $m[1] : null;
}
function require_admin(): array {
    $token = bearer_token();
    if (!$token) json_response(['message'=>'Unauthorized'], 401);
    $s = db()->prepare('SELECT id,name,email FROM admins WHERE token=? LIMIT 1');
    $s->execute([$token]);
    $admin = $s->fetch();
    if (!$admin) json_response(['message'=>'Unauthorized'], 401);
    return $admin;
}
function clean_string($v, int $max = 255): string {
    return mb_substr(trim((string)$v), 0, $max);
}
