<?php
namespace Gestoreasy\Core\Admin;

use Gestoreasy\Core\Config\Config;

class AdminJwt {
    private static function b64e(string $data): string { return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); }
    private static function b64d(string $data): string|false {
        $rem = strlen($data) % 4; if ($rem) $data .= str_repeat('=', 4 - $rem);
        return base64_decode(strtr($data, '-_', '+/'));
    }
    public static function sign(array $payload, ?int $ttlSeconds = null): string {
        $header = ['alg' => 'HS256', 'typ' => 'JWT'];
        $secret = Config::get('ADMIN_JWT_SECRET', 'admin_changeme');
        $ttl = $ttlSeconds ?? (int)Config::get('ADMIN_JWT_TTL_SECONDS', 3600);
        $now = time();
        $payload['iat'] = $payload['iat'] ?? $now;
        $payload['exp'] = $payload['exp'] ?? ($now + $ttl);
        $h = self::b64e(json_encode($header));
        $p = self::b64e(json_encode($payload));
        $sig = hash_hmac('sha256', "$h.$p", $secret, true);
        $s = self::b64e($sig);
        return "$h.$p.$s";
    }
    public static function verify(string $jwt): ?array {
        $secret = Config::get('ADMIN_JWT_SECRET', 'admin_changeme');
        $parts = explode('.', $jwt); if (count($parts) !== 3) return null;
        [$h, $p, $s] = $parts;
        $sig = self::b64e(hash_hmac('sha256', "$h.$p", $secret, true));
        if (!hash_equals($sig, $s)) return null;
        $payloadJson = self::b64d($p); if ($payloadJson === false) return null;
        $payload = json_decode($payloadJson, true); if (!is_array($payload)) return null;
        if (($payload['exp'] ?? 0) < time()) return null;
        return $payload;
    }
}