<?php

namespace src\Utils;

use Exception;

class token
{
    private static $secretKey = 'portal_pamela_ventura_fotografia';

    public static function createToken($payload)
    {
        $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
        $payload = json_encode($payload);

        $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
        $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));

        $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, self::$secretKey, true);
        $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

        $jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;

        return $jwt;
    }

    public static function validateToken($token)
    {
        $parts = explode('.', $token);
        if (count($parts) !== 3) {
            throw new Exception('Token inválido');
        }

        $header = $parts[0];
        $payload = $parts[1];
        $signatureProvided = $parts[2];

        $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(json_encode(['typ' => 'JWT', 'alg' => 'HS256'])));
        $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode(json_encode(json_decode(base64_decode($payload), true))));

        $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, self::$secretKey, true);
        $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

        if ($base64UrlSignature !== $signatureProvided) {
            throw new Exception('Token inválido');
        }

        $payloadArray = json_decode(base64_decode($payload), true);
        if ($payloadArray['exp'] < time()) {
            throw new Exception('Token expirado');
        }

        return $payloadArray;
    }

    public static function verifyToken()
    {
        try {
            $headers = getallheaders();
            if (!isset($headers['Authorization'])) {
                throw new Exception('Token não informado');
            }

            $token = str_replace('Bearer ', '', $headers['Authorization']);
            self::validateToken($token);
        } catch (Exception $e) {
            ResponseHelpers::sendErrorResponse($e->getMessage(), 401);
            exit();
        }
    }
}
