<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
         var $menu;
         var $contactus;
        public function __construct()
        {
            parent::__construct();
        //     $this->load->model('Section', 'section_model');
        //     $this->menu = $this->section_model->buildTopMenuItem();
        //     $this->breadcrumbs = [];
        //     $this->load->model('ContactDetails', 'contactdetails_model');
        //     $this->contactus = $this->contactdetails_model->getContactus();

            $this->load->model('BackendUser', 'backenduser_model');
            $this->load->library(array('form_validation','session'));
            $this->load->helper(array('url','html','form'));


        }

        public function successpage(){
                // $this->load->view('successpage');
                // echo "1";
                redirect('/adminmain', 'refresh');
        }
               
        function logout(){

                $this->load->library('logger');
                 $this->logger
                 ->backuserid($this->session->userdata('userid')) //Set UserID, who created this  Action
                 ->type('登出後台') //Entry type like, Post, Page, Entry
                 ->comment("")
                 ->usertype($this->session->userdata('usertype'))
                 ->ipaddress($_SERVER['REMOTE_ADDR'])
                 ->log();



                $this->session->sess_destroy();
                redirect('portable/login');
        }


        public function index()
	{
        
        // load google data if it have        
        //$this->load->view('welcome_message');
        $this->load->view('portable/login');
        // $contactusdata = $this->contactdetails_model->getContactus();
        //     $this->breadcrumbs[] = array (
        //         'label' => '聯絡我們',
        //         'link' => ''
        //     );
        //     $this->twig->display('main', array(
        //         'path' => array(
        //             'vendor' => $this->config->item('vendor_path'),
        //             'script' => $this->config->item('script_path'),
        //             'css' => $this->config->item('css_path'),
        //             'image' => $this->config->item('image_path')
        //         ),
        //         'breadcrumbs' => $this->breadcrumbs,
        //         'menus' => $this->menu,
        //         'contactusdata'=>$contactusdata,
        //         'session' => 'contact',
        //         'contactus' => $this->contactus,
        //         'page' => 'index'
        //     ));
        }
        public function check(){
                // echo "sigin";
                // $this->successpage();
                $this->load->library('logger');

                $this->load->library('form_validation');
                $this->form_validation->set_rules('userName', '登入名稱', 'required');
                $this->form_validation->set_rules('password', '密碼', 'required');

                $this->form_validation->set_message('required', '請輸入%s');


                if ($this->form_validation->run() === FALSE)
                {
                        $this->load->view('/portable/login');      
                }
                else{
                        $data = $this->backenduser_model->check();
			if(empty($data))
			{

                 $this->logger
                 ->frontuserid($this->session->userdata('userid')) //Set UserID, who created this  Action
                 ->type('嘗試登入後台') //Entry type like, Post, Page, Entry
                 ->comment($this->input->post('userName'))
                 ->usertype('backenduser')
                 ->ipaddress($_SERVER[REMOTE_ADDR])
                 ->log();

				$this->session->set_flashdata('msg','請輸入正確登入名稱或密碼.');
				redirect('/portable/login');
			}
			else
			{
                // echo "passwd check";
                //get admin user secret

                // $usersecrete=$this->backenduser_model->getsecret($data['id']);

                    //  $this->load->model('EmployeeModel', 'employee_model');
                    //  $tenant=$this->employee_model->gettenant(trim($this->input->post('userName')));
                    // var_dump($tenant);
                    //  $roleid=$this->employee_model->getUserRole($tenant, $data['id']);
                    //  $rolename=$this->employee_model->getUserRoleName($roleid);



                //end get admin user secret

                //get admin user secret

                $usersecrete=$this->backenduser_model->getsecret($data['id']);

                //end get admin user secret


                //

				$newdata = array(
			        'username'  => $data['username'],
			        'userid'     => $data['id'],
			        // 'fullName' => $data['admin'],
                    'engname' =>$data['eng_firstname'].$data['eng_lastname'],
			        'logged_in' => TRUE,
                    'currentshop'=>$data['shopid'],
                    'shopid'=>$data['shopid'],
                    'roleId'=>$data['roleId'],
                    // 'rolename'=>$rolename,
                    // 'secret' =>$usersecrete,
                    'secret' =>$usersecrete,
                    'usertype' => 'backenduser',
                    'chi_name'  => $data['chi_name'],
                    'second_shopid'  => $data['second_shopid'],
				);


                //for setting role right
                $this->setroleright($data['roleId']);
                //end for setting role right


                $this->logger
                 ->backuserid($data['id']) //Set UserID, who created this  Action
                 ->type('登入後台成功') //Entry type like, Post, Page, Entry
                 ->comment($this->input->post('userName'))
                 ->ipaddress($_SERVER['REMOTE_ADDR'])
                 ->usertype('backenduser')
                 ->log();


                // $this->session->set_userdata( array('dashboard_access'=> '123123'));
				$this->session->set_userdata($newdata);
				redirect('/portable/adminmain');
                //using place
			}        
                }        
                // $userName= trim($this->input->post('userName'));
                // $password= md5(trim($this->input->post('password')));
                // echo $userName;
                // echo $password;
                // $query = $this->backenduser_model->processLogin($userName,$password);
                // $query2 = $query->result();
                // echo "login";
                // echo  $query2[0]->login;
                // echo "num row";
                // echo $query->num_rows();
                // $this->form_validation->set_rules('userName', '名稱', 'required|callback_validateUser[' . $query->num_rows() . ']');
                // $this->form_validation->set_rules('password', '密碼', 'required');
                
                // $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
                // $this->form_validation->set_message('validateUser', '錯誤名稱或密碼');
                // $this->form_validation->set_message('required', '請輸入 %s');
                
                //echo query result
              
                //end echo query result

                
                // if (empty($userName)|| empty($password) || ($query->num_rows()!=1)) {
                //         $data['msg']="登入名稱或密碼錯誤1";
                //         $this->load->view('testview',$data);
                        
                //         // echo "testview";
                // }else{
                //         if($query){
                //                 $query = $query->result();
                //                 $user = array(
                //                 'USER_ID' => $query[0]->id,
                //                 'USER_NAME' => $query[0]->login,
                //                 'FULL_NAME' => $query[0]->fullName
                                
                //                 );
                        
                //         $this->session->set_userdata($user);
                //         // redirect('index.php/successpage');
                //                 $this->successpage();
                //                 // echo "success";
                //         }
                // }

        }//public function signin(){
        public function setroleright($roleId){
             // $this->session->set_userdata( array('dashboard_access'=> '123123'));
            $this->load->model('Brgrouprightmodel', 'groupright_model');


            // if($this->groupright_model->checkRoleAccessRight($roleId,"儀錶板","accessfield")==true){
            //      $this->session->set_userdata(array(
            //         'dashboard_access'  => true));
            // }
            // else{
            //     $this->session->set_userdata(array(
            //         'dashboard_access'  => false));
            // }
            // if($this->groupright_model->checkRoleAccessRight($roleId,"儀錶板","accessfield")==true){
            //      $this->session->set_userdata(array(
            //         'dashboard_access'  => true));
            // }
            // else{
            //     $this->session->set_userdata(array(
            //         'dashboard_access'  => false));
            // }
           $rightarray = array( // start from 0 
            array("儀錶板", "accessfield", "dashboard_access"), 
            array("儀錶板", "addfield", "dashboard_add"),
            array("儀錶板", "editfield", "dashboard_edit"),
            array("儀錶板", "deletefield", "dashboard_delete"),

            array("價錢列表", "accessfield", "pricelist_access"), 
            array("價錢列表", "addfield", "pricelist_add"),
            array("價錢列表", "editfield", "pricelist_edit"),
            array("價錢列表", "deletefield", "pricelist_delete"),

            array("客戶管理", "accessfield", "brcustomer_access"), 
            array("客戶管理", "addfield", "brcustomer_add"),
            array("客戶管理", "editfield", "brcustomer_edit"),
            array("客戶管理", "deletefield", "brcustomer_delete"),

            array("預約", "accessfield", "brbooking_access"), 
            array("預約", "addfield", "brbooking_add"),
            array("預約", "editfield", "brbooking_edit"),
            array("預約", "deletefield", "brbooking_delete"),

            array("發票", "accessfield", "brinvoice_access"), 
            array("發票", "addfield", "brinvoice_add"),
            array("發票", "editfield", "brinvoice_edit"),
            array("發票", "deletefield", "brinvoice_delete"),

            array("服務管理", "accessfield", "brservice_access"), 
            array("服務管理", "addfield", "brservice_add"),
            array("服務管理", "editfield", "brservice_edit"),
            array("服務管理", "deletefield", "brservice_delete"),

            array("職員", "accessfield", "bremployee_access"), 
            array("職員", "addfield", "bremployee_add"),
            array("職員", "editfield", "bremployee_edit"),
            array("職員", "deletefield", "bremployee_delete"),

            array("房間", "accessfield", "brroom_access"), 
            array("房間", "addfield", "brroom_add"),
            array("房間", "editfield", "brroom_edit"),
            array("房間", "deletefield", "brroom_delete"),
            array("職員角色", "accessfield", "employeerole_access"), 
            array("職員角色", "addfield", "employeerole_add"),
            array("職員角色", "editfield", "employeerole_edit"),
            array("職員角色", "deletefield", "employeerole_delete"),

            array("系統設定", "accessfield", "brsetting_access"), 
            array("系統設定", "addfield", "brsetting_add"),
            array("系統設定", "editfield", "brsetting_edit"),
            array("系統設定", "deletefield", "brsetting_delete")

            ); 

           foreach ($rightarray as $rightrow) {
            if($this->groupright_model->checkRoleAccessRight($roleId,$rightrow[0],$rightrow[1])==true){
                 $this->session->set_userdata(array(
                    $rightrow[2]  => true));
            }
            else{
                $this->session->set_userdata(array(
                    $rightrow[2]   => false));
            }
           }//foreach ($rightarray as $rightrow) {

        }    

        public function test2()
	{
        //$this->load->view('welcome_message');
        $this->load->view('test1');
        // $contactusdata = $this->contactdetails_model->getContactus();
        //     $this->breadcrumbs[] = array (
        //         'label' => '聯絡我們',
        //         'link' => ''
        //     );
        //     $this->twig->display('main', array(
        //         'path' => array(
        //             'vendor' => $this->config->item('vendor_path'),
        //             'script' => $this->config->item('script_path'),
        //             'css' => $this->config->item('css_path'),
        //             'image' => $this->config->item('image_path')
        //         ),
        //         'breadcrumbs' => $this->breadcrumbs,
        //         'menus' => $this->menu,
        //         'contactusdata'=>$contactusdata,
        //         'session' => 'contact',
        //         'contactus' => $this->contactus,
        //         'page' => 'index'
        //     ));
        }
}
