<?php
/**
 * Gestion de l'authentification JWT
 */

require_once __DIR__ . '/config.php';

/**
 * Générer un token JWT
 */
function generateToken($userId, $matricule) {
    $payload = [
        'iat' => time(),
        'exp' => time() + JWT_EXPIRY,
        'user_id' => $userId,
        'matricule' => $matricule
    ];

    $header = base64_encode(json_encode(['typ' => 'JWT', 'alg' => 'HS256']));
    $payloadEncoded = base64_encode(json_encode($payload));
    $signature = base64_encode(hash_hmac('sha256', "$header.$payloadEncoded", JWT_SECRET, true));

    return "$header.$payloadEncoded.$signature";
}

/**
 * Vérifier et décoder un token JWT
 */
function verifyToken($token) {
    $parts = explode('.', $token);
    if (count($parts) !== 3) {
        return null;
    }

    [$header, $payload, $signature] = $parts;

    // Vérifier la signature
    $expectedSignature = base64_encode(hash_hmac('sha256', "$header.$payload", JWT_SECRET, true));
    if ($signature !== $expectedSignature) {
        return null;
    }

    $payloadData = json_decode(base64_decode($payload), true);
    if (!$payloadData || !isset($payloadData['exp'])) {
        return null;
    }

    // Vérifier l'expiration
    if ($payloadData['exp'] < time()) {
        return null;
    }

    return $payloadData;
}

/**
 * Extraire le token du header Authorization
 */
function getTokenFromHeader() {
    // Essayer d'abord $_SERVER['HTTP_AUTHORIZATION'] (via .htaccess RewriteRule)
    $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';

    // Sinon essayer getallheaders()
    if (empty($authorization)) {
        $headers = getallheaders();
        $authorization = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    }

    // Sinon essager les headers Apache
    if (empty($authorization)) {
        $authorization = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
    }

    if (preg_match('/Bearer\s+(.+)/i', $authorization, $matches)) {
        return trim($matches[1]);
    }

    return null;
}

/**
 * Vérifier l'authentification
 */
function requireAuth() {
    $token = getTokenFromHeader();

    if (!$token) {
        http_response_code(401);
        echo json_encode([
            'success' => false,
            'message' => 'Token d\'authentification requis'
        ]);
        exit;
    }

    $payload = verifyToken($token);
    if (!$payload) {
        http_response_code(401);
        echo json_encode([
            'success' => false,
            'message' => 'Token invalide ou expiré'
        ]);
        exit;
    }

    return $payload;
}