<?php
/* ============================================================
   _bootstrap.php - shared setup for every api/*.php endpoint
   ============================================================ */

require __DIR__ . '/../config.php';
require __DIR__ . '/../db.php';

header('Content-Type: application/json');

function respond($arr, $code = 200) {
    http_response_code($code);
    echo json_encode($arr);
    exit;
}

// --- API key check ---
$headers = function_exists('getallheaders') ? getallheaders() : [];
$apiKey = '';
foreach ($headers as $k => $v) {
    if (strtolower($k) === 'x-api-key') { $apiKey = $v; break; }
}
if ($apiKey === '' && isset($_SERVER['HTTP_X_API_KEY'])) $apiKey = $_SERVER['HTTP_X_API_KEY'];

if (!hash_equals(LICENSE_API_KEY, (string) $apiKey)) {
    respond(['valid' => false, 'message' => 'Unauthorized'], 401);
}

// --- JSON body ---
$GLOBALS['__input'] = json_decode(file_get_contents('php://input'), true) ?: [];

function input($key, $default = '') {
    $v = $GLOBALS['__input'][$key] ?? $default;
    return is_string($v) ? trim($v) : $v;
}
