<?php
namespace WpBookingHotel\Wordpress;

use WpBookingHotel\Language\Text;
use Exception;
use WpBookingHotel\Application\ApplicationAdmin;
use WpBookingHotel\Application\ApplicationSite;
use WpBookingHotel\Factory;
use WpBookingHotel\Filesystem\File;
use WpBookingHotel\Filesystem\Folder;
use WpBookingHotel\Mvc\Controller\Controller;
use WpBookingHotel\Wordpress\ECommerce\ECommerce;
use WpBookingHotelAdmin\app\helpers\ConfigHelper;

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

    /**
     * @var
     */
    private static $instance;
    public static $namespace = "wpbookinghotel_api/1.0";
    public static $key_wpbookinghotel = "wpbookinghotel";
    /**
     * @var int
     */
    private $clientId=0;

    public function __construct($clientId=0)
    {
        $this->clientId=$clientId;
    }
    public function getEcommerce()
    {
        $this->ecommerce= ECommerce::getInstance();
        return $this->ecommerce;
    }

    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_hotel_detail();
        // Remember to flush the rules once manually after you added this code!
        add_rewrite_rule(
        // The regex to match the incoming URL
            'hotel-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.'&hotel_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 WP Booking Hotel';
        $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 = "wpbookinghotel";
            $home_wp_booking_pro_post = array(
                'post_name' => "$key_page",
                'post_title' => "Wp Booking Hotel",
                '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('Wp Booking Hotel'),
                    'menu-item-classes' => 'wpbookinghotel',
                    '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_list_hotel'=>'hotels-list',
            'page_list_hotellocator'=>'hotellocator-list',
            'page_hotel_detail'=>'hotel-detail',
            'page_checkout_default'=>'checkout-default',
        );

        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' => '[wpbookinghotel 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_hotel($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 = WPBOOKINGHOTEL_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,
            "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'),
            )
        );
        register_rest_route(
            self::$namespace,
            "wpbookingpro_backend_woopanel/task",
            array(
                'methods' => 'POST',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
        register_rest_route(
            self::$namespace,
            "wpbookingpro_backend_woopanel/task",
            array(
                'methods' => 'GET',
                'callback' => array($this, 'ajax_action_task'),
            )
        );
    }
    public function ajax_action_task(){

        return Controller::ajax_action_task();

    }
    public function action_task(){

        return Controller::action_task();

    }

    public static function get_list_layout_view_frontend()
    {
        $views_path = WPBOOKINGHOTEL_FRONTEND_PATH . "/app/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 {
                    $title = (string)($xml->layout->attributes())['title'];
                    $bool = (string)($xml->layout->attributes())['show_main_menu'];
                    $show_main_menu = filter_var($bool, FILTER_VALIDATE_BOOLEAN);;
                } catch (Exception $e) {
                    echo "please check file tructor xml";
                    die;
                }
                $title = wpbookinghotel_get_content($title);
                if (!$title) {
                    continue;
                }
                $list_view["$view-$filename"] = array(
                    "title" => $title,
                    "show_main_menu" => $show_main_menu
                );


            }
        }
        return $list_view;
    }
    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;
    }


}