<?php
namespace WpBookingHotel\Mvc\Controller;
use BlockView;
use Exception;
use stdClass;
use WpBookingHotel\Factory;
use WpBookingHotel\Filesystem\File as FileAlias;
use WpBookingHotel\Language\Text;
use WpBookingHotel\Mvc\Model\Model;
use WpBookingHotel\Utilities\Utility;

class Controller{
    public $model;
    public $modelItem="";
    public $modelList="";
    public static $instance;
    public $view=null;

    public function loadTemplate($tpl){
        $tmpl_short_path="/views/".$this->view."/tmpl/".$tpl.".php";
        $tmpl_path=WPBOOKINGHOTEL_APP_PATH.$tmpl_short_path;

        if(file_exists($tmpl_path)){
            ob_start();
            include $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 ajax_get_json_item($id=0){
        $modelItem=$this->getModelItem();
        return json_encode($modelItem->getItem());
    }
    public function ajax_get_item(){

        if(!$this->view){
            echo ('PLEASE_DEFINED_PUBLISH_VAR <b>view</b> IN_FILE '.get_called_class());
            die;
        }

        return self::view($this->view.".form");
    }
    public function ajax_duplicate(){
        $input=Factory::getInput();

        $id=$input->getInt('id');
        $model=$this->getModel();
        $new_item=$model->duplicate($id);
        return $new_item;

    }
    public function ajax_delete(){
        $input=Factory::getInput();

        $id=$input->getInt('id');
        $model=$this->getModel();
        $new_item=$model->delete($id);
        return $new_item;

    }
    public function ajax_save($data_post =array())
    {
        $input=Factory::getInput();
        if(!count($data_post)){

            $data_post=$input->getData();
        }
        $data_post=array_key_exists('data',$data_post)?$data_post['data']:$data_post;
        $data_post= $this->save($data_post);


        return $data_post;
    }
    public static function view($layout){
        list($view,$tpl)=explode(".",$layout);
        $view_name=ucfirst($view);
        $view_path=WPBOOKINGHOTEL_APP_PATH."/views/$view/{$view_name}View.php";
        if(file_exists($view_path)){
            $UFCiew=ucfirst($view);
            if(strpos(WPBOOKINGHOTEL_APP_PATH,"admin_woopanel/app")!==false){
                $view_name="WpBookingHotelAdminWooPanel\\app\\views\\$view\\{$UFCiew}View";
            }elseif(strpos(WPBOOKINGHOTEL_APP_PATH,"admin/app")!==false){
                $view_name="WpBookingHotelAdmin\\app\\views\\$view\\{$UFCiew}View";
            }else{
                $view_name="WpBookingHotelFrontend\\app\\views\\$view\\{$UFCiew}View";
            }
            $view_class=new $view_name();
            $view_class->view=$view;
            $content= $view_class->display($tpl);
            return '<div class="tour-operator-pro-view">'.$content.'</div>';
        }else{
            throw new Exception(Text::_("Error: view <b>$view_path</b> not exists please create it"));
        }
    }
    public static function display_block_app($block_id,$layout){
        $blockModel=Model::getInstance('block');
        $block=$blockModel->getItem($block_id);
        list($view,$tpl)=explode(".",$layout);
        $view_path=WPBOOKINGHOTEL_APP_PATH."/views/$view/view.html.php";

        if(file_exists($view_path)){
            require_once $view_path;
            $UFCiew=ucfirst($view);
            $view_name="{$UFCiew}View";
            $view_class=new $view_name();
            $view_class->view=$view;
            return $view_class->display_block_app($block,$tpl);
        }else{

            throw new Exception(Text::_("Error: view <b>$view_path</b> not exists please create it"));
        }
    }
    public static function config_block($block_name, $config_layout){
        $block_view_path=WPBOOKINGHOTEL_APP_FRONTEND_PATH."/views/block/view.html.php";
        if(file_exists($block_view_path)){
            require_once $block_view_path;
            $view_class=new WpBookingHotel_BlockView();
            $view_class->view="block";
            return $view_class->display('config');
        }else{

            throw new Exception(Text::_("Error: view <b>$block_view_path</b> not exists please create it"));
        }
    }
    public static function view_block_module($block_id,$block_name){
        $block_view_path=WPBOOKINGHOTEL_APP_FRONTEND_PATH."/views/block/BlockView.php";
        if(file_exists($block_view_path)){
            require_once $block_view_path;
            $view_class=new BlockView();
            $view_class->view="block";

            return $view_class->display_block($block_id,$block_name);
        }else{

            throw new Exception(Text::_("Error: view <b>$block_view_path</b> not exists please create it"));
        }
    }
    public function getModel($model=""){
        if(!$model){
            $model=$this->model;
        }
        $Ucfmodel=ucfirst($model);
        $model_path=WPBOOKINGHOTEL_APP_PATH."/models/$Ucfmodel.php";
        $model_name="{$Ucfmodel}Model";
        if(file_exists($model_path)){
            require_once $model_path;
        }
        if(!class_exists($model_name)){
            $model_class=Model::getInstance($model);
            $model_class->model=$model;
            return $model_class;
        }else{
            throw new Exception(Text::_("Error model <b>$model_path</b> not exits, please create first"));
        }

    }
    public function getModelItem($model=""){
        if(!$model){
            $model=$this->modelItem;
        }
        $UCModel=ucfirst($model);
        $model_path=WPBOOKINGHOTEL_APP_PATH."/models/$UCModel.php";
        if(file_exists($model_path)){
            require_once $model_path;
            $model_name="{$model}Model";
            $model_class=Model::getInstance($model);
            $model_class->model=$model;
            return $model_class;
        }else{
            throw new Exception(Text::_("Error model <b>$model_path</b> not exits, please create first"));
        }

    }
    public function getModelList($model=""){
        if(!$model){
            $model=$this->modelList;
        }
        if(!$model){
            throw new Exception(Text::_("please defined publish var modelList in file ".get_called_class()));
        }
        $model_path=WPBOOKINGHOTEL_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</b> not exits, please create first"));
        }


    }
    public static function ajax_action_task(){


        $input=Factory::getInput();

        $task=$input->getString('task','');
        list($controller,$task)=explode(".",$task);
        $file_controller_path=WPBOOKINGHOTEL_APP_PATH."/controllers/".ucfirst($controller)."Controller.php";

        $file_short_controller_path=Utility::get_short_file_by_path($file_controller_path);

        $response=new stdClass();

        if(file_exists($file_controller_path)){

            require_once $file_controller_path;

            if(strpos(WPBOOKINGHOTEL_APP_PATH,"admin/app")!==false){
                $class_name="WpBookingHotelAdmin\\app\\controllers\\".ucfirst($controller)."Controller";
            }else{
                $class_name="WpBookingHotelFrontend\\app\\controllers\\".ucfirst($controller)."Controller";
            }



            if(!class_exists($class_name)){

                $response->result="error";
                $response->msg="file $file_short_controller_path must has class $class_name, please check it";
                $response->data=null;
            }else{

                $class_controller=new $class_name();
                $class_controller->setModel($controller);
                if(method_exists ( $class_controller ,  $task ) ){

                    $data=call_user_func(array($class_controller, $task));
                    $doc=Factory::getDocument();
                    ob_start();
                    ?>
                    <script type="text/javascript">
                        less.registerStylesheetsImmediately();
                        var sheets = [];
                        for(var i = less.sheets.length; i--; )
                            sheets.push(less.sheets[i].href);
                        less.refresh(1);

                        var fnImport = less.tree.Import;
                        less.tree.Import = function(path, imports)
                        {
                            path.value += '?x='+Math.random();
                            fnImport(path, imports);
                        }
                    </script>
                    <?php
                    $script = ob_get_clean();

                    $script = Utility::remove_string_javascript($script);
                    $doc->addScriptDeclaration($script);
                    $response->scripts=$doc->getScripts();

                    $scripts=$response->scripts;
                    $data_script="";

                    foreach ($scripts as $src=>$item){
                        if(trim($src)==="")
                            continue;
                        $item=(object)$item;

                        if(strpos($src,"http")!==false){
                            $data_script.='<script  src="'.$src.'"></script>';
                        }elseif(FileAlias::exists(WPBOOKINGHOTEL_PATH_ROOT.DS.$src)){
                            $data_script.='<script src="'.Factory::getRootUrlPlugin().$src.'"></script>';
                        }

                    }
                    $response->data_script=$data_script;
                    $response->script=$doc->getScript();
                    $response->styleSheets=$doc->getStyleSheets();

                    $config=Factory::getConfig();
                    $environment=$config->get('environment',"development");
                    if($environment=="development") {
                        $response->lessStyleSheets=$doc->getLessStyleSheets();
                    }else{
                        $lessStyleSheets=$doc->getLessStyleSheets();
                        $item=array(
                                "type"=>"text/css",
                                "options"=>array(),
                        );
                        foreach ($lessStyleSheets as $src => $attribs) {
                            $path_info=pathinfo($src);
                            $dirname=$path_info['dirname'];
                            $filename=$path_info['filename'];
                            $css_file_path="$dirname/$filename.css";
                            $response->styleSheets[$css_file_path]=$item;
                        }
                    }
                    unset($response->lessStyleSheets['nb_apps/nb_woobooking/assets/less/main_style.less']);
                    $response->style=$doc->getStyleSheets();

                    if(is_array($data) || $data){
                        $response->result="success";
                        $response->data=$data;
                    }else{

                        $response->result="error";
                        $response->data=$data;
                    }
                }else{
                    $response->result="error";
                    $response->msg="class $class_name in file $file_short_controller_path can not found function(task) $task";
                    $response->data=null;
                }
            }

        }else{

            $response->result="error";
            $response->msg="cannot find file controller $file_short_controller_path not exists, please create it first";
            $response->data=null;
        }

        return json_encode($response);


    }
    public static function action_task(){
        $input=Factory::getInput();
        $task=$input->getString('task','');

        $client=is_admin()?1:0;
        $app=Factory::getApplication($client);
        list($controller,$task)=explode(".",$task);
        $file_controller_path=WPBOOKINGHOTEL_APP_PATH."/controllers/".ucfirst($controller)."Controller.php";
        $file_short_controller_path=Utility::get_short_file_by_path($file_controller_path);
        $response=new stdClass();
        if(file_exists($file_controller_path)){
            if(strpos(WPBOOKINGHOTEL_APP_PATH,"admin/app")!==false){
                $class_name="WpBookingHotelAdmin\\app\\controllers\\".ucfirst($controller)."Controller";
            }else{
                $class_name="WpBookingHotelFrontend\\app\\controllers\\".ucfirst($controller)."Controller";
            }
            if(!class_exists($class_name)){
                $app->enqueueMessage("file $file_short_controller_path must has class $class_name, please check it");
            }else{
                $class_controller=self::getInstance($controller);
                $class_controller->setModel($controller);

                if(method_exists ( $class_controller ,  $task ) ){
                    return call_user_func(array($class_controller, $task));
                }else{
                    $app->enqueueMessage("class $class_name in file $file_short_controller_path can not found function(task) $task");
                }
            }
        }else{

            $app->enqueueMessage("cannot find file controller $file_short_controller_path not exists, please create it first");
        }
    }

    /**
     * Method to get a singleton controller instance.
     *
     * @param $controller
     * @param array $config An array of optional constructor options.
     *
     * @return  \JControllerLegacy
     *
     * @since   3.0
     */
    public static function getInstance($controller, $config = array())
    {
        $clientId=is_admin()?1:0;
        $app=Factory::getApplication($clientId);
        if (is_object(self::$instance[$controller]))
        {
            return self::$instance[$controller];
        }

        $file_controller_path=WPBOOKINGHOTEL_APP_PATH."/controllers/".ucfirst($controller)."Controller.php";
        $file_short_controller_path=Utility::get_short_file_by_path($file_controller_path);
        $response=new stdClass();
        if(file_exists($file_controller_path)){
            if(strpos(WPBOOKINGHOTEL_APP_PATH,"admin/app")!==false){
                $class_name="WpBookingHotelAdmin\\app\\controllers\\".ucfirst($controller)."Controller";
            }else{
                $class_name="WpBookingHotelFrontend\\app\\controllers\\".ucfirst($controller)."Controller";
            }

            if(!class_exists($class_name)){
                $app->enqueueMessage("file $file_short_controller_path must has class $class_name, please check it");
            }else{
                self::$instance[$controller]=new $class_name();
            }
        }else{
            $app->enqueueMessage("cannot find file controller $file_short_controller_path not exists, please create it first");
        }

        return self::$instance[$controller];
    }


    public function setModel($model){
        $this->model=$model;
    }
    public function save($data=array()){

        $input=Factory::getInput();
        if(empty($data))
        {
            $data=$input->getData();
        }
        if(empty($data))
        {
            $data=$input->getArray();
        }
        $model=Model::getInstance($this->model);

        $data= $model->save($data);
        return $data;


    }
    public function save_v2($data=array()){
        $input=Factory::getInput();
        if(empty($data))
        {
            $data=$input->getData();
        }


        $model=$this->getModel();
        $data= $model->save($data);
        return $data;


    }
    public function delete($id=0){

        $input=Factory::getInput();
        if(!$id)
        {
            $id=$input->getInt('id',0);
        }
        $model=$this->getModel();
        return $model->delete($id);



    }
    public function duplicate($id=0){

        $input=Factory::getInput();
        if(!$id)
        {
            $id=$input->getInt('id',0);
        }
        $model=$this->getModel();
        return $model->duplicate($id);



    }
    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 frontendGoToLink($view_layout, $items_var=array()){
        $root_url=Factory::getRootUrl();
        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;
        }
        $url="wp-booking-pro/?page=$view-$layout&".implode("&",$http_list_var);
        $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 function redirect($url){

        $root_url=Factory::getRootUrl();
        wp_redirect($url);
        exit();
    }
    public function redirectInWooBookingPage($page){
        $openSource=Factory::getOpenSource();
        $page=$openSource->get_stander_page_front_end($page);
        $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.'wp-booking-pro?page='.$page)) . ';</script>';
        $html .= '</head><body></body></html>';
        echo ($html);
    }
}