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

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

class Dino_Logs {

    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', '/logs', [
            'methods'  => 'POST',
            'callback' => [$this, 'get_logs'],
            'permission_callback' => '__return_true',
        ]);
    }

    public function get_logs($request) {
        global $wpdb;

        $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' => "Token inválido"]], 401);
            }

            $dados = $request->get_json_params();
            $status = sanitize_text_field($dados['status'] ?? '');
            $tipo   = sanitize_text_field($dados['tipo'] ?? '');

            $results = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$wpdb->prefix}dino_logs WHERE statusLog = %s AND tipoLog = %s ORDER BY dataLog DESC",
                    $status,
                    $tipo
                )
            );

            return new WP_REST_Response([['dados' => $results]], 200);

        } catch (Exception $e) {
            return new WP_REST_Response([['message' => 'ERRO: ' . $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;
    }
}