<?php
namespace WpBookingHotel\Wordpress;

use Exception;
use WpBookingHotel\Html\WpBookingHotelHtmlWooPanel;
use WpBookingHotel\Factory;
use WpBookingHotel\Filesystem\File;
use WpBookingHotel\Html\ToolBar;


use WpBookingHotel\Log\Log;
use WpBookingHotel\Mvc\Controller\Controller;
use WpBookingHotel\Mvc\Model\Model;
use WpBookingHotel\Mvc\View\View;
use WpBookingHotel\Utilities\Utility;
use WpBookingHotel\Language\Text;
/**
 * Class Wordpress
 * @package WpBookingHotel\Wordpress
 */
class WordpressAdminWoopanel extends Wordpress
{

    /**
     * @var
     */
    private static $instance;
    public static $key_woo_booking = "woobooking";
    public static $prefix_link = "wb_";
    /**
     * @var string
     */
    public static $namespace = "wpbookinghotel_api/1.0";
    /**
     * @var int
     */
    private $clientId=2;
    private $init_GutembergBlock=0;
    public function init(){
        if(!$this->is_admin()) {
            add_action( 'init', array( $this, 'init_wordpress' ) );
            add_action( 'woopanel_menus', array($this,'add_menu_to_woopanel') );
            //add_filter( 'woopanel_submenus', array( $this, 'add_sub_menu_to_woopanel') );
            add_filter( 'woopanel_vendor_query_var', array( $this, 'woopanel_query_var_filter') );
            add_action('woopanel_footer', array($this, 'wp_hook_add_script_footer'));
            add_filter('woopanel_critical_path', array($this,'woopanel_critical_css'), 30, 3);
            add_filter('woopanel_critical_url', array($this,'woopanel_critical_css'), 30, 3);
            add_action( 'wp_ajax_action_ajax_by_task', array($this,'wp_appointment_action_ajax_by_task') );
            add_action( 'wp_ajax_nopriv_action_ajax_by_task',   array($this,'wp_appointment_action_ajax_by_task') );

            $list_view_for_woo_panel=WordpressAdmin::get_list_view_for_woo_panel();

            foreach ($list_view_for_woo_panel as $menu){
                $menu=(object)$menu;
                add_action( "woopanel_dashboard_{$menu->id}_endpoint", array($this,'render_page_by_endpoint_woopanel') );
            }

            add_action( 'woopanel_enqueue_scripts', array($this,'wp_enqueue_scripts') );



            WpBookingHotelHtmlWooPanel::load_jquery_library('less');
            WpBookingHotelHtmlWooPanel::load_jquery_library('main_app');
            WpBookingHotelHtmlWooPanel::load_jquery_library('lazy_load');
            WpBookingHotelHtmlWooPanel::load_jquery_library('bootstrap');

            $path = "wp-content/plugins/wpbookinghotel/frontend/app/views.xml";
            add_shortcode('wpbookinghotel', array($this, "front_end_render_view"));
            add_action('rest_api_init', array($this, 'wp_register_rest_route'));
            $list_view = $this->get_list_layout_block_frontend();

        }



    }
    public function tour_op_generate_rewrite_rules()
    {
        $wordpress=Factory::getWordpress(2);
        if(!$wordpress->checkInstalled()) { return; }
        parent::tour_op_generate_rewrite_rules();

    }
    public static function wp_appointment_action_ajax_by_task(){
        $input=Factory::getInput();
        $task=$input->getString("task","");

        if ($task) {
            list($controller, $task) = explode(".", $task);
            $class_name ="WpBookingHotelAdminWooPanel\app\\controllers\\". ucfirst($controller) . "Controller";
            if (class_exists($class_name)) {
                $class_controller = new $class_name();
                if (method_exists($class_controller, $task)) {
                    //not return
                    call_user_func(array($class_controller, $task));

                }
            }
        }
    }
    public static function woopanel_critical_css( $path, $type, $route) {
        $routeRewrite = array(
            "wb_activities",
            "wb_amenity",
            "wb_block",
            "wb_calendar",
            "wb_category",
            "wb_wishlist",
            "wb_config",
            "wb_countries",
            "wb_customers",
            "wb_customize",
            "wb_dashboard",
            "wb_discount",
            "wb_hotel",
            "wb_location",
            "wb_orders",
            "wb_orderstatus",
            "wb_payment",
            "wb_review",
            "wb_roomtype",
            "wb_service",
            "wb_sms",
            "wb_smscontent",
            "wb_states",
            "wb_tool",
        );


        if( in_array($route, $routeRewrite) ) {
            if( $type == 'path') {
                $path = WPBOOKINGHOTEL_ADMIN_WOOPANEL_PATH.DS."app/assets/woopanel-criticle";
            }else {
                $path = WPBOOKINGHOTEL_PLUGIN_DIR_URL.DS."admin_woopanel/app/assets/woopanel-criticle";
            }
        }
        return $path;
    }

    public static function add_menu_to_woopanel($woopanel_menus) {

        // remove woocommerce menu
        foreach($woopanel_menus as $index => $menu) {
            if($menu['id'] != 'logout' && $menu['id'] != 'settings') {
                unset($woopanel_menus[$index]);
            }
        }
        $list_view_for_woo_panel=WordpressAdmin::get_list_view_for_woo_panel();
        for($i=0;$i<count($list_view_for_woo_panel);$i++) {
            $view=$list_view_for_woo_panel[$i];
            $view=(object)$view;
            $woopanel_menus[$i+4]=array(
                "id"=>$view->id,
                "menu_slug"=>$view->menu_slug,
                "menu_title"=>$view->label,
                "capability"=>"",
                "page_title"=>$view->label,
                "icon"=> $view->icon,
                "classes"=>$view->menu_slug,
                "permission"=>"global",
            );
        }

        return $woopanel_menus;

    }
    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;
    }
    private static function get_true_menu_of_woo_booking($menu)
    {
        return str_replace(self::$prefix_link, "", $menu);
    }


    public static function render_page_by_endpoint_woopanel(){
        $input = Factory::getInput();
        $woopanel_page = $input->getString('page', '');
        $layout=$input->getString('layout',"");
        if($woopanel_page=="wb_config"){
            if($layout!=="install" && !self::checkInstalled()){
                self::goToPopupInstall();
                return;
            }
        }elseif(!self::checkInstalled()){
            self::goToPopupInstall();
            return;
        }
        require_once WPBOOKINGHOTEL_PATH_ROOT.DS."admin/app/Html/HtmlBackend.php";
        WpBookingHotelHtmlWooPanel::load_jquery_library('less');
        WpBookingHotelHtmlWooPanel::load_jquery_library('debug');
        WpBookingHotelHtmlWooPanel::load_jquery_library('bootstrap');
        WpBookingHotelHtmlWooPanel::load_jquery_library('tooltip');
        WpBookingHotelHtmlWooPanel::load_jquery_library('main_app');
        WpBookingHotelHtmlWooPanel::load_jquery_library('awesome');
        WpBookingHotelHtmlWooPanel::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";
        $query_vars = WooDashboard()->query->query_vars;

        $woopanel_page=$input->getString('woopanel_page',"");
        $file_controller_path = WPBOOKINGHOTEL_APP_BACKEND_PATH . "/controllers/" . ucfirst($woopanel_page) . "Controller.php";
        $file_controller_short_path = Utility::get_short_file_by_path($file_controller_path);

        if (file_exists($file_controller_path)) {

            $class_name = "WpBookingHotelAdminWooPanel\\app\\controllers\\".ucfirst($woopanel_page) . "Controller";

            if (class_exists($class_name)) {
                $class_controller = new $class_name();
                $content=$class_controller->view("$woopanel_page.$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);
        }
        $word_press=Factory::getWordpress(2);

        add_action('admin_footer', array($word_press, 'wp_hook_add_script_footer'));
    }

    public static 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 static function add_sub_menu_to_woopanel($woopanel_submenus){
        $list_view_for_woo_panel=WordpressAdmin::get_list_view_for_woo_panel();

        $woopanel_submenus['wp_bookinghotel']=($list_view_for_woo_panel);
       return $woopanel_submenus;

    }
    public function woopanel_query_var_filter( $query_vars ) {
        $list_view_for_woo_panel=WordpressAdmin::get_list_view_for_woo_panel();
        foreach ($list_view_for_woo_panel as $menu){
            $menu=(object)$menu;
            $query_vars[] = $menu->id;
        }
        return $query_vars;
    }
    public static function wp_enqueue_scripts(){
        $config=Factory::getConfig();
        $environment=$config->get('environment',"development");
        if($environment=="production") {
            wp_enqueue_style( 'wpbookinghotel-bootstrap-style', WPBOOKINGHOTEL_PLUGIN_DIR_URL . '/admin_woopanel/resources/bootstrap3.3.7/bootstrap.min.css', array());
            wp_enqueue_style( 'wpbookinghotel-main-woopanel-admin-style', WPBOOKINGHOTEL_PLUGIN_DIR_URL . '/admin_woopanel/app/assets/less/style.css', array());
        }else{

        }


    }
    public function wp_register_rest_route(){
        register_rest_route(
            self::$namespace,
            "wpbookinghotel_backend_woopanel/task",
            array(
                'methods' => 'POST',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
        register_rest_route(
            self::$namespace,
            "wpbookinghotel_backend_woopanel/task",
            array(
                'methods' => 'GET',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
    }

    public function init_wordpress(){
        load_plugin_textdomain( 'wpbookinghotel', false, WPBOOKINGHOTEL_PATH_ROOT . '/languages/' );
        $input=Factory::getInput();
        $data=$input->getData();
        if(isset($data['_locale'])){
            return false;
        }
        $task=$input->getString('task',"");
        if ($task) {
            list($controller, $task) = explode(".", $task);
            $class_name ="WpBookingHotelAdminWooPanel\app\\controllers\\". ucfirst($controller) . "Controller";
            if (class_exists($class_name)) {
                $class_controller = new $class_name();
                if (method_exists($class_controller, $task)) {
                    //not return
                    call_user_func(array($class_controller, $task));

                }
            }
        }
    }

    function woo_booking_render_block_by_tag_func($atts, $content, $a_view)
    {


        $input = Factory::getInput();
        if (is_array($atts) && $id = reset($atts)) {

            list($package, $block, $block_name) = explode("-", $a_view);

            wp_kses(Controller::view_block_module($id, $block_name),true);
        }
        return false;
    }
    public function getKeyWooBooking()
    {
        return self::$key_woo_booking;
    }

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

    }
    public function front_end_render_view($params,$option,$view){
        $input=Factory::getInput();
        WpBookingHotelHtmlWooPanel::load_jquery_library('bootstrap');
        $view=isset($params['view'])?$params['view']:"services-list";
        $a_view=$input->getString('view',"");
        if($a_view){
            $view=$a_view;
        }
        list($view, $layout) = explode("-", $view);

        echo (Controller::view("$view.$layout"));


    }
    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());
            }
        }
        $styleSheets = $doc->getStyleSheets();
        foreach ($styleSheets as $src => $item) {
            $random = random_int(0, 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);
        }
    }


}