<?php
namespace WpBookingPro\Wordpress;

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

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

    /**
     * @var
     */
    private static $instance;
    public static $namespace = "wpbookingpro_api/1.0";
    public static $key_wpbookingpro = "wpbookingpro";
    /**
     * @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 == 1) {
                static::$instance[$clientId] = new WordpressAdmin();
            }else{
                $clientId=0;
                static::$instance[$clientId] = new WordpressSite();
            }
        }
        static::$instance[$clientId]->init();


        return static::$instance[$clientId];

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

    }

    public function service_op_generate_rewrite_rules()
    {

        $page_service_detail= ConfigHelper::get_page_service_detail();
        // Remember to flush the rules once manually after you added this code!
        add_rewrite_rule(
        // The regex to match the incoming URL
            'service-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_service_detail.'&service_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-appointment',
                '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 appointment';
        $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 = "wpbookingpro";
            $home_wp_booking_pro_post = array(
                'post_name' => "$key_page",
                'post_title' => "WP Booking Appointment",
                '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 Appointment'),
                    'menu-item-classes' => 'wpbooking appointment',
                    '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_service'=>'services-list',
            'page_list_servicelocator'=>'servicelocator-list',
            'page_list_category'=>'categories-list',
            'page_login'=>'login-list',
            'page_signup'=>'signup-list',
            'page_user_account'=>'account-detail',
            'page_list_vendor' => 'vendor-list',
            'page_vendor_detail' => 'vendor-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);
                    $appointment_detail = array(
                        'post_name' => "$key",
                        'post_title' => $key_page,
                        'post_content' => '[wpbookingpro view="' . $key . '"]',
                        'post_status' => "publish",
                        'post_author' => get_current_user_id(),
                        'post_type' => "page",
                    );
                    $post_id = wp_insert_post($appointment_detail, '');
                }
                if(in_array($key,$list_mege_key))
                {
                    $a_key = array_search($key, $list_mege_key);
                    ConfigHelper::set_page_appointment($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 = WPBOOKINGPRO_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,
            "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'),
            )
        );
        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 static function get_list_layout_view_frontend()
    {
        $views_path = WPBOOKINGPRO_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 = wpbookingpro_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;
    }



}