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

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

class Dino_Publish {

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

    // ---------------- PUBLISH ----------------
    public function publish_post($request) {
        global $wpdb;

        $json = $request->get_json_params();
        $token = $this->getBearerToken();

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

        try {
            $decoded = JWT::decode($token, new Key($this->jwt_secret, 'HS256'));

            if ($decoded->role !== $this->jwt_role || $decoded->iss !== $this->jwt_issuer) {
                $this->salvarLog('PUBLICAR','ERRO','Token inválido');
                return new WP_REST_Response(['message'=>'Token inválido'], 401);
            }

            $usuario = $wpdb->get_row(
                $wpdb->prepare("SELECT id, login FROM {$wpdb->prefix}dino_users WHERE id=%d AND login=%s LIMIT 1", $decoded->sub, $decoded->login)
            );

            if (!$usuario) {
                $this->salvarLog('PUBLICAR','ERRO','Usuário Dino não localizado');
                return new WP_REST_Response(['message'=>'Usuário não encontrado'], 401);
            }

            $post = (object) ($json[0] ?? $json);

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

            if (($post->deletePost ?? false) === true) {
                $this->delete_post($post_id);
            } elseif ($post_id) {
                $this->update_post($post_id, $post);
            } else {
                $post_id = $this->insert_post($post);
            }

            $url = get_permalink($post_id);
            return ['message' => "OK", 'code' => 200, 'formattedUrl' => $url];

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

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

    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')
        );
    }

    // ---------------- FUNÇÕES DE POST ----------------
    private function insert_post($post) {
        $user = get_users(['search' => 'DINO', 'number' => 1])[0] ?? null;
        if (!$user) return;

        $datapost = explode('T', $post->publishedAt)[0];

        $postData = [
            'post_title' => $post->title ?? ' ',
            'post_status' => 'publish',
            'post_content' => $post->content ?? ' ',
            'post_excerpt' => $post->excerpt ?? ' ',
            'post_author' => $user->ID,
            'post_type' => 'post',
            'post_category' => [get_cat_ID('Notícias Corporativas')],
            'post_name' => sanitize_title($post->releaseId . '-' . $post->title),
            'post_parent' => $post->releaseId,
            'post_date' => $datapost,
            'post_date_gmt' => $datapost
        ];

        kses_remove_filters();
        $idpost = wp_insert_post($postData);
        kses_init_filters();

        add_post_meta($idpost, 'idRelease', $post->releaseId ?? '');
        if (!empty($post->tags)) {
            foreach ($post->tags as $tag) wp_add_post_tags($idpost, $tag);
        }

        if (!empty($post->imageUrl) && $this->url_exists($post->imageUrl)) {
            $this->uploadRemoteImageAndAttach($post->imageUrl, $idpost, $post->title);
        }

        $this->salvarLog('PUBLICAR','SUCESSO','Post criado com sucesso');

        return $idpost;
    }

    private function update_post($post_id, $post) {
        $user = get_users(['search' => 'DINO', 'number' => 1])[0] ?? null;
        if (!$user) return;

        $datapost = explode('T', $post->publishedAt)[0];

        $postData = [
            'ID' => $post_id,
            'post_title' => $post->title ?? ' ',
            'post_status' => 'publish',
            'post_content' => $post->content ?? ' ',
            'post_excerpt' => $post->excerpt ?? ' ',
            'post_author' => $user->ID,
            'post_type' => 'post',
            'post_category' => [get_cat_ID('Notícias Corporativas')],
            'post_parent' => $post->releaseId,
            'post_date' => $datapost,
            'post_date_gmt' => $datapost
        ];

        kses_remove_filters();
        wp_update_post($postData);
        kses_init_filters();

        add_post_meta($post_id, 'idRelease', $post->releaseId ?? '');
        if (!empty($post->tags)) {
            foreach ($post->tags as $tag) wp_add_post_tags($post_id, $tag);
        }

        if (!empty($post->imageUrl) && $this->url_exists($post->imageUrl)) {
            $this->uploadRemoteImageAndAttach($post->imageUrl, $post_id, $post->title);
        }

        $this->salvarLog('PUBLICAR','SUCESSO','Post atualizado com sucesso');
    }

    private function delete_post($post_id) {
        wp_trash_post($post_id);
        $this->salvarLog('PUBLICAR','SUCESSO','Post movido para lixeira');
    }

    private function url_exists($url) {
        $headers = @get_headers($url);
        return $headers && strpos($headers[0], '200') !== false;
    }

    private function uploadRemoteImageAndAttach($image_url, $post_id, $imageAlt = '') {
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';

        $tmp = download_url($image_url);
        if (is_wp_error($tmp)) return;

        $file_array = [
            'name' => basename($image_url),
            'tmp_name' => $tmp
        ];

        $attach_id = media_handle_sideload($file_array, $post_id);
        if (is_wp_error($attach_id)) {
            wp_delete_file($tmp);
            return;
        }

        set_post_thumbnail($post_id, $attach_id);
        update_post_meta($attach_id, '_wp_attachment_image_alt', $imageAlt);
        $this->salvarLog('PUBLICAR','SUCESSO','Imagem anexada ao post com sucesso');
    }

}