<?php
require_once 'vendor/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

$config = [
    'jwt_secret' => 'your_strong_secret_key', // Replace with a secure key
];

function authenticate() {
    // Try to retrieve Authorization header
    $authorizationHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? null;

    // If no Authorization header, send an error and stop
    if (!$authorizationHeader) {
        http_response_code(401);
        echo json_encode([
            "success" => false,
            "message" => "Authorization header missing"
        ]);
        exit; // <-- Important
    }

    // Remove "Bearer " part and extract token
    $token = str_replace('Bearer ', '', $authorizationHeader);

    // Verify the token
    $decoded = verifyToken($token);

    if (!$decoded) {
        http_response_code(401);
        echo json_encode([
            "success" => false,
            "message" => "Invalid or expired token"
        ]);
        exit; // <-- Important
    }

    return $decoded; // stdClass object
}


function generateToken($userId, $role) {
    global $config;
    $payload = [
        'iat' => time(),
        'exp' => time() + (30 * 24 * 60 * 60), // Token expires in 30 days
        'user_id' => $userId,
        'user_type' => $role
    ];
    return JWT::encode($payload, $config['jwt_secret'], 'HS256');
}

function verifyToken($token) {
    global $config;
    try {
        return JWT::decode($token, new Key($config['jwt_secret'], 'HS256'));
    } catch (Exception $e) {
        return null;
    }
}
