<?php

    // prevent direct file access
	if( !defined( 'ABSPATH' ) ) exit;
    
    class Pixe_Switch_Editor{

        private $edit_button = false;

        // init object
        function __construct(){

            if( is_admin() ){

                // add post state
                add_filter('display_post_states', array($this, 'set_post_states'), 10, 2);

                // add button to post
                add_action('admin_print_styles', array(&$this, 'add_edit_button_styles'));
                add_action('admin_print_footer_scripts', array(&$this, 'add_edit_button_scripts'));

                // add button to post table
                add_filter('page_row_actions', array($this, 'add_table_edit_button'), 10, 2);
                add_filter('post_row_actions', array($this, 'add_table_edit_button'), 10, 2);

                // for redirecting to pixebuilder on new post
                add_action('wp_after_insert_post', array(&$this, 'builder_redirect'), 10, 4);
            }else{

                // edit with pixe builder button
                add_filter('admin_bar_menu', array($this, 'add_admin_bar_edit_button'), 100);
                add_filter('wp_enqueue_scripts', array($this, 'print_admin_bar_style'));
            }
        }

        // set post states ( end text in post list page )
        function set_post_states($post_states, $post){
            $screen = get_current_screen();
            if( $screen && $screen->id === 'edit-page' ){
                $use_pixe_builder = get_post_meta($post->ID, 'use-pixe-builder', true);
                if( !empty($use_pixe_builder) ){
                    $post_states['pixebuilder'] = esc_html__('Pixe Builder', 'pixebuilder');
                }
            }
            
            return $post_states;
        }

        // add edit with pixe builder button
        function add_edit_button_styles(){
            global $post;
            if( empty($post) ) return;
            if( !Pixe_Builder::can_use_builder($post) ) return;

            $current_screen = get_current_screen();
            
            // if enable gutenberg
            if( method_exists($current_screen, 'is_block_editor') && $current_screen->is_block_editor() ){
?><style>
.pixe-edit-post-header-button{ display: block; height: 33px; line-height: 32px; text-decoration: none; margin: 2px 15px 2px; padding: 0px 14px; white-space: nowrap;
    color: #fff; background: #0487ff; transition: opacity 150ms; border-radius: 3px; }
.pixe-edit-post-header-button:hover{ color: #fff; background: #0487ff; opacity: 0.7; }
.pixe-edit-post-header-button:focus{ box-shadow: none; color: #fff; }
.pixe-edit-post-header-button svg{ vertical-align: middle; margin-right: 8px; }
</style><?php
            }
        }
        function add_edit_button_scripts(){
            global $post;
            if( empty($post) ) return;
            if( !Pixe_Builder::can_use_builder($post) ) return;

            $current_screen = get_current_screen();
            
            // if enable gutenberg
            if( method_exists($current_screen, 'is_block_editor') && $current_screen->is_block_editor() ){
?><script>
(function($){

    $(window).load(function(){
        
        // wait until editor is initialized
        var wpEditor = $('#editor');
        var toolbarInterval = setInterval(function(){
            var headerToolbar = wpEditor.find('.edit-post-header-toolbar');
            if( headerToolbar.length ){
                var switchButton = $('<a class="pixe-edit-post-header-button" href="<?php echo esc_attr(Pixe_Builder::get_post_edit_url($post->ID)); ?>" >Edit with Pixe Builder</a>');
                switchButton.prepend('<svg width="11" height="16" viewBox="0 0 11 16" fill="none" ><path d="M3.14604 0.145508C4.71758 0.145508 4.71758 0.145508 4.71758 0.145508V4.86131L1.37761 4.86135L0.00256348 4.86131C0.00256348 4.86131 0.00256348 4.86131 0.00256348 3.28937C0.00256348 0.145508 2.71651 0.145508 3.14604 0.145508Z" fill="white"/><path d="M0 6.42896H4.71266C4.71266 6.42896 4.71659 11.1385 4.71659 14.2823C4.71659 15.8543 3.52467 15.8543 3.14505 15.8543C0.366262 15.8543 0.00157347 15.8543 0.00157347 15.8543L0 6.42896Z" fill="white"/><path d="M6.28497 0.145508C6.28497 0.145508 7.85887 0.145508 9.42962 0.145508C11 0.145508 11 1.0015 11 1.71642C11 4.8582 11 7.15814 11 9.57086C11 11.1692 9.94168 11.1492 9.42845 11.1492C7.85651 11.1492 6.28497 11.1492 6.28497 11.1492V0.145508Z" fill="white"/></svg>');
                switchButton.insertAfter(headerToolbar);

                switchButton.on('click', function(){

                    // for new post
                    if( wp.data.select('core/editor').getCurrentPost().status == 'auto-draft' ){
                        var title = wp.data.select('core/editor').getEditedPostAttribute('title');
                        if( !title ){
                            wp.data.dispatch('core/editor').editPost({
                                title: 'Pixebuilder #<?php echo esc_js($post->ID); ?>'
                            });
                        }
                        
                        // listen for status changed
                        const unssubscribe = wp.data.subscribe(function(){
                            if( wp.data.select('core/editor').getCurrentPost().status == 'draft' ){
                                window.location.href = switchButton.attr('href'); 
                            }
                        });

                        wp.data.dispatch('core/editor').savePost();
                        return false;
                    }
                    
                });
                clearInterval(toolbarInterval);
            }
        }, 500);
    });
})(jQuery);
</script><?php
            }
        }

        // redirect to pixebuilder for new posts with specific args
        function builder_redirect($post_id, $post, $update, $post_before){
            global $pagenow;

            if( $pagenow === 'post-new.php' && !empty($_GET['action']) && $_GET['action'] == 'edit-with-pxb' ){ // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Nonce not required
                
                // prevent infinite loop
                remove_action('wp_after_insert_post', array(&$this, 'builder_redirect'));

                // initialize id
                wp_update_post([
                    'ID' => $post_id,
                    'post_title'  => 'Pixebuilder #' . $post_id,
                    'post_status' => 'draft'
                ]);

                $redirect_url = Pixe_Builder::get_post_edit_url($post_id);
                wp_safe_redirect($redirect_url);
                exit;
            }
        }

        // add button to post table
        function add_table_edit_button( $actions, $post ){
            if( !Pixe_Builder::can_use_builder($post) ) return $actions;

            $actions['pixe-edit'] = '<a href="' . esc_attr(Pixe_Builder::get_post_edit_url($post->ID)) . '" >Edit with Pixe Builder</a>';
            return $actions;
        }

        // admin bar 
        function print_admin_bar_style(){
            if( is_page() || is_single() ){
                global $post;
                if( !Pixe_Builder::can_use_builder($post) ) return;

                $use_pixe_builder = get_post_meta($post->ID, 'use-pixe-builder', true);
                if( !empty($use_pixe_builder) ){
                    $this->edit_button = true;

                    ob_start();
                    echo 'li#wp-admin-bar-pixe-builder-post-edit svg{ vertical-align: middle; margin-right: 7px; fill: #fff; display: inline; }';
                    echo 'li#wp-admin-bar-pixe-builder-post-edit a:hover svg{ fill: #72aee6 }';
                    wp_add_inline_style('pixe-inline', ob_get_clean());
                }
            }
        }
        function add_admin_bar_edit_button($admin_bar){
            if( $this->edit_button ){
                $icon = '<svg width="11" height="16" viewBox="0 0 11 16" ><path d="M3.14604 0.145508C4.71758 0.145508 4.71758 0.145508 4.71758 0.145508V4.86131L1.37761 4.86135L0.00256348 4.86131C0.00256348 4.86131 0.00256348 4.86131 0.00256348 3.28937C0.00256348 0.145508 2.71651 0.145508 3.14604 0.145508Z" /><path d="M0 6.42896H4.71266C4.71266 6.42896 4.71659 11.1385 4.71659 14.2823C4.71659 15.8543 3.52467 15.8543 3.14505 15.8543C0.366262 15.8543 0.00157347 15.8543 0.00157347 15.8543L0 6.42896Z" /><path d="M6.28497 0.145508C6.28497 0.145508 7.85887 0.145508 9.42962 0.145508C11 0.145508 11 1.0015 11 1.71642C11 4.8582 11 7.15814 11 9.57086C11 11.1692 9.94168 11.1492 9.42845 11.1492C7.85651 11.1492 6.28497 11.1492 6.28497 11.1492V0.145508Z" /></svg>';

                $admin_bar->add_menu( array(
                    'id' => 'pixe-builder-post-edit',
                    'title' => $icon . 'Edit with Pixe Builder',
                    'href' => Pixe_Builder::get_post_edit_url(get_the_ID())
                ));
            }
        }

    }

    add_action('init', 'pixe_init_switch_editor');
    function pixe_init_switch_editor(){
        if( is_user_logged_in() ){
            new Pixe_Switch_Editor();
        }
    }
    