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

add_action( 'admin_menu', 'Dino_Link' );

function Dino_Link() {
    $urlLogo = esc_url( DINO_PLUGIN_URL . 'assets/img/icon-dino.png' );

    add_menu_page(
        esc_html__( 'Dino', 'dino-divulgador-de-noticias' ), // page_title
        esc_html__( 'Dino', 'dino-divulgador-de-noticias' ), // menu_title
        'manage_options',
        'wp-usuario-dino',
        'usuarioDino',
        $urlLogo,
        9
    );

    add_submenu_page(
        'wp-usuario-dino',
        esc_html__( 'Cadastro', 'dino-divulgador-de-noticias' ),
        esc_html__( 'Cadastro', 'dino-divulgador-de-noticias' ),
        'manage_options',
        'wp-usuario-dino',
        'usuarioDino'
    );

    add_submenu_page(
        'wp-usuario-dino',
        esc_html__( 'Instruções', 'dino-divulgador-de-noticias' ),
        esc_html__( 'Instruções', 'dino-divulgador-de-noticias' ),
        'manage_options',
        'wp-instrucoes-dino',
        'instrucoesUsoDino'
    );

    function instrucoesUsoDino() {
        require_once dirname( __FILE__ ) . '/wp-instrucoes-dino.php';
    }

    function usuarioDino() {
        require_once dirname( __FILE__ ) . '/wp-usuario-dino.php';
    }
}

add_action( 'init', 'dino_table' );

function dino_table() {
    global $wpdb;

    $publicacoes     = $wpdb->prefix . 'dino_noticias';
    $tableposts      = $wpdb->prefix . 'posts';
    $tabelapostmeta  = $wpdb->prefix . 'postmeta';
    $tabelacategorias= $wpdb->prefix . 'terms';
    $tabelausers     = $wpdb->prefix . 'users';
    $tabelacat       = $wpdb->prefix . 'term_taxonomy';
    $tablepostscats  = $wpdb->prefix . 'term_relationships';
    $logs            = $wpdb->prefix . 'dino_logs';

    $cat_slug = 'noticias-corporativas-dino';
    $cat_name = 'Notícias Corporativas';
    $cat_desc = 'Notícias Corporativas Dino';

    $term = get_term_by( 'slug', $cat_slug, 'category' );

    if ( ! $term ) {
        $result = wp_insert_term(
            $cat_name,
            'category',
            array(
                'slug'        => $cat_slug,
                'description' => $cat_desc,
            )
        );

        if ( is_array( $result ) && isset( $result['term_id'] ) ) {
            $term_id = $result['term_id'];
        } else {
            $term_id = 0;
        }
    } else {
        $term_id = $term->term_id;
        wp_update_term( $term_id, 'category', array(
            'name'        => $cat_name,
            'description' => $cat_desc,
        ) );
    }

    $resultsusers = $wpdb->get_results( "SELECT ID FROM {$wpdb->prefix}users WHERE user_email='dino@dino.com'" );
    $rowuser = $wpdb->num_rows;

    if ( $rowuser == 0 ) {
        $results = $wpdb->insert(
            $tabelausers,
            array(
                'user_login'          => 'DINO',
                'user_pass'           => wp_hash_password( 'dinopass' ),
                'user_nicename'       => 'DINO',
                'user_email'          => 'dino@dino.com',
                'user_url'            => '',
                'user_registered'     => current_time( 'mysql' ),
                'user_activation_key' => '',
                'user_status'         => 0,
                'display_name'        => 'DINO'
            ),
            array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s' )
        );

        $resultsusers = $wpdb->get_results( "SELECT ID FROM {$wpdb->prefix}users WHERE UPPER(display_name)='DINO'" );

        $userpost = 0;
        foreach ( $resultsusers as $uid ) {
            $userpost = $uid->ID;
        }

        if ( $userpost ) {
            $results = $wpdb->get_results( "SELECT p.ID, d.releaseId FROM {$wpdb->prefix}dino_noticias d JOIN {$wpdb->posts} p ON(p.post_author = d.releaseId AND p.post_status = 'publish') WHERE d.deletePost='false' ORDER BY p.ID" );

            foreach ( $results as $vres ) {
                $wpdb->query(
                    $wpdb->prepare(
                        "UPDATE {$wpdb->posts} SET post_author = %d, post_parent = %d WHERE ID = %d",
                        $userpost,
                        $vres->releaseId,
                        $vres->ID
                    )
                );
            }
        }
    }

    // Use quotes around LIKE pattern
    if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}dino_logs'" ) != $logs ) {

        $sql = "CREATE TABLE {$wpdb->prefix}dino_logs (
            id int(10) NOT NULL AUTO_INCREMENT,
            dataLog datetime NOT NULL,
            statusLog varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
            tipoLog varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
            mensagemLog varchar(400) COLLATE utf8mb4_unicode_ci NOT NULL,
            PRIMARY KEY (id)
        );";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );
    }

    if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}dino_noticias'" ) != $publicacoes ) {

        $sql = "CREATE TABLE {$wpdb->prefix}dino_noticias (
            id int(10) NOT NULL AUTO_INCREMENT,
            title varchar(400) COLLATE utf8mb4_unicode_ci NOT NULL,
            excerpt varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL,
            content LONGTEXT COLLATE utf8mb4_unicode_ci DEFAULT NULL,
            quote varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL,
            tags varchar(400) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
            editory varchar(50) DEFAULT NULL,
            place varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
            imageUrl text COLLATE utf8mb4_unicode_ci DEFAULT NULL,
            imageAlt varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
            imageDescription varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
            videoUrl text COLLATE utf8mb4_unicode_ci NOT NULL,
            releaseId int(11) NOT NULL,
            publishedAt datetime NOT NULL,
            website varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
            deletePost boolean NOT NULL,
            slug varchar(400) COLLATE utf8mb4_unicode_ci NOT NULL,
            urlpost text COLLATE utf8mb4_unicode_ci NOT NULL,
            PRIMARY KEY (id)
        );";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );
    }

    $users = $wpdb->prefix . 'dino_users';

    if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}dino_users'" ) != $users ) {

        $sql = "CREATE TABLE {$wpdb->prefix}dino_users (
            id int(10) NOT NULL AUTO_INCREMENT,
            nome varchar(400) COLLATE utf8mb4_unicode_ci NOT NULL,
            login varchar(400) COLLATE utf8mb4_unicode_ci NOT NULL,
            password varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
            password_hash varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
            PRIMARY KEY (id)
        );";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );

    } else {
        $table_name  = $wpdb->prefix . 'dino_users';
        $column_name = 'password_hash';

        $column_exists = $wpdb->get_results(
            $wpdb->prepare(
                "SHOW COLUMNS FROM `$table_name` LIKE %s",
                $column_name
            )
        );

        if ( empty( $column_exists ) ) {
            $wpdb->query(
                "ALTER TABLE `$table_name` ADD COLUMN `$column_name` VARCHAR(255) NULL AFTER `password`"
            );
        }
    }

    $results = $wpdb->get_results( "SELECT id, password FROM {$wpdb->prefix}dino_users" );

    foreach ( $results as $vres ) {
        if ( ! empty( $vres->password ) ) {
            $senhaHash = password_hash( $vres->password, PASSWORD_DEFAULT );
            $wpdb->query(
                $wpdb->prepare(
                    "UPDATE {$wpdb->prefix}dino_users SET password_hash = %s WHERE id = %d",
                    $senhaHash,
                    $vres->id
                )
            );
        }
    }

    $session = $wpdb->prefix . 'dino_sessao_token';

    if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}dino_sessao_token'" ) != $session ) {

        $sql = "CREATE TABLE {$wpdb->prefix}dino_sessao_token (
            id int(10) NOT NULL AUTO_INCREMENT,
            sessao text COLLATE utf8mb4_unicode_ci NOT NULL,
            status varchar(1) COLLATE utf8mb4_unicode_ci NOT NULL,
            PRIMARY KEY (id)
        );";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );
    }

    $layout = $wpdb->prefix . 'dino_layout';

    if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}dino_layout'" ) != $layout ) {

        $sql = "CREATE TABLE {$wpdb->prefix}dino_layout (
            id int(10) NOT NULL AUTO_INCREMENT,
            tipo_layout int NOT NULL,
            PRIMARY KEY (id)
        );";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );

        $wpdb->insert(
            $wpdb->prefix . 'dino_layout',
            array( 'tipo_layout' => 1 ),
            array( '%d' )
        );
    }

    $poststatus = $wpdb->prefix . 'related_post_stats';

    if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}related_post_stats'" ) != $poststatus ) {

        $sql = "CREATE TABLE {$wpdb->prefix}related_post_stats (
            id int(100) NOT NULL AUTO_INCREMENT,
            from_id int(100) NOT NULL,
            to_id int(100) NOT NULL,
            date date NOT NULL,
            PRIMARY KEY (id)
        );";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );
    }

    $categoria = $wpdb->prefix . 'dino_categoria';

    if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}dino_categoria'" ) != $categoria ) {

        $sql = "CREATE TABLE {$wpdb->prefix}dino_categoria (
            id int(10) NOT NULL AUTO_INCREMENT,
            nome varchar(400) COLLATE utf8mb4_unicode_ci NOT NULL,
            PRIMARY KEY (id)
        );";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta( $sql );
    }

    // --- Callbacks and admin_post handlers ---

    function dino_user_post_callback() {
        global $wpdb;
        $tablename = $wpdb->prefix . 'dino_users';

        check_admin_referer( 'dino_user_action', 'dino_nonce' );

        if ( ! is_user_logged_in() ) {
            wp_die( esc_html__( 'Você precisa estar logado para executar esta ação.', 'dino-divulgador-de-noticias' ) );
        }

        $nome  = isset( $_POST['nome'] ) ? sanitize_text_field( wp_unslash( $_POST['nome'] ) ) : '';
        $email = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
        $senha = isset( $_POST['senha'] ) ? sanitize_text_field( wp_unslash( $_POST['senha'] ) ) : '';

        if ( $nome && $email && $senha ) {
            $senhaHash = password_hash( $senha, PASSWORD_DEFAULT );

            $wpdb->insert(
                $tablename,
                array(
                    'nome'          => $nome,
                    'login'         => $email,
                    'password'      => $senha,
                    'password_hash' => $senhaHash,
                ),
                array( '%s', '%s', '%s', '%s' )
            );
        }

        wp_safe_redirect( wp_get_referer() );
        exit;
    }
    add_action( 'admin_post_dino_user_ajax', 'dino_user_post_callback' );


    function dino_remover_categoria_callback() {
        global $wpdb;
        $wpdb->query( "DELETE FROM {$wpdb->prefix}dino_categoria" );

        wp_safe_redirect( wp_get_referer() );
        exit;
    }
    add_action( 'admin_post_dino_remover_categoria_ajax', 'dino_remover_categoria_callback' );

    function dino_categoria_callback() {
        global $wpdb;
        $tablecategoria = $wpdb->prefix . 'dino_categoria';
        $categoria = isset( $_POST['categoria'] ) ? sanitize_text_field( wp_unslash( $_POST['categoria'] ) ) : '';
        if ( ! empty( $categoria ) ) {
            $wpdb->insert(
                $tablecategoria,
                array( 'nome' => $categoria ),
                array( '%s' )
            );
        }

        wp_safe_redirect( wp_get_referer() );
        exit;
    }
    add_action( 'admin_post_dino_categoria_ajax', 'dino_categoria_callback' );
}