<?php

namespace Blazemedia\Blackhole\Settings;
use Blazemedia\Blackhole\Settings\Capability;

class SettingPage {

    private $blackhole_settings_options;

    public function __construct() {
        add_action( 'admin_menu', [ $this, 'blackhole_settings_add_plugin_page' ]);
        add_action( 'admin_init', [ $this, 'blackhole_settings_page_init' ] );
        add_action( 'wp_ajax_get_terms_by_taxonomy', [ $this, 'get_terms_by_taxonomy' ] ); // AJAX for terms
    }

    public function blackhole_settings_add_plugin_page() {
        add_menu_page(
            'Blackhole Settings', // page_title
            'Blackhole Settings', // menu_title
            'manage_options', // capability
            'blackhole-settings', // menu_slug
            [ $this, 'blackhole_settings_create_admin_page' ], // callback
            'dashicons-media-archive', // icon_url
            65 // position
        );
    }

    public function blackhole_settings_create_admin_page() {

        if( !current_user_can( Capability::BLACKHOLE_CAP ) ) {
            wp_die('Non hai i permessi per visualizzare questa pagina');
        } 

        $this->blackhole_settings_options = get_option( 'blackhole_settings_option' ); ?>

        <div class="wrap">
            <h2>Impostazioni Blackhole</h2>
            <form method="post" action="options.php">
                <?php
                    settings_fields( 'blackhole_settings_option_group' );
                    do_settings_sections( 'blackhole-settings-admin' );
                    submit_button();
                ?>
            </form>
        </div>
        <script>
            jQuery(document).ready(function($) {
                // Function to load terms when a taxonomy is selected
                function loadTerms(selectTaxonomy, selectTerm) {
                    var taxonomy = selectTaxonomy.val();
                    selectTerm.empty().append('<option value="">Seleziona un termine</option>'); // reset terms
                    if (taxonomy) {
                        $.post(ajaxurl, {
                            action: 'get_terms_by_taxonomy',
                            taxonomy: taxonomy
                        }, function(response) {
                            if (response.success) {
                                $.each(response.data, function(index, term) {
                                    selectTerm.append('<option value="'+term.slug+'">'+term.name+'</option>');
                                });
                            }
                        });
                    }
                }

                // Handle the add new Taxonomy/Terms fields
                $('#add-taxonomy-term').click(function(e) {
                    e.preventDefault();
                    var lastIndex = $('.taxonomy-term-wrapper').length; // get the last index
                    var clone = $('.taxonomy-term-wrapper:first').clone(); // clone first element
                    clone.find('select').val(''); // reset the values
                    clone.find('select').each(function() {
                        var name = $(this).attr('name');
                        name = name.replace(/\[0\]/g, '[' + lastIndex + ']'); // update the index
                        $(this).attr('name', name);
                    });
                    $('#taxonomy-terms-container').append(clone); // append to container
                });

                // Trigger terms load on taxonomy select change
                $(document).on('change', '.taxonomy-select', function() {
                    var selectTaxonomy = $(this);
                    var selectTerm = selectTaxonomy.closest('.taxonomy-term-wrapper').find('.term-select');
                    loadTerms(selectTaxonomy, selectTerm);
                });
            });
        </script>
    <?php }

    public function blackhole_settings_page_init() {
        register_setting(
            'blackhole_settings_option_group', // option_group
            'blackhole_settings_option', // option_name
            array(  $this, 'blackhole_settings_sanitize' ) // sanitize_callback
        );

        add_settings_section(
            'blackhole_settings_setting_section', // id
            'Impostazioni', // title
            array( $this, 'blackhole_settings_section_info' ), // callback
            'blackhole-settings-admin' // page
        );

        // Analytics Property field (Text input)
        add_settings_field(
            'analytics_property', // id
            'Id Property Analitics', // title
            array( $this, 'analytics_property_callback' ), // callback
            'blackhole-settings-admin', // page
            'blackhole_settings_setting_section' // section
        );

        // Post Types field (Multiple select)
        add_settings_field(
            'post_types', // id
            'Tipi di Post', // title
            array( $this, 'post_types_callback' ), // callback
            'blackhole-settings-admin', // page
            'blackhole_settings_setting_section' // section
        );

        // Taxonomy/Term fields (dynamic)
        add_settings_field(
            'taxonomy_terms', // id
            'Tassonomie e Termini', // title
            array( $this, 'taxonomy_terms_callback' ), // callback
            'blackhole-settings-admin', // page
            'blackhole_settings_setting_section' // section
        );

      
    }

    public function blackhole_settings_sanitize($input) {
        $sanitary_values = array();

        if ( isset( $input['post_types'] ) ) {
            $sanitary_values['post_types'] = array_map( 'sanitize_text_field', $input['post_types'] );
        }

        if ( isset( $input['taxonomy_terms'] ) ) {
            $sanitary_values['taxonomy_terms'] = array_map( function($item) {
                return [
                    'taxonomy' => sanitize_text_field( $item['taxonomy'] ),
                    'term' => sanitize_text_field( $item['term'] )
                ];
            }, $input['taxonomy_terms']);
        }

        if ( isset( $input['analytics_property'] ) ) {
            $sanitary_values['analytics_property'] = sanitize_text_field( $input['analytics_property'] );
        }

        return $sanitary_values;
    }

    public function blackhole_settings_section_info() {
        echo 'Seleziona le impostazioni per il plugin Blackhole.';
    }

    public function post_types_callback() {
        $post_types = get_post_types(['public' => true], 'objects');
        $selected_post_types = isset( $this->blackhole_settings_options['post_types'] ) ? $this->blackhole_settings_options['post_types'] : array();
        ?>
        <select name="blackhole_settings_option[post_types][]" multiple="multiple" size="10">
            <option value="">Seleziona un tipo di post</option>
            <?php foreach ($post_types as $post_type) : ?>
                <option value="<?php echo esc_attr($post_type->name); ?>" 
                    <?php echo in_array($post_type->name, $selected_post_types) ? 'selected' : ''; ?>>
                    <?php echo esc_html($post_type->label); ?>
                </option>
            <?php endforeach; ?>
        </select>
        <?php
    }

    public function taxonomy_terms_callback() {
        $taxonomies = get_taxonomies([], 'objects');
        $saved_taxonomy_terms = isset( $this->blackhole_settings_options['taxonomy_terms'] ) ? $this->blackhole_settings_options['taxonomy_terms'] : array();
        ?>
        <div id="taxonomy-terms-container">
            <?php 
            if (!empty($saved_taxonomy_terms)) {
                foreach ($saved_taxonomy_terms as $index => $taxonomy_term) { ?>
                    <div class="taxonomy-term-wrapper">
                        <select class="taxonomy-select" name="blackhole_settings_option[taxonomy_terms][<?php echo $index; ?>][taxonomy]">
                            <option value="">Seleziona una tassonomia</option>
                            <?php foreach ($taxonomies as $taxonomy) : ?>
                                <option value="<?php echo esc_attr($taxonomy->name); ?>" <?php selected($taxonomy_term['taxonomy'], $taxonomy->name); ?>>
                                    <?php echo esc_html($taxonomy->label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <select class="term-select" name="blackhole_settings_option[taxonomy_terms][<?php echo $index; ?>][term]">
                            <option value="">Seleziona un termine</option>
                            <?php
                            $terms = get_terms(['taxonomy' => $taxonomy_term['taxonomy'], 'hide_empty' => false]);
                            foreach ($terms as $term) : ?>
                                <option value="<?php echo esc_attr($term->slug); ?>" <?php selected($taxonomy_term['term'], $term->slug); ?>>
                                    <?php echo esc_html($term->name); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                <?php }
            } else { ?>
                <div class="taxonomy-term-wrapper">
                    <select class="taxonomy-select" name="blackhole_settings_option[taxonomy_terms][0][taxonomy]">
                        <option value="">Seleziona una tassonomia</option>
                        <?php foreach ($taxonomies as $taxonomy) : ?>
                            <option value="<?php echo esc_attr($taxonomy->name); ?>">
                                <?php echo esc_html($taxonomy->label); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <select class="term-select" name="blackhole_settings_option[taxonomy_terms][0][term]">
                    <option value="">Seleziona un termine</option>
                    </select>
                </div>
            <?php } ?>
        </div>
        <button id="add-taxonomy-term" class="button">+ Aggiungi Tassonomia/Termine</button>
        <?php
    }

    // Callback for the Analytics Property field
    public function analytics_property_callback() {
        $analytics_property = isset( $this->blackhole_settings_options['analytics_property'] ) ? $this->blackhole_settings_options['analytics_property'] : '';
        ?>
        <input type="text" name="blackhole_settings_option[analytics_property]" value="<?php echo esc_attr($analytics_property); ?>" placeholder="Inserisci Id Property Analitics" />
        <?php
    }

    // AJAX function to load terms based on selected taxonomy
    public function get_terms_by_taxonomy() {
        $taxonomy = isset($_POST['taxonomy']) ? sanitize_text_field($_POST['taxonomy']) : '';
        if ($taxonomy) {
            $terms = get_terms(['taxonomy' => $taxonomy, 'hide_empty' => false]);
            if (!is_wp_error($terms)) {
                wp_send_json_success($terms);
            }
        }
        wp_send_json_error();
    }
}