<?php
// Prevent direct file access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://thedock.io
 * @since      1.0.0
 *
 * @package    Thedock_Enhanced_Rich_Text_Editor
 * @subpackage Thedock_Enhanced_Rich_Text_Editor/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Thedock_Enhanced_Rich_Text_Editor
 * @subpackage Thedock_Enhanced_Rich_Text_Editor/admin
 * @author     TheDock <connect@thedock.io>
 */
class Thedock_Enhanced_Rich_Text_Editor_Admin
{
    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $version    The current version of this plugin.
     */
    private $version;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param      string    $plugin_name       The name of this plugin.
     * @param      string    $version    The version of this plugin.
     */
    public function __construct($plugin_name, $version)
    {

        $this->plugin_name = $plugin_name;
        $this->version = $version;

    }

    /**
     * Check if the current page is the TheDock builder page.
     * The builder page manages its own script queue and must not be interfered with.
     *
     * @since    1.0.0
     * @return   bool
     */
    private function is_builder_page()
    {
        global $hook_suffix;
        return isset( $hook_suffix ) && $hook_suffix === 'thedock-builder';
    }

    /**
     * Register the stylesheets for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_styles()
    {
        // Do not load on the TheDock builder page — it manages its own assets.
        if ( $this->is_builder_page() ) {
            return;
        }

        // Only load for users who can edit posts or pages
        if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ) {
            return;
        }

        $asset_version = defined( 'THEDOCK_ENHANCED_RTE_ASSET_VERSION' ) ? THEDOCK_ENHANCED_RTE_ASSET_VERSION : $this->version;
        wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'assets/css/thedock-enhanced-rich-text-editor-admin.css', array(), $asset_version, 'all' );
    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts()
    {
        // Do not load on the TheDock builder page — it manages its own assets.
        if ( $this->is_builder_page() ) {
            return;
        }

        // Only load for users who can edit posts or pages
        if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ) {
            return;
        }

        $asset_version = defined( 'THEDOCK_ENHANCED_RTE_ASSET_VERSION' ) ? THEDOCK_ENHANCED_RTE_ASSET_VERSION : $this->version;

        // Deregister WordPress bundled TinyMCE 4 to prevent it from
        // loading after our TinyMCE 7 and overwriting the global tinymce object.
        wp_deregister_script( 'wp-tinymce' );

        wp_enqueue_script( 'lodash' );
        wp_enqueue_script( 'thedock-enhanced-rte-tinymce', dirname( plugin_dir_url( __FILE__ ) ) . '/vendor/tinymce/tinymce.min.js', array( 'jquery' ), $asset_version, true );
        wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'assets/js/thedock-enhanced-rich-text-editor-admin.js', array( 'thedock-enhanced-rte-tinymce', 'jquery' ), $asset_version, true );
    }

    /**
     * Add TinyMCE initialization as an inline script.
     *
     * Uses wp_add_inline_script() to properly enqueue the TinyMCE pre-initialization
     * settings before the main plugin script. The mceInit settings come from WordPress
     * core's tiny_mce_before_init filter and may contain JavaScript object literals
     * that are handled by _parse_init (based on WordPress core's _WP_Editors::_parse_init).
     *
     * @since    1.0.0
     */
    public function add_init_inline_script()
    {
        // Do not load on the TheDock builder page.
        if ( $this->is_builder_page() ) {
            return;
        }

        // Only output for users who can edit posts or pages
        if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ) {
            return;
        }

        global $thedock_enhanced_rte_mce_settings;

        if ( ! $thedock_enhanced_rte_mce_settings ) {
            return;
        }

        $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';

        $mce_init_parts = array();
        foreach ( $thedock_enhanced_rte_mce_settings as $editor_id => $init ) {
            $safe_id          = wp_json_encode( (string) $editor_id );
            $options          = self::_parse_init( $init );
            $mce_init_parts[] = $safe_id . ':' . $options;
        }
        $mce_init = '{' . implode( ',', $mce_init_parts ) . '}';

        $base_url = wp_json_encode( esc_url( plugins_url( 'vendor/tinymce/', dirname( __FILE__ ) ) ) );
        $suffix_js = wp_json_encode( $suffix );

        $inline_script = sprintf(
            'tinyMCEPreInit = {baseURL: %s, suffix: %s, dragDropUpload: true, mceInit: %s, qtInit: false};'
            . 'window.initMce(tinyMCEPreInit);',
            $base_url,
            $suffix_js,
            $mce_init
        );

        wp_add_inline_script( $this->plugin_name, $inline_script, 'after' );
    }

    /**
     * Output the WordPress link dialog HTML in the admin footer.
     *
     * @since    1.0.0
     */
    public function output_link_dialog()
    {
        // Do not load on the TheDock builder page.
        if ( $this->is_builder_page() ) {
            return;
        }

        // Only output for users who can edit posts or pages
        if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ) {
            return;
        }

        global $thedock_enhanced_rte_mce_settings;

        if ( $thedock_enhanced_rte_mce_settings && class_exists( '_WP_Editors' ) ) {
            _WP_Editors::wp_link_dialog();
        }
    }

    /**
     * Parse TinyMCE init settings into JavaScript object literal.
     *
     * Based on WordPress core's _WP_Editors::_parse_init method. This is necessary
     * because TinyMCE settings can contain JavaScript function callbacks and object
     * literals that cannot be properly encoded with wp_json_encode.
     *
     * @since    1.0.0
     * @param    array    $init    The init settings array.
     * @return   string            JavaScript object literal string.
     */
    private static function _parse_init( $init )
    {
        $options = '';

        foreach ( $init as $key => $value ) {
            // Sanitize key: only allow word characters (letters, digits, underscore).
            if ( ! preg_match( '/^[a-zA-Z_][a-zA-Z0-9_]*$/', $key ) ) {
                continue;
            }

            if ( is_bool( $value ) ) {
                $val      = $value ? 'true' : 'false';
                $options .= $key . ':' . $val . ',';
                continue;
            } elseif ( is_numeric( $value ) ) {
                $options .= $key . ':' . floatval( $value ) . ',';
                continue;
            } elseif ( ! empty( $value ) && is_string( $value ) && (
                ( '{' === $value[0] && '}' === $value[ strlen( $value ) - 1 ] ) ||
                ( '[' === $value[0] && ']' === $value[ strlen( $value ) - 1 ] ) ||
                preg_match( '/^\(?function ?\(/', $value )
            ) ) {
                $options .= $key . ':' . $value . ',';
                continue;
            }
            $options .= $key . ':' . wp_json_encode( (string) $value ) . ',';
        }

        return '{' . trim( $options, ' ,' ) . '}';
    }

    public function block_editor_for_post()
    {
        return false;
    }

    public function tiny_mce_before_init($settings, $editor_id)
    {
        // Do not alter WP editor hooks on the TheDock builder page.
        if ( ! $this->is_builder_page() ) {
            remove_action('admin_print_footer_scripts', array( '_WP_Editors', 'editor_js' ), 50);
            remove_action('wp_print_footer_scripts', array( '_WP_Editors', 'editor_js' ), 50);
            remove_action('admin_print_footer_scripts', array( '_WP_Editors', 'print_default_editor_scripts' ), 50);
            remove_action('wp_print_footer_scripts', array( '_WP_Editors', 'print_default_editor_scripts' ), 50);
        }

        global $thedock_enhanced_rte_mce_settings;

        $settings['license_key'] = 'gpl';
        $settings['theme'] = 'silver';
        $settings['skin'] = 'oxide';
        $settings['branding'] = false;
        $settings['contextmenu'] = false;
        $settings['highlight_on_focus'] = true;
        $settings['image_caption'] = true;
        $settings['link_default_target'] = '_blank';
        $settings['paste_as_text'] = false;
        $settings['promotion'] = false;
        $settings['toolbar'] = 'tdblocks tdstyles | tdimage table | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent | code charmap removeformat | visualblocks visualchars preview fullscreen | undo redo';
        $settings['toolbar_sticky'] = true;
        $settings['toolbar_sticky_offset'] = 32;
        $settings['plugins'] = 'autoresize advlist autolink charmap code link lists fullscreen preview quickbars table visualblocks visualchars wordcount tdblocks tdimage tdlink tdstyles';
        $settings['wpeditimage_html5_captions'] = true;
        $settings['quickbars_insert_toolbar'] = '';
        $settings['quickbars_selection_toolbar'] = 'bold italic underline strikethrough | tdlink unlink | superscript subscript | forecolor backcolor';
        $settings['menubar'] = false;
        $settings['content_style'] = 'body { margin: 1rem; }';
        $settings['min_height'] = 500;
        $settings['newline_behavior'] = 'default';
        unset($settings['toolbar1']);
        unset($settings['toolbar2']);
        unset($settings['toolbar3']);
        unset($settings['toolbar4']);
        unset($settings['tabfocus_elements']);
        unset($settings['external_plugins']);
        unset($settings['preview_styles']);
        unset($settings['end_container_on_empty_block']);
        unset($settings['wp_lang_attr']);
        unset($settings['wp_keep_scroll_position']);
        unset($settings['wp_shortcut_labels']);
        unset($settings['wp_autoresize_on']);

        $thedock_enhanced_rte_mce_settings[$editor_id] = $settings;
        $thedock_enhanced_rte_mce_settings['excerpt'] = $settings;

        return $settings;
    }

    public function wp_editor_settings($settings, $editor_id)
    {
        $settings['media_buttons'] = false;
        $settings['buttons'] = false;
        $settings['quicktags'] = false;

        return $settings;
    }

    public function acf_wysiwyg_toolbars($field)
    {
        $field['type'] = 'textarea';
        $field['class'] = 'acf-wysiwyg';
        $field['rows'] = 30;
        if (isset($field['toolbar']) && is_array($field['toolbar'])) {
            $field['wrapper']['data-toolbar'] = implode(',', $field['toolbar']);
        }

        unset($field['media_upload']);
        unset($field['tabs']);
        unset($field['toolbar']);

        return $field;
    }

}
