<?php

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

if (!function_exists('generateJWT')) {
    function generateJWT($userData)
    {
        $key = getenv('JWT_SECRET'); // Load secret from .env
        $issuedAt = time();
        $expire = time() + (60 * 60 * 12);  // Token valid for 24 hour

        $payload = [
            'iss' => base_url(), // Issuer
            'iat' => $issuedAt,  // Issued at
            'exp' => $expire,    // Expiration time
            'sub' => $userData['id'],  // Subject (User ID)
            'data' => $userData  // Additional user data
        ];

        return JWT::encode($payload, $key, 'HS256');
    }
}

if (!function_exists('validateJWT')) {
    function validateJWT($token)
    {
        $key = getenv('JWT_SECRET'); 

        try {
            $decoded = JWT::decode($token, new Key($key, 'HS256'));
            return (array) $decoded; 
        } catch (\Exception $e) {
            return null; 
        }
    }
}
