<?php
namespace WpBookingEvent\Mvc\View;
use Exception;
use WpBookingEvent\Factory;
use WpBookingEvent\Language\Text;
use WpBookingEvent\Mvc\Model\Model;
use WpBookingEvent\Object\CMSObject;
use WpBookingEvent\Utilities\Utility;

class View extends CMSObject
{
    public $view="";
    public $list="";
    public $header="";
    public $item="";
    public $filterForm;
    public $_defaultModel;
    public $form="";
    protected $_escape = 'htmlspecialchars';
    public function getModel($model=""){
        $model=$model?$model:$this->view;
        $model=ucfirst($model);
        $model_path=WPBOOKINGEVENT_APP_PATH."/models/$model.php";
        if(file_exists($model_path)){
            $model_class=Model::getInstance($model);
            $model_class->model=$model;
            return $model_class;
        }else{
            throw new Exception(Text::_("Error: model <b>$model_path</b> not exists, please create first"));
        }

    }
    public static $instance=array();

    public static function getInstance($view, $prefix = '', $config = array()):View
    {
        $view = preg_replace('/[^A-Z0-9_\.-]/i', '', $view);
        $UCFview = ucfirst($view);
        $view_path = WPBOOKINGEVENT_APP_PATH . "/views/$view/{$UCFview}View.php";
        if (file_exists($view_path)) {
            require_once $view_path;
            if (!array_key_exists($view, self::$instance)) {
                if(strpos(WPBOOKINGEVENT_APP_PATH,"admin/app")!==false){
                    $class_name="WpBookingEventAdmin\\app\\views\\$view\\".$UCFview."View";
                }else{
                    $class_name="WpBookingEventFrontend\\app\\views\\$view\\".$UCFview."View";
                }
                self::$instance[$view] = new $class_name();
                self::$instance[$view]->model = $view;
            }

        } else {
            throw new Exception(Text::_("can not found model:" . Utility::get_short_file_by_path($view_path) . ',please create it'));
        }
        return self::$instance[$view];
    }


    public function __construct()
    {

    }
    public function get($property, $default = null)
    {
        // If $model is null we use the default model
        if ($default === null)
        {
            $model = $this->_defaultModel;
        }
        else
        {
            $model = strtolower($default);
        }

        // First check to make sure the model requested exists
        if (isset($this->_models[$model]))
        {
            // Model exists, let's build the method name
            $method = 'get' . ucfirst($property);

            // Does the method exist?
            if (method_exists($this->_models[$model], $method))
            {
                // The method exists, let's call it and return what we get
                $result = $this->_models[$model]->$method();

                return $result;
            }
        }

        // Degrade to \JObject::get
        $result = parent::get($property, $default);

        return $result;
    }


    public function escape($var)
    {
        if (in_array($this->_escape, array('htmlspecialchars', 'htmlentities')))
        {
            return call_user_func($this->_escape, $var, ENT_COMPAT, isset($this->_charset)?$this->_charset:"");
        }

        return call_user_func($this->_escape, $var);
    }

    public static function goToLink($view_layout, $items_var=array()){

        list($view,$layout)=explode(".",$view_layout);
        $openSource=Factory::getOpenSource();
        $key_woo_booking=$openSource->getKeyWooBooking();
        $http_list_var=array();
        if(is_array($items_var)){
            foreach ($items_var as $key=> $value){
                $http_list_var[]="$key=$value";
            }
        }else{
            $http_list_var[]=  $items_var;
        }


        $link=Factory::getRootUrl()."wp-admin/admin.php?page=wb_$view&layout=$layout".implode("&",$http_list_var);
        return $link;
    }
    public function redirect($url){
        $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.'/'.$url)) . ';</script>';
        $html .= '</head><body></body></html>';
        echo ($html);
    }

    public static function frontendGoToLink($view_layout, $items_var=array()){

        list($view,$layout)=explode(".",$view_layout);
        $openSource=Factory::getOpenSource();
        $key_woo_booking=$openSource->getKeyWooBooking();
        $http_list_var=array();
        if(is_array($items_var)){
            foreach ($items_var as $key=> $value){
                $http_list_var[]="$key=$value";
            }
        }else{
            $http_list_var[]=  $items_var;
        }


        $link=Factory::getRootUrl()."wp-booking-pro/?page=$view-$layout&".implode("&",$http_list_var);
        return $link;
    }
    public static function getFrontendLink($view_layout, $items_var=array()){

        list($view,$layout)=explode(".",$view_layout);
        $openSource=Factory::getOpenSource();
        $key_woo_booking=$openSource->getKeyWooBooking();
        $http_list_var=array();
        if(is_array($items_var)){
            foreach ($items_var as $key=> $value){
                $http_list_var[]="$key=$value";
            }
        }else{
            $http_list_var[]=  $items_var;
        }


        $link=Factory::getRootUrl()."wp-booking-pro/?page=$view-$layout&".implode("&",$http_list_var);
        return $link;
    }

    public static function goToTaskLinkBackend($view,$task, $items_var=array()){


        $http_list_var=array();
        if(is_array($items_var)){
            foreach ($items_var as $key=> $value){
                $http_list_var[]="$key=$value";
            }
        }else{
            $http_list_var[]=  $items_var;
        }


        $link=Factory::getRootUrl()."wp-admin/admin.php?page=wb_$view&task=$view.$task".(is_array($items_var)&&count($items_var)?'&':null).implode("&",$http_list_var);
        return $link;
    }
    public static function goToTaskLinkFrontend($view,$task, $items_var=array()){


        $http_list_var=array();
        if(is_array($items_var)){
            foreach ($items_var as $key=> $value){
                $http_list_var[]="$key=$value";
            }
        }else{
            $http_list_var[]=  $items_var;
        }


        $link=Factory::getRootUrl()."wp-booking-pro/?page=$view-list&task=$view.$task".(is_array($items_var)&&count($items_var)?'&':null).implode("&",$http_list_var);
        return $link;
    }
    public static function goToTaskLink($view,$task, $items_var=array()){


        $http_list_var=array();
        if(is_array($items_var)){
            foreach ($items_var as $key=> $value){
                $http_list_var[]="$key=$value";
            }
        }else{
            $http_list_var[]=  $items_var;
        }


        $link=Factory::getRootUrl()."/wp-admin/admin.php?page=wb_$view&task=$view.$task".(is_array($items_var)&&count($items_var)?'&':null).implode("&",$http_list_var);
        return $link;
    }
    public function loadTemplate($tpl){
        $tmpl_short_path="/views/".$this->view."/tmpl/".$tpl.".php";

        $tmpl_path=WPBOOKINGEVENT_APP_PATH.$tmpl_short_path;

        if(file_exists($tmpl_path)){
            ob_start();
            require $tmpl_path;
            $content=ob_get_clean();
            echo ($content);
        }else{
            throw new Exception(Text::_("Error:tpl <b>$tpl</b> not exits, please create it"));
        }
    }
    public function loadSharedTemplate($template){
        list($template,$layout)=explode(".",$template);
        $tmpl_short_path="/shared/".$template."/$layout.php";

        $tmpl_path=WPBOOKINGEVENT_APP_PATH.$tmpl_short_path;

        if(file_exists($tmpl_path)){
            ob_start();
            require $tmpl_path;
            $content=ob_get_clean();
            echo ($content);
        }else{
            throw new Exception(Text::_("Error:tpl <b>$tmpl_short_path</b> not exits, please create it"));
        }
    }
    public function loadTemplateFromOtherView($view,$tpl){
        $tmpl_short_path="/views/".$view."/tmpl/".$tpl.".php";
        $tmpl_path=WPBOOKINGEVENT_APP_PATH.$tmpl_short_path;

        if(file_exists($tmpl_path)){
            ob_start();
            require $tmpl_path;
            $content=ob_get_clean();
            echo ($content);
        }else{
            throw new Exception(Text::_("Error:tpl <b>$tpl</b> not exits, please create it"));
        }
    }
    public function display($tpl){
        $tmpl_short_path="/views/".$this->view."/tmpl/".$tpl.".php";

        $tmpl_path=WPBOOKINGEVENT_APP_PATH.$tmpl_short_path;
        ob_start();
        ?>
        <div id="loader-wrapper">
            <div id="loader"></div>

            <div class="loader-section section-left"></div>
            <div class="loader-section section-right"></div>

        </div>

        <?php
        $loading=ob_get_clean();
        if(file_exists($tmpl_path)){
            ob_start();
            include $tmpl_path;
            $content=ob_get_clean();
            if(!trim($content)){
                $content="<div class='wrapper-tour-operator-pro'><p>layout <b>$tmpl_short_path</b> empty please add content to it</p></div>";
            }
            $content="<div class=\"wrapper-tour-operator-pro\">$loading $content</div>";
            return $content;
        }else{
            throw new Exception(Text::_("Error:tpl <b>$tpl</b> not exits, please create it in view <b>".$this->view."</b>"));
        }


    }
    public function displayList(){
        if(!$this->list){
            $model=$this->getModel();
            $this->list=$model->getList();
            $this->header=$model->getHeader();
        }
        $this->view="default";
        echo (self::display("list"));

    }
    public function displayForm(){
        if(!$this->form){
            $model=$this->getModel();
            $this->form=$model->getForm();
        }
        $this->view="default";
        echo (self::display("form"));
    }
}