<?php
// ============================================================
// bootstrap.php — included at the top of EVERY endpoint file
// Each endpoint is a standalone PHP file — no router needed.
// ============================================================

ob_start();
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');

// CORS — always first
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, Accept");
header("Access-Control-Max-Age: 86400");
header("Content-Type: application/json; charset=UTF-8");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    ob_end_clean();
    http_response_code(204);
    exit();
}

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../config/database.php';

// ── Shared helpers ──────────────────────────────────────────
$method = $_SERVER['REQUEST_METHOD'];
// Merge JSON body + $_POST so endpoints work with both FormData and JSON
$_jsonBody = json_decode(file_get_contents('php://input'), true) ?? [];
$input = !empty($_POST) ? array_merge($_jsonBody, $_POST) : $_jsonBody;
// $uri is available for endpoints that inspect the URL path
// When called as auth.php?route=/auth/login, use the route param
$uri = isset($_GET['route']) ? '/' . ltrim($_GET['route'], '/') : ($_SERVER['REQUEST_URI'] ?? '/');

function getBearerToken(): ?string {
    $auth = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    if (!$auth) $auth = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
    if (!$auth && function_exists('apache_request_headers')) {
        $h = apache_request_headers();
        $auth = $h['Authorization'] ?? $h['authorization'] ?? '';
    }
    if (preg_match('/Bearer\s+(.+)$/i', $auth, $m)) return trim($m[1]);
    return null;
}

function verifyJWT(string $token): ?array {
    $parts = explode('.', $token);
    if (count($parts) !== 3) return null;
    [$h, $p, $sig] = $parts;
    $expected = rtrim(strtr(base64_encode(hash_hmac('sha256', "$h.$p", JWT_SECRET, true)), '+/', '-_'), '=');
    if (!hash_equals($expected, $sig)) return null;
    $data = json_decode(base64_decode(strtr($p, '-_', '+/')), true);
    if (!$data || (isset($data['exp']) && $data['exp'] < time())) return null;
    return $data;
}

function createJWT(array $payload): string {
    $h   = rtrim(strtr(base64_encode(json_encode(['alg'=>'HS256','typ'=>'JWT'])), '+/', '-_'), '=');
    $payload['exp'] = time() + SESSION_LIFETIME;
    $payload['iat'] = time();
    $p   = rtrim(strtr(base64_encode(json_encode($payload)), '+/', '-_'), '=');
    $sig = rtrim(strtr(base64_encode(hash_hmac('sha256', "$h.$p", JWT_SECRET, true)), '+/', '-_'), '=');
    return "$h.$p.$sig";
}

function requireAuth(): array {
    $token = getBearerToken();
    if (!$token) jsonError('Unauthorized. Please log in.', 401);
    $data = verifyJWT($token);
    if (!$data) jsonError('Session expired. Please log in again.', 401);
    $db   = Database::getInstance();
    $user = $db->fetch("SELECT id,status FROM users WHERE id=? LIMIT 1", [$data['user_id']]);
    if (!$user || $user['status'] === 'banned') jsonError('Account access denied.', 403);
    return $data;
}

function requireAdmin(): array {
    $token = getBearerToken();
    if (!$token) jsonError('Unauthorized', 401);
    $data = verifyJWT($token);
    if (!$data || !isset($data['admin_id'])) jsonError('Admin access required', 401);
    return $data;
}

function jsonSuccess($data = [], string $message = 'Success'): void {
    ob_end_clean();
    echo json_encode(['success'=>true,'message'=>$message,'data'=>$data]);
    exit();
}

function jsonError(string $message, int $code = 400): void {
    ob_end_clean();
    http_response_code($code);
    echo json_encode(['success'=>false,'message'=>$message]);
    exit();
}

function sanitize($val): string {
    return htmlspecialchars(trim((string)$val), ENT_QUOTES, 'UTF-8');
}

function methodIs(string $m): bool {
    return $_SERVER['REQUEST_METHOD'] === strtoupper($m);
}
