<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class IDVE_Editor {

    private $blocks;

    public function __construct( IDVE_Blocks $blocks ) {
        $this->blocks = $blocks;
        add_action( 'admin_init', array( $this, 'handle_editor_switch' ) );
        add_action( 'edit_form_after_title', array( $this, 'render_editor' ) );
        add_action( 'add_meta_boxes', array( $this, 'add_gutenberg_meta_box' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
        add_filter( 'use_block_editor_for_post', array( $this, 'maybe_disable_gutenberg' ), 10, 2 );
        add_action( 'save_post', array( $this, 'save_toggle' ) );
        add_filter( 'wp_insert_post_data', array( $this, 'preserve_content' ), 10, 2 );
    }

    public function handle_editor_switch() {
        if ( ! isset( $_GET['idve_switch'], $_GET['post'], $_GET['_wpnonce'] ) ) {
            return;
        }
        $post_id = absint( $_GET['post'] );
        if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }
        if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'idve_switch_' . $post_id ) ) {
            return;
        }
        $active = '1' === $_GET['idve_switch'] ? '1' : '';
        update_post_meta( $post_id, '_idve_active', $active );
        wp_safe_redirect( admin_url( 'post.php?post=' . $post_id . '&action=edit' ) );
        exit;
    }

    public function render_editor( $post ) {
        $post_types = IDVE_Core::instance()->get_supported_post_types();
        if ( ! in_array( $post->post_type, $post_types, true ) ) {
            return;
        }

        $active = get_post_meta( $post->ID, '_idve_active', true );
        $is_active = '1' === $active;

        wp_nonce_field( 'idve_toggle_nonce', 'idve_toggle_nonce_field' );

        // Hide default editor immediately via CSS when IDVE is active
        if ( $is_active ) {
            echo '<style id="idve-hide-editor">#postdivrich { display: none !important; }</style>';
        }
        ?>
        <div id="idve-toggle-bar">
            <button type="button" id="idve-toggle-btn" class="button button-primary">
                <?php echo $is_active ? esc_html__( 'Back to Default Editor', 'insight-dezign-visual-editor' ) : esc_html__( 'Edit with ID Visual Editor', 'insight-dezign-visual-editor' ); ?>
            </button>
        </div>
        <input type="hidden" name="idve_active" id="idve-active-input" value="<?php echo $is_active ? '1' : ''; ?>">
        <div id="idve-editor" data-post-id="<?php echo esc_attr( $post->ID ); ?>" style="<?php echo $is_active ? '' : 'display:none;'; ?>"></div>
        <script>
        (function() {
            var btn = document.getElementById('idve-toggle-btn');
            var editor = document.getElementById('idve-editor');
            var input = document.getElementById('idve-active-input');
            var initialized = <?php echo $is_active ? 'true' : 'false'; ?>;

            function showIdve() {
                // Add CSS rule to hide default editor
                if (!document.getElementById('idve-hide-editor')) {
                    var s = document.createElement('style');
                    s.id = 'idve-hide-editor';
                    s.textContent = '#postdivrich { display: none !important; }';
                    document.head.appendChild(s);
                }
                editor.style.display = '';
                input.value = '1';
                btn.textContent = '<?php echo esc_js( __( 'Back to Default Editor', 'insight-dezign-visual-editor' ) ); ?>';
                if (!initialized && window.IDVE && IDVE.Editor && IDVE.Editor.activate) {
                    IDVE.Editor.activate();
                    initialized = true;
                }
            }

            function showDefault() {
                if (window.IDVE && IDVE.state && IDVE.state.dirty) {
                    if (!confirm('You have unsaved changes. Switch editors anyway?')) {
                        return;
                    }
                }
                // Remove CSS rule to restore default editor
                var s = document.getElementById('idve-hide-editor');
                if (s) s.parentNode.removeChild(s);
                editor.style.display = 'none';
                input.value = '';
                btn.textContent = '<?php echo esc_js( __( 'Edit with ID Visual Editor', 'insight-dezign-visual-editor' ) ); ?>';

                // TinyMCE may have initialized while hidden (0-dimension iframe).
                // Force it to re-render by re-triggering the current editor mode.
                setTimeout(function() {
                    var wrap = document.getElementById('wp-content-wrap');
                    var mode = (wrap && wrap.classList.contains('html-active')) ? 'html' : 'tmce';
                    if (window.switchEditors) {
                        switchEditors.go('content', mode);
                    }
                    window.dispatchEvent(new Event('resize'));
                }, 100);
            }

            btn.addEventListener('click', function() {
                if (input.value === '1') {
                    showDefault();
                } else {
                    showIdve();
                }
            });
        })();
        </script>
        <?php
    }

    /**
     * Sidebar meta box for Gutenberg — gives users a way to switch
     * to IDVE when the block editor is active.
     */
    public function add_gutenberg_meta_box() {
        $screen = get_current_screen();
        // Only in block editor — Classic Editor uses the inline toggle bar
        if ( ! $screen || ! $screen->is_block_editor ) {
            return;
        }

        $post_types = IDVE_Core::instance()->get_supported_post_types();
        foreach ( $post_types as $pt ) {
            add_meta_box(
                'idve-activate-box',
                __( 'ID Visual Editor', 'insight-dezign-visual-editor' ),
                array( $this, 'render_gutenberg_meta_box' ),
                $pt,
                'side',
                'high'
            );
        }
    }

    public function render_gutenberg_meta_box( $post ) {
        $switch_url = wp_nonce_url(
            admin_url( 'post.php?post=' . $post->ID . '&action=edit&idve_switch=1' ),
            'idve_switch_' . $post->ID
        );
        echo '<p style="margin-bottom:12px;">' . esc_html__( 'Switch to the ID Visual Editor to design this page with rows, columns, and blocks.', 'insight-dezign-visual-editor' ) . '</p>';
        echo '<a href="' . esc_url( $switch_url ) . '" class="button button-primary">' . esc_html__( 'Edit with ID Visual Editor', 'insight-dezign-visual-editor' ) . '</a>';
    }

    public function enqueue_assets( $hook ) {
        if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ), true ) ) {
            return;
        }

        $post = get_post();
        if ( ! $post ) {
            return;
        }

        $post_types = IDVE_Core::instance()->get_supported_post_types();
        if ( ! in_array( $post->post_type, $post_types, true ) ) {
            return;
        }

        $active = get_post_meta( $post->ID, '_idve_active', true );

        wp_enqueue_media();
        wp_enqueue_editor();
        wp_enqueue_style( 'wp-color-picker' );

        $v = IDVE_VERSION;
        wp_enqueue_style( 'idve-editor', IDVE_PLUGIN_URL . 'admin/css/idve-editor.css', array(), $v );
        wp_enqueue_style( 'dashicons' );
        wp_enqueue_style( 'idve-fontawesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css', array(), '6.7.2' ); // phpcs:ignore PluginCheck.CodeAnalysis.EnqueuedResourceOffloading.OffloadedContent

        $js_dir = IDVE_PLUGIN_URL . 'admin/js/';
        wp_enqueue_script( 'idve-history',        $js_dir . 'idve-history.js',        array(), $v, true );
        wp_enqueue_script( 'idve-rich-text',       $js_dir . 'idve-rich-text.js',      array(), $v, true );
        wp_enqueue_script( 'idve-blocks-js',       $js_dir . 'idve-blocks.js',         array(), $v, true );
        wp_enqueue_script( 'idve-drag-drop',       $js_dir . 'idve-drag-drop.js',      array(), $v, true );
        wp_enqueue_script( 'idve-settings-panel',  $js_dir . 'idve-settings-panel.js', array( 'wp-color-picker' ), $v, true );
        wp_enqueue_script( 'idve-editor-js',       $js_dir . 'idve-editor.js',         array(
            'idve-history', 'idve-rich-text', 'idve-blocks-js',
            'idve-drag-drop', 'idve-settings-panel',
        ), $v, true );
        if ( idve_is_pro() ) {
            wp_enqueue_script( 'idve-ai-js', $js_dir . 'idve-ai.js', array( 'idve-editor-js' ), $v, true );
        }

        $cm_settings = wp_enqueue_code_editor( array( 'type' => 'text/css' ) );
        if ( false !== $cm_settings ) {
            wp_localize_script( 'idve-editor-js', 'idveCodeEditor', $cm_settings );
        }

        wp_localize_script( 'idve-blocks-js', 'idveData', array(
            'postId'      => $post->ID,
            'restUrl'     => rest_url( 'idve/v1/' ),
            'nonce'       => wp_create_nonce( 'wp_rest' ),
            'blocks'      => $this->blocks->get_editor_config(),
            'mediaTitle'  => __( 'Select Image', 'insight-dezign-visual-editor' ),
            'mediaButton' => __( 'Use Image', 'insight-dezign-visual-editor' ),
            'isActive'    => '1' === $active,
            'logoUrl'     => IDVE_PLUGIN_URL . 'admin/images/id-icon-36x36.png',
            'aiEnabled'   => idve_is_pro() && self::ai_has_key(),
        ) );

        do_action( 'idve_editor_scripts' );
    }

    public function maybe_disable_gutenberg( $use_block_editor, $post ) {
        if ( '1' === get_post_meta( $post->ID, '_idve_active', true ) ) {
            return false;
        }
        return $use_block_editor;
    }

    /**
     * Prevent the WP "Update" button from wiping post_content when
     * IDVE is active. The default editor is hidden but still submits
     * its (stale) content — we override it with the DB content that
     * IDVE saved via REST API.
     */
    public function preserve_content( $data, $postarr ) {
        $post_id = isset( $postarr['ID'] ) ? absint( $postarr['ID'] ) : 0;
        if ( ! $post_id ) {
            return $data;
        }
        // Check the form value so transitions (active→inactive) work correctly
        $active_in_form = isset( $postarr['idve_active'] ) && '1' === $postarr['idve_active'];
        if ( ! $active_in_form ) {
            return $data;
        }
        $existing = get_post_field( 'post_content', $post_id );
        if ( ! empty( $existing ) ) {
            $data['post_content'] = $existing;
        }
        return $data;
    }

    private static function ai_has_key() {
        $ai = get_option( 'idve_ai_settings', array() );
        return is_array( $ai ) && ! empty( $ai['api_key'] );
    }

    public function save_toggle( $post_id ) {
        if ( ! isset( $_POST['idve_toggle_nonce_field'] ) ) {
            return;
        }
        if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['idve_toggle_nonce_field'] ) ), 'idve_toggle_nonce' ) ) {
            return;
        }
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }
        $active = isset( $_POST['idve_active'] ) && '1' === $_POST['idve_active'] ? '1' : '';
        update_post_meta( $post_id, '_idve_active', $active );
    }
}
