<?php
namespace WpBookingHotel\Wordpress;
use Exception;
use WpBookingHotel\Factory;
use WpBookingHotel\Filesystem\File;
use WpBookingHotel\Filesystem\Folder;
use WpBookingHotel\Html\ToolBar;
use WpBookingHotel\Html\WpBookingHotelHtmlBackend;
use WpBookingHotel\Mvc\Controller\Controller;
use WpBookingHotel\Mvc\Model\Model;
use WpBookingHotel\Utilities\Utility;
use WpBookingHotel\Html\Html;
use WpBookingHotel\Language\Text;use WpBookingHotelAdmin\app\helpers\ConfigHelper;

/**
 * Class Wordpress
 * @package WpBookingHotel\Wordpress
 */
class WordpressAdmin extends Wordpress
{
    private static $items_submenus;
    private static $list_menu_by_xml;
    public static $prefix_link = "wb_";

    public function init(){
        $path="wp-content/plugins/wpbookinghotel/frontend/app/views.xml";
        add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
        $gutembergBlock=GutembergBlock::getInstance();
        add_action('rest_api_init', array($this, 'wp_register_rest_route'));
        add_filter('block_categories', array($gutembergBlock, 'register_block_categories'), 10, 2);
        add_action( 'enqueue_block_editor_assets',array($gutembergBlock,'mdlr_editable_block_example_backend_enqueue') );
        add_action( 'admin_head-nav-menus.php', array($this,'register_menu_metabox') );
        add_action('admin_menu', array($this, 'wpbookinghotel_plugin_setup_menu'));
        add_filter( 'init', array($this,"tour_op_generate_rewrite_rules"));
         $widgets = Widgets::getInstance();
         $widgets->init();
    }

    public  function load_plugin_textdomain(){
        load_plugin_textdomain( 'wpbookinghotel', false, WPBOOKINGHOTEL_PATH_ROOT . '/languages/' );
    }
    public  function check_is_page_in_plugin($page){
        $list_view_admin = self::get_list_view_for_woo_panel();
        foreach ($list_view_admin as $current_page){
            if($current_page['id']==$page){
                return true;
            }
        }
        return false;
    }
        public function wp_register_rest_route(){
        register_rest_route(
            self::$namespace,
            "wpbookinghotel_frontend/task",
            array(
                'methods' => 'POST',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
        register_rest_route(
            self::$namespace,
            "wpbookinghotel_frontend/task",
            array(
                'methods' => 'GET',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
        register_rest_route(
            self::$namespace,
            "wpbookinghotel_backend/task",
            array(
                'methods' => 'POST',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
        register_rest_route(
            self::$namespace,
            "wpbookinghotel_backend/task",
            array(
                'methods' => 'GET',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
    }

    function wpbookinghotel_plugin_setup_menu()
    {
        $input=Factory::getInput();
        $list_view_admin = self::get_list_view_for_woo_panel();
        $page=$input->getString('page',"");
        $task=$input->getString('task',"");
        if(self::check_is_page_in_plugin($page) && $task!==""){
           Controller::action_task();
        }
        $first_view = array_shift($list_view_admin);
        $first_view = (object)$first_view;
        $menu_slug = str_replace('_', '-', $first_view->menu_slug);
        $link_dashboard = "wb_dashboard";
        add_menu_page('Wpbooking Hotel', 'Wp Booking Hotel', 'manage_options', $link_dashboard, array($this, 'wpbookinghotel_page'));
        foreach ($list_view_admin as $key => $view) {
            $view = (object)$view;
            $layout=$view->layout;
            $menu_slug=$view->menu_slug;

            add_submenu_page($link_dashboard, $view->label, $view->label, 'manage_options', $menu_slug,
                array($this, 'wpbookinghotel_page'));
        }






    }

    public static function get_api_task()
    {
        return "/wpbookinghotel_backend/task";

    }
    function register_menu_metabox() {
        $custom_param = array( 0 => 'This param will be passed to my_render_menu_metabox' );

        add_meta_box( 'wpbookinghotel-metabox', 'Wp Booking Hotel', array($this,'render_menu_metabox'), 'nav-menus', 'side', 'default', $custom_param );
    }
    /**
     * Displays a menu metabox
     *
     * @param string $object Not used.
     * @param array $args Parameters and arguments. If you passed custom params to add_meta_box(),
     * they will be in $args['args']
     */
    function render_menu_metabox( $object, $args ) {
        global $nav_menu_selected_id;
        $list_page = self::get_list_layout_view_frontend();
        $key_woo_booking = self::$key_wpbookinghotel;
        $my_items=array();
        $i=1;
        foreach ($list_page as $key=> $page){
            $my_items[]=(object)array(
                'ID' => $i,
                'db_id' => 0,
                'menu_item_parent' => 0,
                'object_id' => $i,
                'post_parent' => 0,
                'type' => 'custom',
                'key' => $key,
                'content' => '[wpbookinghotel view="'.$key.'"]',
                'object' => 'my-object-slug',
                'type_label' => 'My Cool Plugin',
                'title' => $page['title'],
                'url' => home_url( '/'.$key ),
                'target' => '',
                'attr_title' => '',
                'description' => '',
                'classes' => array(),
                'xfn' => '',
            );
            $i++;
        }
        // Create an array of objects that imitate Post objects

        $removed_args = array(
            'action',
            'customlink-tab',
            'menu-item',
            'page-tab',
            '_wpnonce',
        ); ?>
        <div id="my-plugin-div">
        <div id="tabs-panel-my-plugin-all" class="tabs-panel tabs-panel-active">
            <ul id="my-plugin-checklist-pop" class="categorychecklist form-no-clear" >
                <?php foreach ($my_items as $item){ ?>
                    <li>
                        <label class="menu-item-title">
                            <input type="checkbox" class="menu-item-checkbox" name="menu-item[-<?php Text::_echo_no_translate($item->ID) ?>][menu-item-object-id]" value="-<?php Text::_echo_no_translate($item->ID) ?>"><?php Text::_echo_no_translate($item->title) ?></label>
                        <input type="hidden" class="menu-item-type" name="menu-item[-<?php Text::_echo_no_translate($item->ID) ?>][menu-item-type]" value="custom">
                        <input type="hidden" class="menu-item-title" name="menu-item[-<?php Text::_echo_no_translate($item->ID) ?>][menu-item-title]" value="<?php Text::_echo_no_translate($item->title) ?>">
                        <input type="hidden" class="menu-item-url" name="menu-item[-<?php Text::_echo_no_translate($item->ID) ?>][menu-item-url]" value="<?php Text::_echo_no_translate($item->url) ?>">
                        <input type="hidden" class="menu-item-classes" name="menu-item[-2][menu-item-classes]">
                    </li>
                <?php } ?>
            </ul>

            <p class="button-controls">
			<span class="list-controls">
				<a href="<?php
                echo (add_query_arg(
                    array(
                        'my-plugin-all' => 'all',
                        'selectall' => 1,
                    ),
                    remove_query_arg( $removed_args )
                ));
                ?>#my-menu-test-metabox" class="select-all"><?php esc_html_e( 'Select All','wpbookinghotel' ); ?></a>
			</span>

                <span class="add-to-menu">
				<input type="submit"<?php wp_nav_menu_disabled_check( $nav_menu_selected_id ); ?> class="button-secondary submit-add-to-menu right" value="<?php esc_attr_e( 'Add to Menu' ,'wpbookinghotel'); ?>" name="add-my-plugin-menu-item" id="submit-my-plugin-div" />
				<span class="spinner"></span>
			</span>
            </p>
        </div>
        <?php
    }
    public static function get_list_layout_view_frontend()
    {

        $views_path = WPBOOKINGHOTEL_APP_FRONTEND_PATH . "/views";

        $list_view = array();
        $folders = Folder::folders($views_path);


        foreach ($folders as $view) {
            $view_path = $views_path . "/$view";
            if (!Folder::exists($view_path . "/tmpl")) {
                continue;
            }
            $files = Folder::files($view_path . "/tmpl", ".xml");


            foreach ($files as $file) {
                if (strpos($file, "config_") === 0) {
                    continue;
                }
                $xmlFile = pathinfo($file);
                $filename = $xmlFile['filename'];
                $file_path = $view_path . "/tmpl/$file";
                $title = "";
                $show_main_menu = true;
                $xml = simplexml_load_file($file_path);

                try {
                    $attributes=$xml->layout->attributes();
                    $title = (string)$attributes['title'];
                    $bool = (string)$attributes['show_main_menu'];
                    $show_main_menu = filter_var($bool, FILTER_VALIDATE_BOOLEAN);;
                } catch (Exception $e) {
                    echo ('PLEASE_CHECK_FILE_TRUCTOR_XML');
                    die;
                }
                $title = esc_html($title);
                if (!$title) {
                    continue;
                }
                $list_view["$view-$filename"] = array(
                    "title" => $title,
                    "show_main_menu" => $show_main_menu
                );


            }
        }
        return $list_view;
    }

    public static function get_list_view_for_woo_panel()
    {
        if (empty(static::$items_submenus)) {
            $list_menu_by_xml = self::get_list_view_xml();
            $confingModel = Model::getInstance('config');
            $list_view = $confingModel->get_list_view_publish();
            $items_submenus = array();
            $index = 21;

            $config = Factory::getConfig();
            $environment = $config->get('environment', 'production');
            $list_environment = array(
                "production"
            );
            if ($environment == "development") {
                $list_environment[] = "development";
            }

            foreach ($list_menu_by_xml as $view) {

                if (in_array($view->environment, $list_environment) && ($view->is_system || in_array($view->menu_slug,
                            $list_view))) {
                    $items_submenus[] = array(
                        'id' => self::$prefix_link . $view->id,
                        'menu_slug' => self::$prefix_link . $view->menu_slug,
                        'label' => $view->label,
                        'page_title' => $view->page_title,
                        'capability' => $view->capability,
                        'icon' => $view->icon,
                        "item_url" => $view->item_url,
                        "layout" => $view->layout,
                        "environment" => $view->environment
                    );

                    $index++;
                }

            }
            self::$items_submenus = $items_submenus;
        }


        return self::$items_submenus;
    }

    public static function get_list_view_xml()
    {

        if (empty(self::$list_menu_by_xml)) {
            $file_xml_path_app = WPBOOKINGHOTEL_APP_BACKEND_PATH . "/views.xml";
            $xml = simplexml_load_file($file_xml_path_app);


            $list_menu_by_xml = array();
            foreach ($xml->view as $view) {
                $attributes=$view->attributes();
                $environment = (string)$attributes['environment'];
                if (!$environment) {
                    $environment = "production";
                }
                $list_menu_by_xml[] = (object)array(
                    'id' => (string)$attributes['id'],
                    'menu_slug' => (string)$attributes['menu_slug'],
                    'label' => (string)$attributes['label'],
                    'page_title' => (string)$attributes['page_title'],
                    'capability' => (string)$attributes['capability'],
                    'icon' => (string)$attributes['icon'],
                    'class' => (string)$attributes['class'],
                    'is_system' => (boolean)$attributes['is_system'],
                    'item_url' => (string)$attributes['item_url'],
                    'layout' => (string)$attributes['layout'],
                    'environment' => $environment

                );


            }
            self::$list_menu_by_xml = $list_menu_by_xml;
        }
        return self::$list_menu_by_xml;
    }
        public static function checkInstalled()
    {
        $app = Factory::getApplication(1);
        $db = Factory::getDBO();
        $installed = true;
        $list_table_in_database = $db->setQuery("SHOW TABLES LIKE " . $db->quote("woobooking\\_%"))->loadColumn();
        if (count($list_table_in_database) == 0) {
            $installed = false;
        }
        $json_table_need_install = File::read(WPBOOKINGHOTEL_PLUGIN_DIR_URL . "/install/tables.json");

        $json_table_need_install = json_decode($json_table_need_install);

        foreach ($json_table_need_install as $need_table) {
            if (!in_array($need_table, $list_table_in_database)) {
                $installed = false;
                break;
            }
        }
        return $installed;
    }
    function goToPopupInstall()
    {
        $root_url = Factory::getRootUrl();
        $html = '<html><head>';
        $html .= '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
        $html .= '<script>document.location.href=' . json_encode(str_replace("'", '&apos;',
                $root_url . '/wp-admin/admin.php?page=wb_config&layout=install')) . ';</script>';
        $html .= '</head><body></body></html>';
        echo ($html);
    }
   public function tour_op_generate_rewrite_rules()
    {
        $wordpress=Factory::getWordpress(1);
        if(!$wordpress->checkInstalled()) { return; }
        parent::tour_op_generate_rewrite_rules();

    }

    function wpbookinghotel_page()
    {
        $input = Factory::getInput();
        $page = $input->getString('page', '');
        $layout=$input->getString('layout',"");
        if($page=="wb_config"){
            if($layout!=="install" && !self::checkInstalled()){
                self::goToPopupInstall();
            }
        }elseif(!self::checkInstalled()){
            self::goToPopupInstall();
        }
        require_once WPBOOKINGHOTEL_PATH_ROOT.DS."admin/app/Html/HtmlBackend.php";
        WpBookingHotelHtmlBackend::load_jquery_library('less');
        WpBookingHotelHtmlBackend::load_jquery_library('debug');
        WpBookingHotelHtmlBackend::load_jquery_library('bootstrap');
        WpBookingHotelHtmlBackend::load_jquery_library('tooltip');
        WpBookingHotelHtmlBackend::load_jquery_library('main_app');
        WpBookingHotelHtmlBackend::load_jquery_library('awesome');
        WpBookingHotelHtmlBackend::load_jquery_library('confirm');
        wp_enqueue_editor();
        wp_enqueue_media();
        $input = Factory::getInput();
        $data = $input->getData();
        $task = array_key_exists('task', $data) ? $data['task'] : null;
        $layout = array_key_exists('layout', $data) ? $data['layout'] : null;
        $layout = $layout ? $layout : "list";
        $menu = self::get_true_menu_of_woo_booking($page);
        $file_controller_path = WPBOOKINGHOTEL_APP_BACKEND_PATH . "/controllers/" . ucfirst($menu) . "Controller.php";
        $file_controller_short_path = Utility::get_short_file_by_path($file_controller_path);

        if (file_exists($file_controller_path)) {

            $class_name = "WpBookingHotelAdmin\\app\\controllers\\".ucfirst($menu) . "Controller";
            if (class_exists($class_name)) {
                $class_controller = new $class_name();
                $content=$class_controller->view("$menu.$layout");
                $toolbar=ToolBar::render_toolbar();
                echo '<div class="wrapper-wpbooking-hotel-view-admin">'.$toolbar.$content.$toolbar.'</div>';
            } else {
                echo ('CLASS'.$class_name.'NOT_EXIT_IN_FILE'.$file_controller_short_path.'PLEASE_CREATE_THIS_CLASS');
            }
        } else {
            echo ('FILE_CONTROLLER_NOT_FOUND_PLEASE_CREATE_FILE '.$file_controller_short_path);
        }
        add_action('admin_footer', array($this, 'wp_hook_add_script_footer'));
    }
    public function wp_hook_add_script_footer(){
        global $wp;

        wp_enqueue_script("jquery");
        $doc = Factory::getDocument();

        $lessStyleSheets = $doc->getLessStyleSheets();
        $config=Factory::getConfig();

        $environment=$config->get('environment',"development");
        if($environment=="development") {
            foreach ($lessStyleSheets as $src=> $item) {
                ob_start();
                ?>
                <link rel="stylesheet/less" type="text/css"
                      href="<?php  Text::_echo(WPBOOKINGHOTEL_PLUGIN_DIR_URL . "/" . $src) ?>"/>
                <?php
                echo (ob_get_clean());
            }
        }else{
            $doc->addStyleSheet('admin/app/assets/less/style.css');
        }

        $styleSheets = $doc->getStyleSheets();
        foreach ($styleSheets as $src => $item) {
            $random = random_int(100000, 900000);
            if (strpos($src, 'http') !== false) {
                wp_enqueue_style('wpbookinghotel-css-' . $random, $src);
            } else {
                wp_enqueue_style('wpbookinghotel-css-' . $random, WPBOOKINGHOTEL_PLUGIN_DIR_URL . '/' . $src);
            }
        }
        ob_start();
        ?>
        <script type="text/javascript">
            var wpbookinghotel_root_url = "<?php  echo (WPBOOKINGHOTEL_SITE_URL) ?>";
            var wpbookinghotel_current_url = "<?php  echo (WPBOOKINGHOTEL_SITE_URL) ?>";
            var wpbookinghotel_root_url_plugin = "<?php echo (WPBOOKINGHOTEL_PLUGIN_DIR_URL); ?>/";
            var wpbookinghotel_api_task = "/wp-json/<?php echo (self::$namespace.$this->get_api_task()) ?>";
        </script>
        <?php
        $content=ob_get_clean();
        $content= Utility::remove_string_javascript($content);
        wp_enqueue_script('wpbookinghotel-js-init', WPBOOKINGHOTEL_PLUGIN_DIR_URL .'frontend/resources/init.js' );
        wp_add_inline_script('wpbookinghotel-js-init', $content);

        $scripts = $doc->getScripts();

        foreach ($scripts as $src => $item){
            try {
                $random = random_int(100000, 900000);
                if (strpos($src, 'http') !== false || strpos($src, 'https') !== false) {
                    wp_enqueue_script('wpbookinghotel-js-out-site'.$random,$src,array('jquery') );
                } else {
                    $src=WPBOOKINGHOTEL_PLUGIN_DIR_URL . $src;
                    wp_enqueue_script('wpbookinghotel-js-in-site-'.$random, $src,array('jquery') );
                }
            } catch (Exception $e) {
            }

        }
        wp_enqueue_script('wpbookinghotel-js-defined', WPBOOKINGHOTEL_PLUGIN_DIR_URL .'frontend/resources/define.js' );
        $doc=Factory::getDocument();
        $script = $doc->getScript();
        foreach ($script as $content) {
            wp_add_inline_script('wpbookinghotel-js-defined', $content);
        }
    }

    private static function get_true_menu_of_woo_booking($menu)
    {
        return str_replace(self::$prefix_link, "", $menu);
    }



}