<?php

namespace Blazemedia\Blackhole\CustomPostTypes;
use Blazemedia\Blackhole\Tools\SimpleDB;

class Blackhole {

    static function init() {

        // Add the custom columns to the posts post type:
        add_filter( 'init',    [ get_called_class(), 'add_post_type'] , 20);
    }

    /**
     * registra il post-type per le tabelle
     *
     * @return void
     */
    static function add_post_type() {

        $taxonomy_objects = get_taxonomies();

        register_post_type('blackhole', [

            'public'              => false,
            'show_ui'             => true,
            'show_in_menu'        => false,
            'publicly_queryable'  => false,
            'capability_type'     => 'post',
            'exclude_from_search' => true,
            'can_export'          => false,
            'hierarchical'        => false,
            'rewrite'             => false,
            'has_archive'         => false,
            'supports'            => [ 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'revisions', 'custom-fields' ],
            //'show_in_nav_menus' => false,
            'taxonomies'          => array_keys($taxonomy_objects),


            'menu_position' => 81,

            'labels' => [
                'name' => 'Blackhole',
                'singular_name' => 'Blackhole',
                'add_new' => 'Aggiungi nuovo',
                'add_new_item' => 'Aggiungi nuovo in Blackhole',
                'edit' => 'Modifica',
                'edit_item' => 'Modifica in Blackhole',
                'new_item' => 'Nuovo in Blackhole',
                'view' => 'Vedi',
                'view_item' => 'Vedi Blackhole',
                'search_items' => 'Cerca Blackhole',
                'not_found' => 'Nessun Blackhole trovato',
                'not_found_in_trash' => 'Nessuna Blackhole trovato nel cestino'
            ]
        ]);

        register_taxonomy_for_object_type('post_tag', 'blackhole'); 
       
        add_action('restrict_manage_posts', [ get_called_class(),'add_tag_filter']);
        add_action('restrict_manage_posts', [ get_called_class(),'filter_dropdown_by_author']);
        add_action('parse_query', [ get_called_class(),'handle_author_filter']);
        add_filter( 'post_row_actions', [ get_called_class(), 'add_restore_row_action' ], 10, 2 );
        add_filter( 'bulk_actions-edit-blackhole', [ get_called_class(), 'register_bulk_restore_action' ] );
        add_filter( 'handle_bulk_actions-edit-blackhole', [ get_called_class(), 'handle_bulk_restore_action' ], 10, 3 );
        add_action( 'admin_init', [ get_called_class(), 'handle_single_restore_action' ] );
        add_action( 'admin_notices', [ get_called_class(), 'render_restore_notice' ] );
        add_action( 'post_submitbox_misc_actions', [ get_called_class(), 'render_single_restore_button_in_editor' ] );
    }

    static function add_tag_filter($query) {
        global $typenow;
     
        // Verifica che tu sia nella pagina 'edit.php' e che sia un tipo di post che supporta i tag
        if ($typenow == 'blackhole') {
            $args = array(
                'show_option_all' => 'Mostra tutti i tag',
                'taxonomy'        => 'post_tag', // Assicurati di utilizzare il nome corretto della tassonomia dei tag
                'name'            => 'post_tag',
                'orderby'         => 'name',
                'selected'        => isset($_GET['tag']) ? $_GET['tag'] : '',
                'hierarchical'    => false,
                'depth'           => 1,
                'show_count'      => false,
                'hide_empty'      => true,
            );

            wp_dropdown_categories($args);
        }
    }

    static function filter_dropdown_by_author() {
        global $typenow;

        // Verifica se il post_type corrente supporta l'ordinamento per autore
        if ("blackhole" == $typenow) {
            $authors = get_users();
    
            if (!empty($authors)) {
                // Stampa il menu a discesa
                echo '<select name="filter_by_author">';
                echo '<option value="">Filtra per autore</option>';
                foreach ($authors as $author) {
                    $selected = (isset($_GET['filter_by_author']) && $_GET['filter_by_author'] == $author->ID) ? 'selected' : '';
                    echo '<option value="' . $author->ID . '" ' . $selected . '>' . $author->display_name . '</option>';
                }
                echo '</select>';
            }
        }
    }

    static function handle_author_filter($query) {
        if (!is_admin() || !$query->is_main_query())
            return;

        global $typenow;
        global $pagenow;
        if ('edit.php' == $pagenow && "blackhole" == $typenow ) {
            if (isset($_GET['filter_by_author']) && !empty($_GET['filter_by_author'])) {
                $query->set('author', $_GET['filter_by_author']);
            }
        }
    }

    public static function add_restore_row_action( $actions, $post ) {
        if ( !is_object( $post ) || $post->post_type !== 'blackhole' || !current_user_can( 'edit_post', $post->ID ) ) {
            return $actions;
        }

        $url = wp_nonce_url(
            add_query_arg(
                array(
                    'blz_blackhole_action' => 'restore_single',
                    'post_id' => $post->ID,
                ),
                admin_url( 'edit.php?post_type=blackhole' )
            ),
            'blz_restore_blackhole_' . $post->ID
        );

        $actions['blz_restore_blackhole'] = '<a href="' . esc_url( $url ) . '">Ripristina</a>';
        return $actions;
    }

    public static function register_bulk_restore_action( $actions ) {
        $actions['blz_restore_blackhole_bulk'] = 'Ripristina in post type originale';
        return $actions;
    }

    public static function handle_bulk_restore_action( $redirect_to, $doaction, $post_ids ) {
        if ( $doaction !== 'blz_restore_blackhole_bulk' ) {
            return $redirect_to;
        }

        $db = SimpleDB::getInstance();
        $restored = 0;
        foreach ( (array) $post_ids as $post_id ) {
            if ( $db->restoreFromBlackhole( (int) $post_id ) ) {
                $restored++;
            }
        }

        return add_query_arg(
            array(
                'post_type' => 'blackhole',
                'blz_restored' => $restored,
            ),
            $redirect_to
        );
    }

    public static function handle_single_restore_action() {
        if ( !is_admin() ) {
            return;
        }

        $action = isset( $_GET['blz_blackhole_action'] ) ? sanitize_text_field( wp_unslash( $_GET['blz_blackhole_action'] ) ) : '';
        if ( $action !== 'restore_single' ) {
            return;
        }

        $post_id = isset( $_GET['post_id'] ) ? absint( $_GET['post_id'] ) : 0;
        if ( $post_id <= 0 || !current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        check_admin_referer( 'blz_restore_blackhole_' . $post_id );

        $restored = SimpleDB::getInstance()->restoreFromBlackhole( $post_id ) ? 1 : 0;
        $redirect = add_query_arg(
            array(
                'post_type' => 'blackhole',
                'blz_restored' => $restored,
            ),
            admin_url( 'edit.php' )
        );

        wp_safe_redirect( $redirect );
        exit;
    }

    public static function render_restore_notice() {
        $post_type = isset( $_GET['post_type'] ) ? sanitize_key( wp_unslash( $_GET['post_type'] ) ) : '';
        if ( !is_admin() || !isset( $_GET['blz_restored'] ) || $post_type !== 'blackhole' ) {
            return;
        }

        $restored = absint( wp_unslash( $_GET['blz_restored'] ) );
        if ( $restored <= 0 ) {
            echo '<div class="notice notice-warning is-dismissible"><p>Nessun post ripristinato.</p></div>';
            return;
        }

        $message = sprintf(
            _n( '%d post ripristinato correttamente.', '%d post ripristinati correttamente.', $restored ),
            $restored
        );
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html( $message ) . '</p></div>';
    }

    public static function render_single_restore_button_in_editor() {
        global $post;

        if ( !is_object( $post ) || $post->post_type !== 'blackhole' || !current_user_can( 'edit_post', $post->ID ) ) {
            return;
        }

        $url = wp_nonce_url(
            add_query_arg(
                array(
                    'blz_blackhole_action' => 'restore_single',
                    'post_id' => $post->ID,
                ),
                admin_url( 'edit.php?post_type=blackhole' )
            ),
            'blz_restore_blackhole_' . $post->ID
        );

        echo '<div class="misc-pub-section">';
        echo '<a class="button button-secondary" href="' . esc_url( $url ) . '">Ripristina post originale</a>';
        echo '</div>';
    }
}
