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

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

class Dino_Delete {

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

    public function delete_news($request) {
        global $wpdb;
        $response = [];

        $token = $this->getBearerToken();
        if (!$token) {
            $this->log_error('TOKEN NÃO FORNECIDO');
            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) {
                $this->log_error('TOKEN INVÁLIDO');
                return new WP_REST_Response([['message' => "Token inválido"]], 401);
            }

            $dados = $request->get_json_params();
            if (empty($dados['releaseId'])) {
                $this->log_error('RELEASEID NÃO FORNECIDO');
                return new WP_REST_Response([['message' => 'ReleaseId não fornecido!']], 400);
            }

            $releaseId = intval($dados['releaseId']);

            // Deleta na tabela personalizada
            $wpdb->query(
                $wpdb->prepare(
                    "DELETE FROM {$wpdb->prefix}dino_noticias WHERE releaseId = %d",
                    $releaseId
                )
            );

            // Deleta o post no WordPress
            $post_id = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_status = %s AND post_type = %s",
                    $releaseId,
                    'publish',
                    'post'
                )
            );

            if ($post_id) {
                wp_delete_post($post_id, true);
            }

            $this->log_success('NOTÍCIA DELETADA, RELEASEID: ' . $releaseId);
            return new WP_REST_Response([['message' => "Sucesso, Notícia removida!"]], 200);

        } catch (Exception $e) {
            $this->log_error('DELETAR NOTÍCIA: ' . $e->getMessage());
            return new WP_REST_Response([['message' => 'Erro: ' . $e->getMessage()]], 500);
        }
    }

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

    private function log_error($msg) {
        $this->salvarLog('DELETE', 'ERRO', $msg);
    }

    private function log_success($msg) {
        $this->salvarLog('DELETE', 'SUCESSO', $msg);
    }

    private function salvarLog($tipo, $status, $mensagem) {
        global $wpdb;
        $table = $wpdb->prefix . 'dino_logs';

        $dataAtual = current_time('mysql');

        $wpdb->insert(
            $table,
            array(
                'dataLog' => $dataAtual,
                'statusLog' => $status ?? ' ',
                'tipoLog' => $tipo ?? ' ',
                'mensagemLog' => $mensagem ?? ' '
            ),
            array('%s', '%s', '%s')
        );
    }
}