<?php
/**
 * JWT Utilities
 * Handles JWT token generation and validation
 */

require_once __DIR__ . '/vendor/autoload.php';
// require_once __DIR__ . '/apiv11.php';
use \Firebase\JWT\JWT;
use \Firebase\JWT\Key;

// JWT Configuration
require_once('config/auth_config.php');
$GLOBALS['JWT_SECRET'] = $GLOBALS['JWT_SECRET']; // Use secret from auth_config.php
$GLOBALS['JWT_EXPIRY'] = 60 * 60 * 24 * 7; // 7 days in seconds

/**
 * Generate JWT token
 * 
 * @param array $payload Token payload
 * @return string JWT token
 */
function jwt_generateToken($payload) {
    $payload['iat'] = time();
    $payload['exp'] = time() + $GLOBALS['JWT_EXPIRY'];
    
    return JWT::encode($payload, $GLOBALS['JWT_SECRET'], 'HS256');
}

/**
 * Validate JWT token
 * 
 * @param string $token JWT token
 * @return array [success, payload]
 */
function jwt_validateToken($token) {
    try {
        $decoded = JWT::decode($token, new Key($GLOBALS['JWT_SECRET'], 'HS256'));
        return [true, (array)$decoded];
    } catch (Exception $e) {
        error_log("JWT validation failed: " . $e->getMessage());
        return [false, null];
    }
}

/**
 * Get user from JWT token
 * 
 * @param string $token JWT token
 * @return array|null User data or null if invalid
 */
function jwt_getUserFromToken($token) {
    list($success, $payload) = jwt_validateToken($token);
    
    if (!$success || !isset($payload['sub'])) {
        error_log("JWT validation failed or missing sub: " . print_r($payload, true));
        return null;
    }
    
    error_log("Looking up user with ID: " . $payload['sub']);
    $user = mysql_get('members', $payload['sub']);
    error_log("User lookup result: " . print_r($user, true));
    
    if (!$user) {
        error_log("User not found for ID: " . $payload['sub']);
        return null;
    }
    
    return $user;
}

