<?php if ( ! defined( 'ABSPATH' ) ) {exit;} // Exit if accessed directly.

/**
 * Codevz advanced WP Editor for taxonomies
 * 
 * @author Codevz
 * @link http://codevz.com/
 */

class Codevz_Terms_WP_Editor {

	use Codevz_Plus_Instance;

    public function __construct() {
        add_action( 'admin_enqueue_scripts',    [ $this, 'enqueue' ] );
        add_action( 'admin_footer', 			[ $this, 'script' ], 99 );
        add_action( 'init', 					[ $this, 'allow_rich_description' ] );
    }

    public function enqueue($hook) {
        if (!in_array($hook, ['edit-tags.php','term.php'])) {
            return;
        }
        wp_enqueue_editor();
    }

    public function script() {
        $screen = get_current_screen();
        if (!in_array($screen->base, ['edit-tags','term'])) {
            return;
        }
        ?>
        <script>
        jQuery(function ($) {
            let desc = $('[name="description"]');
            if (desc.length && !$('#codevz_term_desc').length) {
                desc.hide().after('<textarea id="codevz_term_desc" name="description"></textarea>');
                $('#codevz_term_desc').val(desc.val());
                wp.editor.initialize('codevz_term_desc', {
                    tinymce: {
                        wpautop: true,
                        menubar: false,
                        toolbar1: 'formatselect fontselect fontsizeselect styleselect | hr',
                        toolbar2: 'bold italic underline | forecolor backcolor | alignleft aligncenter alignright | bullist numlist | link unlink | removeformat',
                        plugins: 'lists link hr textcolor wordpress wpautoresize'
                    },
                    quicktags: true
                });
            }
        });
        </script>
        <?php
    }

    public function allow_rich_description() {
        remove_filter('term_description', 'wp_kses_data');
        remove_filter('pre_term_description', 'wp_filter_kses');

        add_filter('sanitize_term_field_description', function ($value, $term_id, $taxonomy, $context) {
            return $context === 'db' ? wp_kses($value, wp_kses_allowed_html('post')) : $value;
        }, 10, 4);

        add_filter('wp_kses_allowed_html', function ($tags, $context) {
            if ($context === 'post') {
                foreach(['span','p','div','a','strong','em','li','ul','ol','i','section','h1','h2','h3','h4','h5','h6'] as $tag){
                    $tags[$tag]['style'] = true;
                }
            }
            return $tags;
        }, 10, 2);

        add_filter('term_description', 'do_shortcode');
        add_filter('term_description', 'wpautop');
    }

}
Codevz_Terms_WP_Editor::instance();