<?php

class LaniakeaSwiperCPT
{
    public $swiper_options = "
    {
        speed: 400,
        slidesPerView: 1,
        spaceBetween: 16,
        loop: true,
        initialSlide: '0',
        centeredSlides: false,
        centerInsufficientSlides: false,
        scrollbar: {
            enabled: false
        },
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
        freeMode: {
            enabled: true,
        },
        breakpoints: {
            1280: {
                slidesPerView: 4
            },
            1024: {
                slidesPerView: 3
            },
            768: {
                slidesPerView: 2
            }
        },
    }
    ";

    public function __construct()
    {
        add_action('init', array($this, 'register_cpt'));
        add_action('save_post', array($this, 'save_metabox'), 10, 2);

        //swiper group custom fields:
        add_action('swiper_group_edit_form_fields', array($this, 'swiper_group_custom_fields'), 10, 2);
        add_action('edited_swiper_group', array($this, 'save_swiper_group_custom_fields'), 10, 2);
    }

    function register_cpt($hook)
    {
        global $pagenow;

        //SWIPER

        register_post_type(
            'laniakea_swiper',
            array(
                'labels'      => array(
                    'name'          => __('Swiper Slide', 'laniakea'),
                    'singular_name' => __('Swiper Slide', 'laniakea'),
                    'add_new' => __('Aggiungi nuovo', 'laniakea'),
                    'add_new_item' => __('Aggiungi nuovo Swiper Slide', 'laniakea'),
                    'edit_item' => __('Modifica Swiper Slide', 'laniakea'),
                    'view_item' => __('Vedi Swiper Slide', 'laniakea'),
                    'all_items' => __('Tutti gli Swiper Slides', 'laniakea'),
                    'not_found' => __('Nessun Swiper Slides', 'laniakea'),

                ),
                'public'      => true,
                'has_archive' => true,
                'supports' => array('title', 'editor', 'thumbnail', 'revisions',),
                'taxonomies'  => array('swiper_group'),
                'register_meta_box_cb' =>  array($this, 'register_metaboxes'),

            )
        );

        //RIMUOVE EDITOR VISUALE DALLO SWIPER:
        if ('post.php' == $pagenow) {
            $type = get_post_type($_GET['post']);
            if ('laniakea_swiper' == $type)
                add_filter('user_can_richedit', '__return_false');
        } elseif ('post-new.php' == $pagenow) {
            if (isset($_GET['post_type']) && $_GET['post_type'] == 'laniakea_swiper')
                add_filter('user_can_richedit', '__return_false');
        }

        //SWIPER TAXONOMY

        register_taxonomy('swiper_group', ['laniakea_swiper'], [
            'label' => __('Gruppi Slide', 'laniakea'),
            'hierarchical' => true,
            'rewrite' => ['slug' => 'swiper-group'],
            'show_admin_column' => true,
            'show_in_rest' => true,
            'labels' => [
                'singular_name' => __('Genre', 'laniakea'),
                'all_items' => __('Tutti i Gruppi Slide', 'laniakea'),
                'edit_item' => __('Modifica Gruppo Slide', 'laniakea'),
                'view_item' => __('Vedi Gruppo Slide', 'laniakea'),
                'update_item' => __('Aggiorna Gruppo Slide', 'laniakea'),
                'add_new_item' => __('Aggiungi Nuovo Gruppo Slide', 'laniakea'),
                'new_item_name' => __('Nuovo nome Gruppo Slide', 'laniakea'),
                'search_items' => __('Cerca Gruppi Slide', 'laniakea'),
                'not_found' => __('Nessun Gruppo Slide', 'laniakea'),
            ]
        ]);
        register_taxonomy_for_object_type('swiper_group', 'laniakea_swiper');
    }

    function register_metaboxes()
    {
        add_meta_box(
            'Swiper Slide Link',
            'Features',
            array($this, 'render_metabox'),
            'laniakea_swiper',
            'advanced',
            'high'
        );
    }

    public function render_metabox($post)
    {

        wp_nonce_field('laniakea_nonce_action', 'laniakea_nonce_name');

?>
        <div class="field-group">
            <label>Link della slide</label>
            <input type="text" name="slide_link" value="<?php echo get_post_meta($post->ID, 'slide_link', true); ?>" />
        </div>
    <?php
    }


    public function save_metabox($post_id, $post)
    {
        // Add nonce for security and authentication.
        $nonce_name   = isset($_POST['laniakea_nonce_name']) ? $_POST['laniakea_nonce_name'] : '';
        $nonce_action = 'laniakea_nonce_action';

        // Check if nonce is valid.
        if (!wp_verify_nonce($nonce_name, $nonce_action)) {
            return;
        }

        // Check if user has permissions to save data.
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        // Check if not an autosave.
        if (wp_is_post_autosave($post_id)) {
            return;
        }

        // Check if not a revision.
        if (wp_is_post_revision($post_id)) {
            return;
        }

        if (isset($_POST['slide_link'])) update_post_meta($post_id, 'slide_link', $_POST['slide_link']);
    }

    public function swiper_group_custom_fields($tag)
    {
        $term_id = $tag->term_id;
        $term_meta = get_option("taxonomy_term_$term_id");
        $term_meta_value = isset($term_meta['swiper_group_json']) ? $term_meta['swiper_group_json'] : $this->swiper_options;

    ?>
        <tr class="form-field">
            <th scope="row" valign="top">
                <label for="swiper_group_json">Swiper Options</label>
            </th>
            <td>
                <pre id="swiper_options_ace_editor"></pre>
                <textarea id="swiper_options_textarea" name="term_meta[swiper_group_json]" id="term_meta[swiper_group_json]"><?php echo esc_textarea(wp_unslash($term_meta_value)); ?></textarea>
                <span class="description"><a href="https://swiperjs.com/swiper-api#parameters" target="_blank">SwiperJs API</a></span>
            </td>
        </tr>
        <script>
            const swiperOptionsTextarea = document.getElementById('swiper_options_textarea');
            var editor = ace.edit("swiper_options_ace_editor", {
                 mode: "ace/mode/javascript", 
                theme: "ace/theme/twilight",
                value: swiperOptionsTextarea.value,
                useWorker: false,
            });

            editor.session.on('change', function(delta) {
                // delta.start, delta.end, delta.lines, delta.action
                const value = editor.getValue();
                swiperOptionsTextarea.value = value;

            });
        </script>
<?php
    }

    function save_swiper_group_custom_fields($term_id)
    {
        if (isset($_POST['term_meta'])) {
            $t_id = $term_id;
            $term_meta = get_option("taxonomy_term_$t_id");
            $cat_keys = array_keys($_POST['term_meta']);
            foreach ($cat_keys as $key) {
                if (isset($_POST['term_meta'][$key])) {
                    $term_meta[$key] = trim($_POST['term_meta'][$key]);
                }
            }
            //save the option array
            update_option("taxonomy_term_$t_id", $term_meta);
        }
    }
}

new LaniakeaSwiperCPT();
