<?php
if (!defined('ABSPATH')) exit;

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

class Dino_Version {

    private $jwt_secret = "e02c91bf03ea8a306eb2f3ba6b383024a96a59f7b1bec7ad8887acf620e9c4c5%";
    private $jwt_issuer = "dino-divulgador-de-noticias";
    private $jwt_role = "DINO_NOTICIAS_CORPORATIVAS";

    public function __construct() {
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes() {
        register_rest_route('dino-divulgador-de-noticias/v1', '/version', [
            'methods'  => 'POST',
            'callback' => [$this, 'check_version'],
            'permission_callback' => '__return_true',
        ]);
    }

    public function check_version($request) {
        $token = $this->getBearerToken();

        if (!$token) {
            return new WP_REST_Response([['message' => "Token não fornecido"]], 401);
        }

        try {
            $chave_secreta = sanitize_text_field(wp_unslash($this->jwt_secret));

            if (!is_string($chave_secreta) || $chave_secreta === '' || !preg_match('/^[\x20-\x7E]+$/', $chave_secreta)) {
                return new WP_REST_Response([['message' => "JWT_SECRET inválido ou não configurado"]], 500);
            }

            $decoded = JWT::decode($token, new Key($chave_secreta, 'HS256'));

            if ($decoded->role === $this->jwt_role && $decoded->iss === $this->jwt_issuer) {
                return new WP_REST_Response([['message' => "Versão do plugin: v3.4"]], 200);
            } else {
                return new WP_REST_Response([['message' => "Token inválido"]], 401);
            }

        } catch (Exception $e) {
            return new WP_REST_Response([['message' => 'Token inválido: ' . $e->getMessage()]], 401);
        }
    }

    private function getBearerToken() {
        $headers = getallheaders();
        if (!empty($headers['Authorization']) && preg_match('/Bearer\s(\S+)/', $headers['Authorization'], $matches)) {
            return $matches[1];
        }
        return null;
    }
}