<?php
namespace WpBookingPro\Wordpress;

use Exception;
use WpBookingPro\Factory;
use WpBookingPro\Filesystem\File;
use WpBookingPro\Html\WpBookingProHtmlBackend;
use WpBookingPro\Html\WpBookingProHtmlFrontend;
use WpBookingPro\Log\Log;
use WpBookingPro\Mvc\Controller\Controller;
use WpBookingPro\Mvc\Model\Model;
use WpBookingPro\Mvc\View\View;
use WpBookingPro\Utilities\Utility;
use WpBookingPro\Language\Text;
use WpBookingPro\Wordpress\ECommerce\ECommerce;
use WpBookingProFrontend\app\helpers\ConfigHelper;
use WpBookingProFrontend\app\helpers\FrontendHelper;
/**
 * Class Wordpress
 * @package WpBookingPro\Wordpress
 */
class WordpressSite extends Wordpress
{

    /**
     * @var
     */
    private static $instance;
    public static $key_woo_booking = "woobooking";
    public static $prefix_link = "wb_";
    /**
     * @var string
     */
    public static $namespace = "wpbookingpro_api/1.0";
    private static $parsed_route=false;
    /**
     * @var int
     */
    private $clientId=0;
    private $init_GutembergBlock=0;
    public function init(){

        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') );
        add_filter( 'wp_title', array($this,'theme_slug_filter_wp_title' ));

        if(!$this->is_admin()) {
            if(session_id() == '')
                session_start();
            //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('user_register',array($this,'sync_user_hook_wp'));
            add_action('wp_login', array($this,'do_anything'),10, 2);



            if(isset($_SESSION['remember']) && $_SESSION['remember']) {
                add_action('after_setup_theme',array($this,'auto_login_activation'));
            }

            $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( 'wp_enqueue_scripts', array($this,'wp_enqueue_scripts') );
            $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 ="WpBookingProFrontend\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));

                    }
                }
            }

            add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
            $path = WPBOOKINGPRO_PATH_ROOT . "frontend/app/views.xml";
            add_shortcode('wpbookingpro', 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();

            foreach ($list_view as $key => $view) {
                $a_key = self::$key_wpbookingpro . "-block-" . $key;
                add_shortcode($a_key, array($this, 'woo_booking_render_block_by_tag_func'));
            }
            add_action( 'wp_head', array($this,'gretathemes_meta_description'));
            add_filter('pre_get_document_title',array($this,'add_title_for_service'),10, 3 );

            $gutembergBlock = GutembergBlock::getInstance();
            $gutembergBlock->init();
            $widgets = Widgets::getInstance();
            $widgets->init();

            $motopress = Motopress::getInstance();
            $motopress->init();

            $eCommerce = ECommerce::getInstance();
            $eCommerce->init();
            add_action('wp_footer', array($this, 'wp_hook_add_script_footer'));
            add_filter( 'init', array($this,"service_op_generate_rewrite_rules"));

        }



    }



    function add_title_for_service(){
        $title="";
        $this->parse_route();
        $input = Factory::getInput();

        $service_id = $input->getInt('service_id',0);
        $modelService= Model::getInstance('service');
        $service=$modelService->getItem($service_id);
        if(isset($service->id)) {
            $title=$service->name;
        }
        return $title;
    }
    public function parse_route(){

        if(!static::$parsed_route) {
            $input = Factory::getInput();
            $uri = Factory::getUri();
            $app = Factory::getApplication(0);
            $_router = $app->getRouter(0);
            $vars = $_router->parse($uri);
            foreach ($vars as $key => $value) {
                $input->set($key, $value);
            }
        }
    }
    function gretathemes_meta_description() {
        $this->parse_route();
        $input = Factory::getInput();
        $service_id = $input->getInt('service_id',0);
        $modelService=Model::getInstance('service');
        $content="";

        $service=$modelService->getItem($service_id);
        if(isset($service->id)) {
            ob_start();
            ?>
            <meta name="description" content="<?php esc_attr_e($service->meta_description) ?>"/>
            <meta name="keyword" content="<?php esc_attr_e($service->meta_keyword) ?>"/>

            <?php
            $content = ob_get_clean();
        }
        echo $content;
    }
    public function service_op_generate_rewrite_rules()
    {
        $wordpress=Factory::getWordpress(0);
        if(!$wordpress->checkInstalled()) { return; }
        parent::service_op_generate_rewrite_rules();

    }
    public function theme_slug_filter_wp_title( $title ) {
        if ( is_404() ) {
            $title = 'ADD 404 TITLE TEXT HERE';
        }
        // You can do other filtering here, or
        // just return $title
        return $title;
    }



    function do_anything($user_login, $user) {
        $_SESSION['user_id'] = $user->ID;
        $_SESSION['user_login'] = $user_login;

    }

    function sync_user_hook_wp($user_id){
        $appConfig = Factory::getAppConfig();
        $default_groupuser_signup = $appConfig->get('default_groupuser_signup', '');
        global $wpdb;
        $email = $wpdb->get_var($wpdb->prepare("SELECT user_email FROM $wpdb->users  WHERE ID = %s", $user_id));
        $modelUser = Model::getInstance('user');
        $modelUser->save(array("open_source_user_id"=>$user_id,"email"=>$email,"group_user_id"=>(int)$default_groupuser_signup));

    }


    function auto_login_activation() {
        $user_id = $_SESSION['user_id'];
        $user_login = $_SESSION['user_login'];
        $user = get_user_by('login',  $user_login);
        wp_clear_auth_cookie();
        wp_set_current_user ( $user_id );
        wp_set_auth_cookie  ( $user_id, true, is_ssl());
        do_action('wp_login', $user_login, $user);

    }

    public static function add_menu_to_woopanel($woopanel_menus){
        $woopanel_menus[4]=array(
            "id"=>"wp_appointment",
            "menu_slug"=>"wp_appointment",
            "menu_title"=>"wp appointment",
            "capability"=>"",
            "page_title"=>"wp appointment",
            "icon"=>"flaticon-line-graph",
            "classes"=>"wp-appointment",
            "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(WPBOOKINGPRO_PATH_ROOT . "/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 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_appointment']=($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_appointment_action_ajax_by_task(){
        $input = Factory::getInput();
        $task=$input->getString("task","");
        if ($task) {
            list($controller, $task) = explode(".", $task);
            $class_name ="WpBookingProFrontend\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));

                }
            }
        }
    }

    /**
     * start session
     */
    function session_start() {
        echo "hello session_start";
        die;
        if(!session_id()) {

            session_start();

        }

    }
    public function render_code_inline_script($selector, $function_name,$config){
        ob_start();
        ?>
            jQuery(document).ready(function ($) {
                $('<?php echo $selector ?>').<?php echo $function_name ?>(<?php echo json_encode($config) ?>);
            });
        <?php

        return ob_get_clean();
    }
    
    public function wp_enqueue_scripts(){
        wp_enqueue_script('jquery-ui-core');
        $depends = array( 'jquery');
        $config=Factory::getConfig();
        $environment=$config->get('environment',"development");
        if($environment=="production" || $environment == 'demo') {
            wp_enqueue_style( 'wpbookingpro-main-frontend-style', WPBOOKINGPRO_PLUGIN_DIR_URL . '/frontend/app/assets/less/style.css', array());
           
        }
        $daterangepicker_depends = array( 'jquery','wb_moment');
        wp_enqueue_style( 'wb_bootstrap', WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/bootstrap3.3.7/bootstrap.min.css');
        wp_enqueue_style( 'wb_owlcarousel2', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/OwlCarousel2-2.3.4/dist/assets/owl.carousel.min.css');
        wp_enqueue_style( 'wb_fontawesome', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/fontawesome-free-5.12.1/css/all.min.css');
        wp_enqueue_style( 'wb_select2', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/select2-4.0.12/dist/css/select2.css');
        wp_enqueue_style( 'wb_daterangepicker', WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/daterangepicker-master/daterangepicker.css');
        wp_enqueue_style( 'wb_icheck', WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/icheck-1.x/skins/all.css');
        wp_enqueue_style( 'wb_bootstrap_datetimepicker', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css');
        wp_register_script ( 'wb_less', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/less/less.min.js'  ,$depends,WPBOOKINGPRO_VERSION);
        wp_register_script ( 'wb_main_app', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/app/assets/js/view_main_app.js' ,$depends,WPBOOKINGPRO_VERSION );
        wp_register_script ( 'wb_lazyload', WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/jquery.lazy/jquery.lazy.js' ,$depends,WPBOOKINGPRO_VERSION );
        wp_register_script ( 'wb_bootstrap', WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/bootstrap3.3.7/bootstrap.min.js' ,$depends,WPBOOKINGPRO_VERSION );
        wp_register_script ( 'wb_owlcarousel2', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/OwlCarousel2-2.3.4/dist/owl.carousel.min.js' ,$depends,WPBOOKINGPRO_VERSION );
        wp_register_script ( 'wb_select2', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/select2-4.0.12/dist/js/select2.full.js' ,$depends,WPBOOKINGPRO_VERSION );
        wp_register_script ( 'wb_moment', WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/daterangepicker-master/moment.min.js' ,$depends,WPBOOKINGPRO_VERSION );
        wp_register_script ( 'wb_daterangepicker', WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/daterangepicker-master/daterangepicker.js' ,$daterangepicker_depends,WPBOOKINGPRO_VERSION );
        wp_register_script ( 'wb_icheck', WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/icheck-1.x/icheck.min.js' ,$depends,WPBOOKINGPRO_VERSION );
        wp_register_script ( 'wb_bootstrap_datetimepicker', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/bootstrap-datetimepicker-master/js/bootstrap-datetimepicker.min.js' ,$depends,WPBOOKINGPRO_VERSION );
        $code = $this->render_code_inline_script('body', 'view_main_app_frontend', array());
        wp_add_inline_script( 'wb_main_app', $code );

        $script = array('wb_less', 'wb_main_app','wb_lazyload' , 'wb_bootstrap','wb_owlcarousel2','wb_moment','wb_daterangepicker','wb_icheck','wb_bootstrap_datetimepicker');
        if(wc_post_content_has_shortcode( 'wpbookingpro' )){
            global $post;
            global $shortcode_tags;
            $content = $post->post_content;
            $content = str_replace(']' , ' /]',$content);
            $view_attr = shortcode_parse_atts($content);
            $view = $view_attr['view'] ? $view_attr['view'] : 'services-list';
            $scripts = array(
                array(
                    'name'  =>  'wb_jquery_datatable',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/datatables/jquery.dataTables.js',
                ),
                array(
                    'name'  =>  'wb_loading_js',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/Fullscreen-Loading-Modal-Indicator/js/jquery.loadingModal.min.js',
                ),
                array(
                    'name'  =>  'wb_confirm',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/jquery-confirm-master/dist/jquery-confirm.min.js',
                ),
                array(
                    'name'  =>  'wb_paginate',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/twbs-pagination/jquery.twbsPagination.min.js',
                ),
                array(
                    'name'  =>  'wb_select_yes_no',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/Toggle-Switches/lc_switch.js',
                ),
                array(
                    'name'  =>  'wb_tooltipster',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/tooltipster/dist/js/tooltipster.bundle.js',
                ),
                array(
                    'name'  =>  'wb_dateselect',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/DateSelect/js/jquery.dateselect.min.js',
                ),
                array(
                    'name'  =>  'wb_daterangepicker',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/daterangepicker-master/daterangepicker.js',
                ),
                array(
                    'name'  =>  'wb_autoNumeric',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/autoNumeric/autoNumeric.js',
                ),
                array(
                    'name'  =>  'wb_slick',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/slick/slick.js',
                ),
                array(
                    'name'  =>  'wb_datetimepicker1',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/datetimepicker/bootstrap-datetimepicker.js',
                ),
            );
            $styles = array(
                array(
                    'name'  =>  'wb_jquery_datatable',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/datatables/DataTables-1.10.20/css/jquery.dataTables.min.css',
                ),
                array(
                    'name'  =>  'wb_loading_js',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/Fullscreen-Loading-Modal-Indicator/css/jquery.loadingModal.min.css',
                ),
                array(
                    'name'  =>  'wb_confirm',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/jquery-confirm-master/dist/jquery-confirm.min.css',
                ),
                array(
                    'name'  =>  'wb_font-icon',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/app/assets/nb-font-icon/nb-font-icon.css',
                ),
                array(
                    'name'  =>  'wb_select_yes_no',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/Toggle-Switches/lc_switch.css',
                ),
                array(
                    'name'  =>  'wb_tooltipster',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/tooltipster/dist/css/tooltipster.bundle.css',
                ),
                array(
                    'name'  =>  'wb_dateselect',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/DateSelect/css/jquery.dateselect.css',
                ),
                array(
                    'name'  =>  'wb_daterangepicker',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/daterangepicker-master/daterangepicker.css',
                ),
                array(
                    'name'  =>  'wb_slick',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/slick/slick.css',
                ),
                array(
                    'name'  =>  'wb_theme_slick',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/slick/slick-theme.css',
                ),
                array(
                    'name'  =>  'wb_datetimepicker1',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/datetimepicker/bootstrap-datetimepicker.css',
                ),
                array(
                    'name'  =>  'wb_glyphicons',
                    'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/glyphicons/bootstrap-glyphicons.css',
                ),
            );
            if($view == 'vendors-list'){
                $modelVendors = Model::getInstance('vendors');
                $total_vendor = $modelVendors->getTotalVendorNoPagination();
                $limit = 8;
                wp_register_script ( 'wb_vendors_list', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/app/assets/js/view_list_vendors.js' ,$depends,WPBOOKINGPRO_VERSION );
                $code = $this->render_code_inline_script('.view-list-vendors','view_list_vendors',array(
                    "limit"=>$limit,
                    "total_result"=>$total_vendor
                ));
                wp_add_inline_script( 'wb_vendors_list', $code );
                $script[] = 'wb_vendors_list';
            }
            if($view == 'vendor-detail'){
                $extra_style = array();
                $extra_scripts = array(
                    array(
                        'name'  =>  'wb_validate',
                        'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/jquery-validation/dist/jquery.validate.js',
                    ),
                    array(
                        'name'  =>  'wb_twbsPagination',
                        'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/twbs-pagination/jquery.twbsPagination.min.js',
                    ),
                );
                $modelVendor = Model::getInstance('vendor');
                $vendor = $modelVendor->getInfoVendor($user_id);
                $limit = 8;
                $scripts = array_merge($scripts,$extra_scripts);
                $styles = array_merge($styles,$extra_style);
                wp_register_script ( 'wb_vendors_detail', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/app/assets/js/view_vendor_detail.js' ,$depends,WPBOOKINGPRO_VERSION );
                $code = $this->render_code_inline_script('.view-vendor-detail','view_vendor_detail',array(
                    "list_category"=>!empty($vendor)&& isset($vendor->list_category) ? $vendor->list_category: array(),
                    "limit"=>$limit,
                    "user_id"=> !empty($vendor)&& isset($vendor->id)?$vendor->id:'',
                    "list_review"=>!empty($vendor)&& isset($vendor->list_review)?$vendor->list_review:array(),
                    "user_id_login"=> isset($_SESSION['user_id'])?$_SESSION['user_id']:''
                ));
                wp_add_inline_script( 'wb_vendors_detail', $code );
                $script[] = 'wb_vendors_detail';
            }
            if($view == 'signup-list'){
                $extra_scripts = array(
                    array(
                        'name'  =>  'wb_validate',
                        'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/jquery-validation/dist/jquery.validate.js',
                    ),
                );
                $scripts = array_merge($scripts,$extra_scripts);
                wp_register_script ( 'wb_view_signup', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/app/assets/js/view_signup.js' ,$depends,WPBOOKINGPRO_VERSION );
                $code = $this->render_code_inline_script('.view-signup','view_signup',array());
                wp_add_inline_script( 'wb_view_signup', $code );
                $script[] = 'wb_view_signup';
            }
            if($view == 'services-list'){
                $extra_scripts = array(
                    array(
                        'name'  =>  'wb_twbsPagination',
                        'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/twbs-pagination/jquery.twbsPagination.min.js',
                    ),
                );
                $scripts = array_merge($scripts,$extra_scripts);
                wp_register_script ( 'wb_list_services', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/app/assets/js/view_list_services.js' ,$depends,WPBOOKINGPRO_VERSION );
                $page_list_service= ConfigHelper::get_page_list_service();
                $input = Factory::getInput();
                $price_search = $input->getString('price_search','');
                $price_search = json_decode($price_search);
                if(is_array($price_search) && !empty($price_search) && count($price_search) == 2) {
                    $min_price_search = min($price_search);
                    $max_price_search = max($price_search);
                } else {
                    $min_price_search = 0;
                    $max_price_search = 1099;
                }
                $limit = 9;
                $modelServices=Model::getInstance('services');
                $list=$modelServices->getList();
                $code = $this->render_code_inline_script('.view-list-services','view_list_services',array(
                    "page_list_service"=>$page_list_service,
                    "min_price"=>$min_price_search,
                    "max_price"=>$max_price_search,
                    "user_id"=> isset($_SESSION['user_id'])?$_SESSION['user_id']:'',
                    "limit"=>$limit,
                    "list_service"=>$list,
                    "format_currency"=> FrontendHelper::getFormatCurrentCurrency()
                ));
                wp_add_inline_script( 'wb_list_services', $code );
                $script[] = 'wb_select2';
                $script[] = 'wb_list_services';
            }
            if($view == 'servicelocator-list'){
                $appConfig = Factory::getAppConfig();
                $google_map_api_key = $appConfig->get('google_map_api_key','');
                $extra_style = array(
                    array(
                        'name'  =>  'wb_storelocator',
                        'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/store_locator/assets/css/storelocator.css',
                    ),
                );
                $extra_scripts = array(
                    array(
                        'name'  =>  'wb_handlebars',
                        'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/store_locator/assets/js/libs/handlebars.min.js',
                    ),
                    array(
                        'name'  =>  'wb_storelocator',
                        'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/resources/store_locator/assets/js/plugins/storeLocator/jquery.storelocator.js',
                    ),array(
                        'name'  =>  'wb_twbsPagination',
                        'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/twbs-pagination/jquery.twbsPagination.min.js',
                    ),
                );
                $scripts = array_merge($scripts,$extra_scripts);
                $styles = array_merge($styles,$extra_style);
                $input = Factory::getInput();
                $modelServices = Model::getInstance('services');
                $list=$modelServices->get_list_service_loc();
                wp_register_script ( 'wb_view_storelocator', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/app/assets/js/view_list_servicelocator.js' ,$depends,WPBOOKINGPRO_VERSION );
                $code = $this->render_code_inline_script('.view-list-servicelocator', 'view_list_servicelocator', array(
                    'data_input' => $input->getData(),
                    'list_service'=>$list,
                    "format_currency"=> FrontendHelper::getFormatCurrentCurrency()
                ));
                wp_add_inline_script( 'wb_view_storelocator', $code );
                $script[] = 'wb_select2';
                $script[] = 'wb_view_storelocator';
                
            }
            if($view == 'service-detail'){
                $extra_style = array();
                $extra_scripts = array(
                    array(
                        'name'  =>  'wb_validate',
                        'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/jquery-validation/dist/jquery.validate.js',
                    ),
                    array(
                        'name'  =>  'wb_twbsPagination',
                        'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/twbs-pagination/jquery.twbsPagination.min.js',
                    ),
                );
                $scripts = array_merge($scripts,$extra_scripts);
                $styles = array_merge($styles,$extra_style);
                $input = Factory::getInput();
                $service_id = $input->getInt('service_id',0);
                $modelService=Model::getInstance('service');
                $item = $modelService->getItem($service_id);
                $list_event = $modelService->getEventByServiceId($service_id);
                $appConfig = Factory::getAppConfig();
                $booking_style = $appConfig->get('booking_style', 'in_line');
                $limit = 6;
                
                if(!empty((array)($item))) {
                    $list_review = isset($item->list_review) ? $item->list_review : array();
                }else {
                    $list_review = array();
                }
                $default_currency = $appConfig->get('default_currency','');
                $current_currency = isset($_SESSION['currency']) ? $_SESSION['currency'] : $default_currency;
                $depends[] = 'wb_datetimepicker1';
                wp_register_script ( 'wb_view_service_detail', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/app/assets/js/view_service_detail.js' ,$depends,WPBOOKINGPRO_VERSION );
                
                $code = $this->render_code_inline_script('.view-service-detail','view_service_detail',array(
                    'list_event'=>$list_event,
                    'service_item'=>$item,
                    'booking_style'=> $booking_style,
                    "deposit_percent"=> isset($item->deposit_percent) ? $item->deposit_percent : '',
                    "limit"=>$limit,
                    "list_review"=>$list_review,
                    "format_currency"=>FrontendHelper::getFormatCurrentCurrency(),
                    "rate_exchange"=> FrontendHelper::getExchangeRate($current_currency)
                ));
                wp_add_inline_script( 'wb_view_service_detail', $code );
                $script[] = 'wb_select2';
                $script[] = 'wb_view_service_detail';
                unset($script[9]);
                unset($scripts[7]);
            }
            if($view == 'payment-paynow'){
                wp_register_script ( 'wb_view_paynow', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/app/assets/js/view_payment_paynow.js' ,$depends,WPBOOKINGPRO_VERSION );
                $input = Factory::getInput();
                $orderModel = Model::getInstance('order');
                $order_id = $input->getInt('order_id', 0);
                $order = $orderModel->getItem($order_id);
                $code = $this->render_code_inline_script('.view-payment-paynow','view_payment_paynow',array(
                    "list_rate"=>  $order->list_rate
                ));
                wp_add_inline_script( 'wb_view_paynow', $code );
                $script[] = 'wb_view_paynow';
            }
            if($view == 'payment-return'){
                wp_register_script ( 'wb_view_payment_return', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/app/assets/js/view_payment_paynow.js' ,$depends,WPBOOKINGPRO_VERSION );
                $input = Factory::getInput();
                $orderModel = Model::getInstance('order');
                $order_id = $input->getInt('order_id', 0);
                $order = $orderModel->getItem($order_id);
                $code = $this->render_code_inline_script('.view-payment-return','view_payment_paynow',array(
                    "list_rate"=>  $this->order->list_rate
                ));
                wp_add_inline_script( 'wb_view_payment_return', $code );
                $script[] = 'wb_view_payment_return';
            }
            if($view == 'login-list'){
                wp_register_script ( 'wb_view_login', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/app/assets/js/view_login.js' ,$depends,WPBOOKINGPRO_VERSION );
                $code = $this->render_code_inline_script('.view-login','view_login',array());
                wp_add_inline_script( 'wb_view_login', $code );
                $script[] = 'wb_view_login';
            }
            // echo '<pre>';
            // print_r($view);
            // echo '</pre>';
            // die();
            if($view == 'account-detail'){
                $extra_style = array();
                $extra_scripts = array(
                    array(
                        'name'  =>  'wb_validate',
                        'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/jquery-validation/dist/jquery.validate.js',
                    ),
                    array(
                        'name'  =>  'wb_twbsPagination',
                        'link'  => WPBOOKINGPRO_PLUGIN_DIR_URL . 'admin/resources/twbs-pagination/jquery.twbsPagination.min.js',
                    ),
                );
                $scripts = array_merge($scripts,$extra_scripts);
                $styles = array_merge($styles,$extra_style);
                $depends[] = 'wb_select2';
                wp_register_script ( 'wb_view_user_account', WPBOOKINGPRO_PLUGIN_DIR_URL . 'frontend/app/assets/js/view_user_account.js' ,$depends,WPBOOKINGPRO_VERSION );
                $code = $this->render_code_inline_script('.view-user-account', 'view_user_account', array());
                wp_add_inline_script( 'wb_view_user_account', $code );
                $script[] = 'wb_view_user_account';
            }
            $this->add_script_enqueue($scripts);
            $this->add_style_enqueue($styles);
        }
        
        wp_enqueue_script($script);
    }
    public function wp_register_rest_route(){
        register_rest_route(
            self::$namespace,
            "wpbookingpro_frontend/task",
            array(
                'methods' => 'POST',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
        register_rest_route(
            self::$namespace,
            "wpbookingpro_frontend/task",
            array(
                'methods' => 'GET',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
        register_rest_route(
            self::$namespace,
            "wpbookingpro_backend/task",
            array(
                'methods' => 'POST',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
        register_rest_route(
            self::$namespace,
            "wpbookingpro_backend/task",
            array(
                'methods' => 'GET',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
    }

    public  function load_plugin_textdomain(){
        load_plugin_textdomain( 'wpbookingpro', false, WPBOOKINGPRO_PATH_ROOT . '/languages/' );
    }

    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 "wpbookingpro_frontend/task";

    }
    public function add_script_enqueue($scripts){
        $depends = array( 'jquery');

        foreach($scripts as $script){
            if($script['name'] == 'wb_datetimepicker1'){
                $depends[] = 'wb_moment';
            }
            wp_enqueue_script($script['name'] , $script['link'] , $depends, WPBOOKINGPRO_VERSION);
        }
        
    }
    public function add_style_enqueue($scripts){
        foreach($scripts as $script){
            wp_enqueue_style( $script['name'] , $script['link']);
        }
       
    }
    public function front_end_render_view($params,$option,$view){
        $input=Factory::getInput();
        $page = $input->getString('page', '');
        $layout=$input->getString('layout',"");
        if($page=="wb_config"){
            if($layout!=="install" && !self::checkInstalled()){
                self::goToPopupInstall();
                return;
            }
        }elseif(!self::checkInstalled()){
            self::goToPopupInstall();
            return;
        }
        wp_enqueue_media();
        $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"));
        add_action('wp_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(WPBOOKINGPRO_PLUGIN_DIR_URL . "/" . $src) ?>"/>
                <?php
                echo (ob_get_clean());
            }
        }else{
            //$doc->addStyleSheet('frontend/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('wpbookingpro-css-' . $random, $src);
            } else {
                wp_enqueue_style('wpbookingpro-css-' . $random, WPBOOKINGPRO_PLUGIN_DIR_URL . '/' . $src);
            }
        }

        ob_start();
        ?>
        <script type="text/javascript">
            var wpbookingpro_root_url = "<?php  echo (WPBOOKINGPRO_SITE_URL) ?>";
            var wpbookingpro_current_url = "<?php  echo (WPBOOKINGPRO_SITE_URL) ?>";
            var wpbookingpro_root_url_plugin = "<?php echo (WPBOOKINGPRO_PLUGIN_DIR_URL); ?>/";
            var wpbookingpro_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('wpbookingpro-js-init', WPBOOKINGPRO_PLUGIN_DIR_URL .'frontend/resources/init.js' );
        wp_add_inline_script('wpbookingpro-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('wpbookingpro-js-out-site'.$random,$src,array('jquery') );
                } else {
                    $src=WPBOOKINGPRO_PLUGIN_DIR_URL . $src;
                    wp_enqueue_script('wpbookingpro-js-in-site-'.$random, $src,array('jquery') );
                }
            } catch (Exception $e) {
            }

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



}