<?php

const JWT_SECRET_KEY = 'e7b4c0f9a9c3d4f5e1a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d3e2f1a9b8c7';

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

function generateJWT(array $customPayload)
{
    $issuedAt = time();
    $expire = $issuedAt + (60 * 60);

    // Header
    $header = base64UrlEncode(json_encode(array(
        'alg' => 'HS256',
        'typ' => 'JWT'
    )));

    // Payload
    $payloadData = array_merge($customPayload, array(
        'iat' => $issuedAt,
        'exp' => $expire
    ));

    $payload = base64UrlEncode(json_encode($payloadData));

    // Signature
    $signature = base64UrlEncode(
        hash_hmac(
            'sha256',
            $header . "." . $payload,
            JWT_SECRET_KEY,
            true
        )
    );

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

function verifyJWT($token)
{
    $secretKey = JWT_SECRET_KEY;

    $parts = explode('.', $token);
    if (count($parts) !== 3) {
        return false;
    }

    list($header, $payload, $signature) = $parts;

    $validSignature = base64UrlEncode(
        hash_hmac('sha256', "$header.$payload", $secretKey, true)
    );

    if (!hash_equals($validSignature, $signature)) {
        return false;
    }

    $decodedPayload = json_decode(base64_decode(strtr($payload, '-_', '+/')), true);

    if (!$decodedPayload || $decodedPayload['exp'] < time()) {
        return false;
    }

    return $decodedPayload;
}

