<?php
namespace TourOperatorPro\Wordpress;

use Cassandra\Exception\ProtocolException;
use Exception;
use TourOperatorPro\Factory;
use TourOperatorPro\Factory as FactoryAlias;
use TourOperatorPro\Filesystem\File;
use TourOperatorPro\Html\TourOperatorProHtmlFrontend;
use TourOperatorPro\Html\TourOperatorProHtmlWooPanel;
use TourOperatorPro\Log\Log;
use TourOperatorPro\Mvc\Controller\Controller;
use TourOperatorPro\Mvc\Model\Model;
use TourOperatorPro\Mvc\View\View;
use TourOperatorPro\Router\Router as CoreRouter;
use TourOperatorPro\Utilities\Utility;
use TourOperatorPro\Language\Text;
use TourOperatorPro\Wordpress\WordpressAdmin;
use TourOperatorPro\Wordpress\WordpressAdminWoopanel;
use TourOperatorProAdmin\app\helpers\ConfigHelper;


/**
 * Class Wordpress
 * @package TourOperatorPro\Wordpress
 */
class WordpressSite extends Wordpress
{

    /**
     * @var
     */
    private static $instance;
    public static $key_woo_booking = "touroperatorpro";

    /**
     * @var string
     */
    public static $namespace = "touroperatorpro_api/1.0";
    private static $parsed_route=false;
    /**
     * @var int
     */
    private $clientId=0;
    private $init_GutembergBlock=0;



    public function init(){
        if(!$this->is_admin()) {
            if(session_id() == '')
                session_start();
            $config = Factory::getConfig();
            $db = Factory::getDBO();
            $environment = $config->get('environment', 'production');
            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') );
            $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 ="TourOperatorProFrontend\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' ) );
            TourOperatorProHtmlFrontend::load_jquery_library('less');
            TourOperatorProHtmlFrontend::load_jquery_library('main_app');
            TourOperatorProHtmlFrontend::load_jquery_library('lazy_load');
            TourOperatorProHtmlFrontend::load_jquery_library('bootstrap');

            $path = "wp-content/plugins/touroperatorpro/frontend/app/views.xml";
            add_shortcode('touroperatorpro', 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_touroperatorpro . "-block-" . $key;
                add_shortcode(trim($a_key), array($this, 'woo_booking_render_block_by_tag_func'));
            }
            $gutembergBlock = GutembergBlock::getInstance();
            $gutembergBlock->init();


            $widgets = Widgets::getInstance();
            $widgets->init();
            add_filter( 'init', array($this,"tour_op_generate_rewrite_rules"));
            add_action( 'wp_head', array($this,'gretathemes_meta_description'));
            add_filter('pre_get_document_title',array($this,'add_title_for_tour'),10, 3 );
            add_action('wp_footer', array($this, 'wp_hook_add_script_footer'));
            // add_filter( 'init', array($this,"tour_op_generate_rewrite_rules"));
        }
    }

    public function tour_op_generate_rewrite_rules()
    {
        // $page_tour_detail= ConfigHelper::get_page_tour_detail();
        // // Remember to flush the rules once manually after you added this code!
        // add_rewrite_rule(
        // // The regex to match the incoming URL
        // 'tour-detail/(.*)-(\w+)',
        // // The resulting internal URL: `index.php` because we still use WordPress
        // // `pagename` because we use this WordPress page
        // // `designer_slug` because we assign the first captured regex part to this variable
        // 'index.php?page_id='.$page_tour_detail.'&tour_id=$matches[2]',
        // // This is a rather specific URL, so we add it to the top of the list
        // // Otherwise, the "catch-all" rules at the bottom (for pages and attachments) will "win"
        // 'top');

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

    }
    public static function checkInstalled()
    {
        $app = Factory::getApplication(0);
        $db = Factory::getDBO();
        $installed = true;
        $list_table_in_database = $db->setQuery("SHOW TABLES LIKE " . $db->quote("tbpro\\_%"))->loadColumn();
        if (count($list_table_in_database) == 0) {
            $installed = false;
        }
        $json_table_need_install = File::read(TOUROPERATORPRO_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;
    }

    function add_title_for_tour(){
        $title="";
        $this->parse_route();
        $input = FactoryAlias::getInput();
        $tour_id = $input->getInt('tour_id',0);
        $modelTour=Model::getInstance('tour');
        $tour=$modelTour->getItem($tour_id);
        if(isset($tour->id)) {
            $title=$tour->name;
        }
        return $title;
    }
    function gretathemes_meta_description() {
        $this->parse_route();
        $input = FactoryAlias::getInput();
        $tour_id = $input->getInt('tour_id',0);
        $modelTour=Model::getInstance('tour');
        $content="";

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

            <?php
            $content = ob_get_clean();
        }
        echo $content;
    }

    public static function wp_enqueue_scripts(){
        $config=Factory::getConfig();
        $environment=$config->get('environment',"development");
        if($environment=="production") {
            wp_enqueue_style( 'touroperatorpro-main-frontend-style', TOUROPERATOR_PLUGIN_DIR_URL . '/frontend/app/assets/less/style.css', array());
        }else if($environment=="demo"){
            wp_enqueue_style( 'touroperatorpro-main-frontend-style', TOUROPERATOR_PLUGIN_DIR_URL . '/frontend/app/assets/less/style.css', array());
        }else{

        }


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

    public  function load_plugin_textdomain(){
        load_plugin_textdomain( 'touroperatorpro', false, TOUROPERATORPRO_PATH_ROOT . '/languages/' );
    }

    function woo_booking_render_block_by_tag_func($atts, $content, $a_view)
    {
        $uri=Factory::getUri();
        $app = Factory::getApplication(0);
        $_router = $app->getRouter(0);


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

        $woopanel_submenus['wp_touroperator']=($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 add_menu_to_woopanel($woopanel_menus){
        $woopanel_menus[4]=array(
            "id"=>"wp_touroperator",
            "menu_slug"=>"wp_touroperator",
            "menu_title"=>"wp touroperator",
            "capability"=>"",
            "page_title"=>"wp touroperator",
            "icon"=>"flaticon-line-graph",
            "classes"=>"wp-touroperator",
            "permission"=>"global",
        );
        return $woopanel_menus;
    }
    public function getKeyWooBooking()
    {
        return self::$key_woo_booking;
    }

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

    }
    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);
            }
        }
    }
    public function front_end_render_view($params,$option,$view){
        $this->parse_route();
        $input=Factory::getInput();
        TourOperatorProHtmlFrontend::load_jquery_library('bootstrap');
        $view=isset($params['view'])?$params['view']:"tours-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(TOUROPERATOR_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('touroperatorpro-css-' . $random, $src);
            } else {
                wp_enqueue_style('touroperatorpro-css-' . $random, TOUROPERATOR_PLUGIN_DIR_URL . '/' . $src);
            }
        }

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

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



}