<?php
namespace TourOperatorPro\Wordpress;

use stdClass;
use TourOperatorPro\Language\Text;
use Exception;
use TourOperatorPro\Application\ApplicationAdmin;
use TourOperatorPro\Application\ApplicationSite;
use TourOperatorPro\Factory;
use TourOperatorPro\Filesystem\File;
use TourOperatorPro\Filesystem\Folder;
use TourOperatorPro\Mvc\Controller\Controller;
use TourOperatorProAdmin\app\helpers\ConfigHelper;

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


    /**
     * @var
     */
    private static $instance;
    public static $namespace = "touroperatorpro_api/1.0";
    public static $key_touroperatorpro = "
    ";

    /**
     * @var int
     */
    private $clientId=0;
    public function __construct($clientId=0)
    {
        $this->clientId=$clientId;
    }
    public static function getInstance($clientId = 0)
    {
        if (!isset(static::$instance[$clientId])) {
            if ($clientId == 2) {
                static::$instance[$clientId] = new WordpressAdminWoopanel();
            } else if ($clientId == 1) {
                static::$instance[$clientId] = new WordpressAdmin();

            } else {
                $clientId = 0;
                static::$instance[$clientId] = new WordpressSite();
            }
        }
        static::$instance[$clientId]->init();
        register_activation_hook(__FILE__, array("Wordpress", 'pluginprefix_activation'));
        return static::$instance[$clientId];

    }
    public static function get_format_page($page)
    {
        return "wb_$page";

    }
    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[1]',
            // 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');
    }

    public static function  add_page_to_menu($page_id, $page_title, $menu_id, $parent = 0,$link){
        $key_page = "wp-booking-pro";
        wp_update_nav_menu_item(
            $menu_id, 0,
            array(
                'menu-item-title' =>  esc_html($page_title),
                'menu-item-classes' => 'Wp-booking-pro',
                'menu-item-url' => $link,
                'menu-item-type' => 'custom',
                'menu-item-status' => 'publish',
                'menu-item-parent-id'=>$parent
            )
        );
    }
    function wp_add_inline_script(){
        if(self::is_admin()){
            add_action('admin_footer', array($this, 'wp_hook_add_script_footer'));
        }else{
            add_action('wp_footer', array($this, 'wp_hook_add_script_footer'));
        }
    }

    public static function pluginprefix_activation()
    {
        // setup navigation automatically
        $root_url=Factory::getRootUrl();
        $name = 'Menu tour operator pro';
        $menu_exists = wp_get_nav_menu_object($name);
        $list_page = WordpressAdmin::get_list_layout_view_frontend();

        if( !$menu_exists){

            $menu_id = wp_create_nav_menu($name);
            $menu = get_term_by( 'name', $name, 'nav_menu' );
            $key_page = "touroperatorpro";
            $home_wp_booking_pro_post = array(
                'post_name' => "$key_page",
                'post_title' => "Tour operator pro",
                'post_content' => "[$key_page]",
                'post_status' => "publish",
                'post_author' => get_current_user_id(),
                'post_type' => "page",
            );

            $page_check = get_page_by_path($key_page);
            if (!isset($page_check->ID)) {

                wp_insert_post($home_wp_booking_pro_post, '');
            }
            //add it to create menu

            $home_page=$root_url.'/'.$key_page;
            $my_menu_id=wp_update_nav_menu_item($menu->term_id, 0, array(
                    'menu-item-title' =>  esc_html('Tour operator pro'),
                    'menu-item-classes' => 'tour operator pro',
                    'menu-item-url' => $home_page,
                    'menu-item-type' => 'custom',
                    'menu-item-status' => 'publish'
                )
            );
            foreach ($list_page as $key=>$page ){
                $key=strtolower($key);
                $link=$root_url.'/'.$key;
                $title=$page['title'];
                $show_main_menu=$page['show_main_menu'];
                if($show_main_menu)
                {
                    Wordpress::add_page_to_menu(0,$title,$menu->term_id,$my_menu_id,$link);
                }
            }

        }else{
            $menu = get_term_by( 'name', $name, 'nav_menu' );
        }
        //then you set the wanted theme  location
        $locations = get_theme_mod('nav_menu_locations');
        set_theme_mod( 'nav_menu_locations', $locations );


        $list_mege_key=array(
            'page_tour_checkout'=>'checkout-default',
            'page_list_tour'=>'tours-list',
            'page_list_tour_search_result'=>'tours-list',
            'page_tour_detail'=>'tour-detail',
        );

        foreach ($list_page as $key=>$page ){
            $key=strtolower($key);
            $show_main_menu=$page['show_main_menu'];
            if($show_main_menu)
            {
                $post_id=url_to_postid($key);
                if(!$post_id) {
                    $key_page = str_replace("-", " ", $key);
                    $key_page = ucfirst($key_page);
                    $tour_detail = array(
                        'post_name' => "$key",
                        'post_title' => $key_page,
                        'post_content' => '[touroperatorpro view="' . $key . '"]',
                        'post_status' => "publish",
                        'post_author' => get_current_user_id(),
                        'post_type' => "page",
                    );
                    $post_id = wp_insert_post($tour_detail, '');
                }
                if(in_array($key,$list_mege_key))
                {
                    $a_key = array_search($key, $list_mege_key);
                    ConfigHelper::set_page_tour($post_id,$a_key);
                }
            }
        }



        return true;

    }


    public function is_admin(){
        return is_admin();
    }
    public function init(){
    }


    public static function get_list_layout_block_frontend()
    {
        $blocks_path = TOUROPERATORPRO_APP_FRONTEND_BLOCK_PATH . "/blocks";
        $list_block = array();
        $folders = Folder::folders($blocks_path);
            foreach ($folders as $block) {
                $block_path = $blocks_path . "/$block";
                $file_config_block = str_replace("block_", "", $block);
                $file = $block_path . "/forms/config.xml";
                if (!File::exists($file)) {
                    continue;
                }
                $xml = simplexml_load_file($file);
                try {
                    $attributes = $xml->layout->attributes();
                    $title = (string)$attributes['title'];
                } catch (Exception $e) {
                    echo('PLEASE_CHECK_FILE_TRUCTOR_XML');
                    die;
                }
                $list_block["$file_config_block"] = array(
                    "title" => $title
                );
            }
            return $list_block;
    }
    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'),
            )
        );
        register_rest_route(
            self::$namespace,
            "touroperatorpro_backend_woopanel/task",
            array(
                'methods' => 'POST',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
        register_rest_route(
            self::$namespace,
            "touroperatorpro_backend_woopanel/task",
            array(
                'methods' => 'GET',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
    }

    public function ajax_action_task(){

        return Controller::ajax_action_task();

    }

    public static function is_rest_api()
    {
        $request_uri = $_SERVER['REQUEST_URI'];
        if ((strpos($request_uri, 'wp-json/') !== false) || (strpos($request_uri, 'wc-ajax') !== false)) {
            return true;
        }
        return false;
    }



}