<?php  

ini_set('upload_max_filesize', '50M');
ini_set('post_max_size', '50M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
    


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



class Brbookingportableend extends CI_Controller{

    public function __construct(){
        parent::__construct();
        // $this->load->model('RoomModel', 'room_model');

        $this->load->model('BrBookingModel', 'booking_model');
         $this->load->model('Brcustomermodel', 'customer_model');
         $this->load->model('BrBookingsPhotoModel', 'bookingPhoto_model');
         $this->load->model('BrBookingSignModel', 'bookingSignModel');
    }
    public function submitsign(){
        $id=$this->input->post('id');
        $signaturePad=$this->input->post('inputSignature');
        if($this->bookingSignModel->booking_exists($id)==false){
                 $data= array(
                'id'=>$id,
                'signaturePad'=>$signaturePad,
                );
                $result=$this->bookingSignModel->updateSign($data);


                if($result==false){
                    $code="FAILURE";
                    $msg="記錄不能加入";     
                }
                else{
                    $code="SUCCESS";
                    $msg="記錄成功加入"; 
                    //for add user it will add a secret key to database
                    
                    //end 

                }
                //end update form
        }
        else{
             
        }    

        header('Content-Type: application/json');
            // $code="SUCCESS";
            // $code="FAILURE";
            // $msg="已有相關記錄";
            // $myArray = ['id'=>12, 'name'=>'Topi'];
        $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
        echo json_encode($myArray);
            // echo "posted";



    }
    public function getSignedPhoto(){
         $id=$this->input->post('booking_id');
        $data=$this->bookingSignModel->getSignatureName($id);
        header('Content-Type: application/json');
        echo json_encode($data);
    }
    public function getAllServices(){
        $data=$this->services_model->getAllServices();
        header('Content-Type: application/json');
        echo json_encode($data);
    }

    public function get($id=Null){
        $partnerlist=$this->frontenduser_model->getBannerAll();
        echo  '1';
        print_r($partnerlist);
    }

    public function add(){
       
            // $request= new Request();
            // $admin=$request->getBody();

            // 'inputadminname':$('#inputadminname').val(),
            //     'inputloginname':$('#inputloginname').val(),
            //     'inputPassword'
            // $name=$this->input->post('name');
            
            //add security trim input-todo
            //hash password for security
            $startdate=$this->input->post('startdate');

            $starttime=preg_replace('/\s+/', '', $this->input->post('starttime'));
            // $starttime=trim($this->input->post('starttime')); //for having space in text string
            // $endtime=trim($this->input->post('endtime')); //for having space in text string
            $endtime=preg_replace('/\s+/', '', $this->input->post('endtime'));
            $user_id=$this->input->post('user_id');
            $display_name=$this->input->post('display_name');
            $mobile=$this->input->post('mobile');
            $room_id=$this->input->post('room_id');
            $pic_marked=$this->input->post('pic_marked');
            $pic_1=$this->input->post('pic_1');
            $pic_2=$this->input->post('pic_2');
            $remark=$this->input->post('remark');

            $useserviceboxvalue=$this->input->post('useserviceboxvalue');
            $useproductboxvalue=$this->input->post('useproductboxvalue');
            $shopId=$this->input->post('shopId');

            $addNewCustomer=false;
            if(empty($user_id)){
                $addNewCustomer=true;
            }
            if($addNewCustomer==true){
                $data= array(
                 'code'=>'',
                'display_name'=>$display_name,
                // 'chi_name'=>$chi_name,
                // 'eng_firstname'=>$eng_firstname,
                // 'inputadminname'=>$inputadminname,
                // 'eng_lastname'=>$eng_lastname,
                'gender'=>'',
                'dob'=>'',
                'mobile'=>$mobile,
                'district_id'=>'',
                'area_id'=>'',
                'zone'=>'',
                'address'=>'',
                'join_date'=>date('Y-m-d'),
                'shop_id'=>$shopId,
                'skin_improve'=>'',
                'referred_mobile'=>'',
                'remark'=>'',
                'need_purchase_service'=>'',
                'service_id'=>'',
                'purchased_date'=>'',
                'purchased_qty'=>'',
                'available_qty'=>'',
                'remark2'=>'',
                'promotion_code'=>'',
                'first_registered_tenant_no'=>$shopId,
                'concurrent_registered_tenant_no'=>$shopId,
                'level'=>'',
                'isTemp'=>'',
                'channelSelectID'=>'',
                'prefer_pic'=>'',
                'bodyoptionother_text'=>'',
                'faceoptionother_text'=>'',
  
                );

                if($this->customer_model->customermobile_exists($mobile)==false){
                    // $entercode=$code;
                    $code="FAILURE";
                    $msg="新增失敗。已有客戶電話號碼".$mobile;
                }
                elseif(!empty($code) && strpos($code, $headcode) !== 0){
                    $code="FAILURE";
                    $msg="新增失敗。客戶編號的前綴應為 ".$headcode."。";
                }
                else{
                    //not exist mobile and if exist code, code is ok
                    $result=$this->customer_model->insertCustomer($data);
                    if($result==false){
                        $code="FAILURE";
                        $msg="記錄不能加入";     
                    }
                    else{
                        $code="SUCCESS";
                        $msg="記錄成功加入"; 
                        //for add user it will add a secret key to database
                        
                        
                        //get user id

                        $user_id=$this->customer_model->getCustomerIdByMobile($mobile);
                        //end

                    }    
                }//else{
               
            }//if($addNewCustomer==true){

            if(!empty($user_id)){

                $data= array(
                    'startdate'=>$startdate,
                    'starttime'=>$starttime,
                    'endtime'=>$endtime,
                    // 'inputadminname'=>$inputadminname,
                    'user_id'=>$user_id,
                    'room_id'=>$room_id,
                    'pic_marked'=>$pic_marked,
                    'pic_1'=>$pic_1,
                    'pic_2'=>$pic_2,
                    'status'=>1,
                    'display'=>1,
                    'remark'=>$remark,
                    'useserviceboxvalue'=>$useserviceboxvalue,
                    'useproductboxvalue'=>$useproductboxvalue,
                    'shopId'=>$shopId,
                );

                $code="";
                // if($this->frontenduser_model->admin_exists($inputadminname)==false){
                //     $code="FAILURE";
                //     $msg="已有管理員姓名".$inputadminname;
                // }
                // else
                if($this->booking_model->booking_exists($data)==false){
                    $code="FAILURE";
                    $msg="已有相關booking".$startdate." ".$starttime."-".$endtime."room_id".$room_id." user".$user_id;
                }
                else{
                    $result=$this->booking_model->insertBooking($data);
                    if($result==false){
                        $code="FAILURE";
                        $msg="記錄不能加入";     
                    }
                    else{
                        $code="SUCCESS";
                        $msg="記錄成功加入"; 
                        //for add user it will add a secret key to database
                        
                        //end 

                    }
                }

            }//if(!empty($user_id)){    
            

             header('Content-Type: application/json');
            // $code="SUCCESS";
            // $code="FAILURE";
            // $msg="已有相關記錄";
            // $myArray = ['id'=>12, 'name'=>'Topi'];
            $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
            echo json_encode($myArray);
            // echo "posted";
        
    }
    public function update(){
         // $request= new Request();
            // $admin=$request->getBody();

            // 'inputadminname':$('#inputadminname').val(),
            //     'inputloginname':$('#inputloginname').val(),
            //     'inputPassword'
            // $name=$this->input->post('name');
            
            //add security trim input-todo
            //hash password for security
            $startdate=$this->input->post('startdate');

            $starttime=preg_replace('/\s+/', '', $this->input->post('starttime'));
            // $starttime=trim($this->input->post('starttime')); //for having space in text string
            // $endtime=trim($this->input->post('endtime')); //for having space in text string
            $endtime=preg_replace('/\s+/', '', $this->input->post('endtime'));
            // $user_id=$this->input->post('user_id');
            // $display_name=$this->input->post('display_name');
            // $mobile=$this->input->post('mobile');
            $room_id=$this->input->post('room_id');
            $pic_marked=$this->input->post('pic_marked');
            $pic_1=$this->input->post('pic_1');
            $pic_2=$this->input->post('pic_2');
            $remark=$this->input->post('remark');

            $useserviceboxvalue=$this->input->post('useserviceboxvalue');
            $useproductboxvalue=$this->input->post('useproductboxvalue');
            $shopId=$this->input->post('shopId');
            $bookingid=$this->input->post('bookingid');
            $user_id=$this->input->post('user_id');
           
           $isConfirm=$this->input->post('isConfirm');
            

                $data= array(
                    'startdate'=>$startdate,
                    'starttime'=>$starttime,
                    'endtime'=>$endtime,
                    // 'inputadminname'=>$inputadminname,
                    'user_id'=>$user_id,
                    'room_id'=>$room_id,
                    'pic_marked'=>$pic_marked,
                    'pic_1'=>$pic_1,
                    'pic_2'=>$pic_2,
                    'status'=>1,
                    'display'=>1,
                    'remark'=>$remark,
                    'useserviceboxvalue'=>$useserviceboxvalue,
                    'useproductboxvalue'=>$useproductboxvalue,
                    'shopId'=>$shopId,
                    'bookingid'=>$bookingid,
                    'isConfirm'=>$isConfirm,
                );

                $code="";
                // if($this->frontenduser_model->admin_exists($inputadminname)==false){
                //     $code="FAILURE";
                //     $msg="已有管理員姓名".$inputadminname;
                // }
                // else
                if($this->booking_model->booking_existsById($data)==false){
                    $code="FAILURE";
                    $msg="已有相關booking".$startdate." ".$starttime."-".$endtime."room_id".$room_id." user".$user_id;
                }
                else{
                    $result=$this->booking_model->updateBooking($data);
                    if($result==false){
                        $code="FAILURE";
                        $msg="記錄不能加入";     
                    }
                    else{
                        $code="SUCCESS";
                        $msg="記錄成功加入"; 
                        //for add user it will add a secret key to database
                        
                        //end 

                    }
                }

  
            

             header('Content-Type: application/json');
            // $code="SUCCESS";
            // $code="FAILURE";
            // $msg="已有相關記錄";
            // $myArray = ['id'=>12, 'name'=>'Topi'];
            $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
            echo json_encode($myArray);
            // echo "posted";
    }//end public function update(){
    public function delete(){
        $bookingid=$this->input->post('bookingid');
        // $result=true;
        // foreach ($inputdeletecheckboxvalue as $key => $values){
        //     if($this->shop_model->deleteShop($values)==false){
        //         $result=false; 
        //     }
           
            
        // }//foreach ($inputdeletecheckboxvalue as $key => $values){
        $data= array(
                    'id'=>$bookingid,
                );
        $result=$this->booking_model->deleteBooking($data);
        if($result==true){
            $code="SUCCESS";
            $msg="相關記錄成功删徐";
        }
        else{
            $code="FAILURE";
            $msg="相關記錄不能删徐";
        }
       
        // $msg=$inputdeletecheckboxvalue;
        header('Content-Type: application/json');
        $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
        echo json_encode($myArray);
    }    
    public function checkout(){

        $id=$this->input->post('id');
        $bookingItems=$this->input->post('bookingItems');
        $searcharray = json_decode(stripslashes($bookingItems),true);
        // $searcharray = json_decode(stripslashes($bookingItems));
        // $someArray = json_decode($searcharray, true);
        // var_dump($searcharray);

        //convert stringify codeing into array
        //may be it can change to other method 2020-07-17
         $outarray=array();

         $count=0;
         $itemrow =array();
         foreach($searcharray as $item) {
         // //    echo $item;
         // //     // $result=$this->booking_model->deleteBooking($data);
            
            if(strpos( $item["name"], "bookingitemid") !== false){
                $itemrow['bookingitemid']= $item["value"];
            }
            if(strpos( $item["name"], "code_1") !== false){
                $itemrow['code_1']= $item["value"];
            }
            if(strpos( $item["name"], "code_2") !== false){
                $itemrow['code_2']= $item["value"];
            }
            if(strpos( $item["name"], "code_area") !== false){
                $itemrow['code_area']= $item["value"];
            }
            if(strpos( $item["name"], "code_remark") !== false){
                $itemrow['code_remark']= $item["value"];
                array_push($outarray,$itemrow);
                $itemrow =array();
                $count=$count+1;
            }
            
         }//foreach($searcharray as $item) {        
        //end  //convert stringify codeing into array

        foreach ($outarray as $itemsListRow) {
            $data= array(
                    'id'=>$itemsListRow['bookingitemid'],
                    'code_1'=>$itemsListRow['code_1'],
                    'code_2'=>$itemsListRow['code_2'],
                    'code_area'=>$itemsListRow['code_area'],
                    'code_remark'=>$itemsListRow['code_remark'],
                );
            $result=$this->booking_model->updateCheckOutBookingItem($data);
        }


        //Update booking Checkout time 
        //if isReturn =0
        //update the isReturn = 1 and return time
        $result3=$this->booking_model->updateCheckOutReturnBooking($id);    



        //end Update booking Checkout time



        // foreach ($bookingItems as $bookingItemRow) {
        //     parse_str($bookingItems, $searcharray);
        // }
        // parse_str($bookingItems, $searcharray);
        // $bookingItemsList =  unserialize($bookingItems);
        // foreach ($variable as $key => $value) {
        //     # code...
        // }
        // var_dump($data);
        if($result3==true){
            $code="SUCCESS";
            $msg="相關記錄成功更改";
        }
        else{
            $code="FAILURE";
            $msg="相關記錄不能更改";
        }
       
        // $msg=$inputdeletecheckboxvalue;
        header('Content-Type: application/json');
        // $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
        $myArray = ['recordstatus'=>'SUCCESS', 'msg'=>$outarray , 'completemsg'=>$msg];
        echo json_encode($myArray);
    }
    public function detail(){
         $id=$this->input->post('id');
         $result=$this->booking_model->getBookingByid($id);
         header('Content-Type: application/json');
         echo json_encode($result);
    }
    public function deletephoto(){
        $id=$this->input->post('id');
        // $result=true;
        // foreach ($inputdeletecheckboxvalue as $key => $values){
        //     if($this->shop_model->deleteShop($values)==false){
        //         $result=false; 
        //     }
           
            
        // }//foreach ($inputdeletecheckboxvalue as $key => $values){
        $data= array(
                    'id'=>$id,
                );
        $pathname=$this->bookingPhoto_model->getPhotoPathname($data);

        if(!empty($pathname)){
          unlink($pathname);
          $result=$this->bookingPhoto_model->deletePhoto($data);
          if($result==true){
                $code="SUCCESS";
                $msg="相關記錄成功删徐";
            }
            else{
                $code="FAILURE";
                $msg="相關記錄不能删徐";
            }      
        }//if(!empty($pathname)){   

        
       
        // $msg=$inputdeletecheckboxvalue;
        header('Content-Type: application/json');
        $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
        echo json_encode($myArray);
    }  
    public function getPhotoList(){
         $booking_id=$this->input->post('booking_id');
         $type=$this->input->post('type');
         $result=$this->bookingPhoto_model->getPhotoList($booking_id,$type);
         header('Content-Type: application/json');
         echo json_encode($result);
    }
    public function checkBookingInvoice(){

            $booking_id=$this->input->post('booking_id');
         $result=$this->booking_model->checkIsItNeedPrintInvoice($booking_id);
         header('Content-Type: application/json');
         echo json_encode($result);
    }

    public function edit(){
       
        // $request= new Request();
        // $admin=$request->getBody();

        // 'inputadminname':$('#inputadminname').val(),
        //     'inputloginname':$('#inputloginname').val(),
        //     'inputPassword'
        // $name=$this->input->post('name');
        
        //add security trim input-todo
        //hash password for security
        $inputcompanynameedit=$this->input->post('inputcompanynameedit');
        $inputfullnameedit=$this->input->post('inputfullnameedit');
        $inputteledit=$this->input->post('inputteledit');
        // $inputadminname=$this->input->post('inputadminnameedit');
        $inputloginname=$this->input->post('inputloginnameedit');
        $inputPassword=$this->input->post('inputPasswordedit');
        $id=$this->input->post('inputadminid');

        $data= array(

            'inputcompanynameedit'=>$inputcompanynameedit,
            'inputfullnameedit'=>$inputfullnameedit,
            'inputteledit'=>$inputteledit,
            // 'inputadminname'=>$inputadminname,
            'inputloginname'=>$inputloginname,
            'inputPassword'=>$inputPassword,
            'id'=>$id
        );

        $code="";
        // if($this->frontenduser_model->admin_existsbyid($inputadminname,$id)==false){
        //     $code="FAILURE";
        //     $msg="已有管理員姓名".$inputadminname;
        // }
        // else
        if($this->frontenduser_model->login_existsbyid(strtolower($inputloginname),$id)==false){
            $code="FAILURE";
            $msg="已有登入名稱".$inputloginname;
        }
        else{
            $result=$this->frontenduser_model->updateAdmin($data);
            if($result==false){
                $code="FAILURE";
                $msg="記錄不能更改";     
            }
            else{
                $code="SUCCESS";
                $msg="記錄成功更改";    
            }

            
        }

         
        

         header('Content-Type: application/json');
        // $code="SUCCESS";
        // $code="FAILURE";
        // $msg="已有相關記錄";
        // $myArray = ['id'=>12, 'name'=>'Topi'];
        $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
        echo json_encode($myArray);
        // echo "posted";
    
    }
    // public function delete(){
    //     $inputdeletecheckboxvalue=$this->input->post('inputdeletecheckboxvalue');
    //     $result=true;
    //     foreach ($inputdeletecheckboxvalue as $key => $values){
    //         if($this->frontenduser_model->deleteAdmin($values)==false){
    //             $result=false; 
    //         }
           
            
    //     }//foreach ($inputdeletecheckboxvalue as $key => $values){
    
    //     if($result==true){
    //         $code="SUCCESS";
    //         $msg="相關記錄成功删徐";
    //     }
    //     else{
    //         $code="FAILURE";
    //         $msg="相關記錄不能删徐";
    //     }
       
    //     // $msg=$inputdeletecheckboxvalue;
    //     header('Content-Type: application/json');
    //     $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
    //     echo json_encode($myArray);
    // }
    public function getadmindata(){
        $id=$this->input->post('user_id');
        $data=$this->frontenduser_model->getAdmindateByid($id);
        header('Content-Type: application/json');
        echo json_encode($data);
    }
    public function arrive(){
              $id=$this->input->post('id');  
              $result=$this->booking_model->arriveBooking($id);

              if($result==false){
                        $code="FAILURE";
                        $msg="記錄不能簽到";     
              }
              else{
                        $code="SUCCESS";
                        $msg="記錄成功簽到"; 
                        //for add user it will add a secret key to database
                        
                        //end 

                }


  
            

             header('Content-Type: application/json');
            // $code="SUCCESS";
            // $code="FAILURE";
            // $msg="已有相關記錄";
            // $myArray = ['id'=>12, 'name'=>'Topi'];
            $myArray = ['recordstatus'=>$code, 'msg'=>$msg];
            echo json_encode($myArray);
    }
    public function upload(){
            $bookingId=$this->input->post('bookingid');
            $type=$this->input->post('type');
            // Count total files
            $countfiles = count($_FILES['files']['name']);

            // Upload directory
            $upload_location = "uploads/";

            // To store uploaded files path
            $files_arr = array();

            // Loop all files
            for($index = 0;$index < $countfiles;$index++){
                $filedetail=array();
               // File name
               $filename = $_FILES['files']['name'][$index];
                $size=$_FILES['files']['size'][$index];
                 $ext = explode('.', basename($_FILES['files']['name'][$index]));//explode file name from dot(.) 
                    $file_extension = end($ext); //store extensions in the variable
                $newfilename=md5(uniqid()) . "." . $ext[count($ext) - 1];

               // Get extension
               $ext = pathinfo($filename, PATHINFO_EXTENSION);

               // Valid image extension
               $valid_ext = array("png","jpeg","jpg");

               // Check extension
               if(in_array($ext, $valid_ext)){

                 // File path
                 // $path = $upload_location.$filename;
                 $path = $upload_location.$newfilename;

                 // Upload file
                 

                $code="";
                $data= array(
                    'booking_id'=>$bookingId,
                    'name'=>$filename,
                    'filename'=>$newfilename,
                    // 'inputadminname'=>$inputadminname,
                    'pathname'=>$path,
                    'filetype'=>$file_extension,
                    'size'=>$size,
                    'type'=>$type,
                );    
                // if($this->frontenduser_model->admin_exists($inputadminname)==false){
                //     $code="FAILURE";
                //     $msg="已有管理員姓名".$inputadminname;
                // }
                // else
                if($this->bookingPhoto_model->photo_exists($data)==false){
                    // $code="FAILURE";
                    // $msg="已有相關booking".$startdate." ".$starttime."-".$endtime."room_id".$room_id." user".$user_id;
                }
                else{


                    if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
                    // $files_arr[] = $path;


                        //insert image to database
                         $result=$this->bookingPhoto_model->insertPhoto($data);
                        if($result==false){
                            $code="FAILURE";
                            $msg="記錄不能加入";     
                        }
                        else{
                            $code="SUCCESS";
                            $msg="記錄成功加入"; 
                            //for add user it will add a secret key to database
                             $photoid=$this->bookingPhoto_model->getPhotoId($newfilename);
                            //end 
                            $filedetail['path']=$path;
                            $filedetail['id']=$photoid;
                            $filedetail['name']=$filename;
                            array_push($files_arr,$filedetail);

                        }

                        //end insert image to database    
                    
                    }

                    
                }
                    

                    
               }

            }//for($index = 0;$index < $countfiles;$index++){

            echo json_encode($files_arr);
    }//end public function upload(){

}//class Admins {
