<?php
// JWT helper leger (HS256) sans dependance externe.

$appConfigPath = __DIR__ . '/app_config.php';
$appConfig = [];

if (is_file($appConfigPath)) {
    $loaded = require $appConfigPath;
    if (is_array($loaded)) {
        $appConfig = $loaded;
    }
}

$jwtSecret = $appConfig['jwt_secret'] ?? getenv('JWT_SECRET') ?: '';
$jwtExpires = (int)($appConfig['jwt_expires'] ?? getenv('JWT_EXPIRES') ?: (7 * 24 * 3600));

if (!$jwtSecret) {
    http_response_code(500);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['message' => 'Configuration JWT manquante.']);
    exit;
}

define('JWT_SECRET', $jwtSecret);
define('JWT_EXPIRES', $jwtExpires);

function base64url_encode(string $data): string {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode(string $data): string {
    return base64_decode(strtr($data, '-_', '+/') . str_repeat('=', 3 - (3 + strlen($data)) % 4));
}

function generateJWT(array $payload): string {
    $header = base64url_encode(json_encode(['alg' => 'HS256', 'typ' => 'JWT']));
    $payload['iat'] = time();
    $payload['exp'] = time() + JWT_EXPIRES;
    $body = base64url_encode(json_encode($payload));
    $sig = base64url_encode(hash_hmac('sha256', "$header.$body", JWT_SECRET, true));
    return "$header.$body.$sig";
}

function verifyJWT(string $token): ?array {
    $parts = explode('.', $token);
    if (count($parts) !== 3) return null;
    [$header, $body, $sig] = $parts;

    $expected = base64url_encode(hash_hmac('sha256', "$header.$body", JWT_SECRET, true));
    if (!hash_equals($expected, $sig)) return null;

    $payload = json_decode(base64url_decode($body), true);
    if (!$payload || $payload['exp'] < time()) return null;

    return $payload;
}

// Middleware auth : renvoie l'user_id ou repond 401.
function requireAuth(): int {
    $headers = getallheaders();
    $auth = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    $token = '';

    if (preg_match('/Bearer\s+(.+)/i', $auth, $m)) {
        $token = $m[1];
    }

    if (!$token) {
        http_response_code(401);
        echo json_encode(['message' => 'Token manquant']);
        exit;
    }

    $payload = verifyJWT($token);
    if (!$payload) {
        http_response_code(401);
        echo json_encode(['message' => 'Token invalide ou expire']);
        exit;
    }

    return (int) $payload['id'];
}
