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

class BrBookingModel extends CI_Model {

    function __construct()
    {
        parent::__construct();
        $this->load->model('TransactionModel', 'transaction_model');
        
    }

    //new added booking
     function getAllBooking($shopId) {
        $this->db->from('brbookings');
        $this->db->where('delete_time', NULL);
        $this->db->where('shopId', $shopId);
        // $this->db->where('shop_id',$id);
        $this->db->order_by('startdate DESC');
        $query = $this->db->get();
        return $query->result();
    }

    function getBookingItem($id){
        $this->db->select('b.*, s.code, s.category_id, s.name, s.work, s.price,s.no_credit_rebate');
        $this->db->from('brbooking_items b,brservices s');
        $this->db->where('b.delete_time', NULL);
         $this->db->where('b.service_id = s.id');
        $this->db->where('booking_id',$id);
        $query = $this->db->get();
        return $query->result(); 

    }//function getBookingItem($id){
    function booking_exists($data){
        $this->db->select('*');
        $this->db->from('brbookings');
        $this->db->where('startdate', $data['startdate']);
        $this->db->where('starttime', $data['starttime']);
        $this->db->where('endtime', $data['endtime']);
        $this->db->where('room_id', $data['room_id']);
        $this->db->where('user_id', $data['user_id']);
        $query = $this->db->get();
        if($query->num_rows() == 1){
             return false;
        } else {
             return true;
        }
         
    }
    function insertBooking($inputdata){
        // 'inputadminname'=>$inputadminname,
        //         'inputloginname'=>$inputloginname,
        //         'inputPassword'=>$inputPassword,
        $data = array(
            'startdate' => $inputdata['startdate'] ,
            'starttime' => $inputdata['starttime'] ,
            'endtime' => $inputdata['endtime'] ,
            'user_id' => $inputdata['user_id'] ,
            // 'fullName' => $inputdata['inputadminname'] ,
            'room_id' => $inputdata['room_id'] ,
            'pic_marked'=>$inputdata['pic_marked'],
            'pic_1'=>$inputdata['pic_1'],
            'pic_2'=>$inputdata['pic_2'],
            'status'=>1,
            'display'=>1,
            'remark'=>$inputdata['remark'],
            'shopId'=>$inputdata['shopId'],

         );
        date_default_timezone_set('UTC');
        
         $this->db->set('update_time', time(), FALSE);
         $this->db->set('create_time', time(), FALSE);
         // $this->db->set('update_time', 'NOW()', FALSE);
         // $this->db->set('create_time', 'NOW()', FALSE);
         $query=$this->db->insert('brbookings', $data);
         $insert_id = $this->db->insert_id();
         //insert useService
         if(!empty($inputdata['useserviceboxvalue'])){

             foreach ($inputdata['useserviceboxvalue'] as $useservice) {

                    
                $data = array(
                'booking_id' => $insert_id ,
                'service_user_id' => $useservice ,
                // 'endtime' => $data['endtime'] ,
                // 'user_id' => $data['user_id'] ,
                // // 'fullName' => $data['inputadminname'] ,
                // 'room_id' => $data['room_id'] ,
                // 'pic_marked'=>$data['pic_marked'],
                // 'pic_1'=>$data['pic_1'],
                // 'pic_2'=>$data['pic_2'],
                'status'=>1,
                'display'=>1,
                // 'remark'=>$data['remark'],


             );
                 $this->db->set('update_time', time(), FALSE);
                 $this->db->set('create_time', time(), FALSE);
                 $query=$this->db->insert('brbooking_items', $data);
             } //foreach ($data['useserviceboxvalue'] as $useservice) 

         }//if(!empty($inputdata['useserviceboxvalue'])){
         //end 


         //insert useProduct


         //end 

         return $query;
    }
    function getBookingByid($id){
        $this->db->select('brbookings.*,brcustomer.display_name,brcustomer.mobile');
        $this->db->from('brbookings');
        $this->db->join('brcustomer', 'brbookings.user_id = brcustomer.id');
        $this->db->where('brbookings.delete_time', NULL);
        $this->db->where('brbookings.id',$id);
        $query = $this->db->get();
        if($query->num_rows() == 1){
             return $query->row();
        } else {
            return "";
        } 
    }//function getBookingByid($id){
    function getBookingService($bookingid){
        $this->db->select('service_user_id');
        $this->db->from('brbooking_items');
        $this->db->where('brbooking_items.booking_id',$bookingid);
        $query = $this->db->get();
        return $query->result();
    }
    //end new added booking
         
    function getIntime($id){
        $this->db->select('arriveTime');
        $this->db->from('brbookings');
        $this->db->where('id',$id);
        $query = $this->db->get();
        if($query->num_rows() == 1){
             return $query->row()->arriveTime;
        } else {
            return "";
        }
       
    }

    function getOuttime($id){
        $this->db->select('returnTime');
        $this->db->from('brbookings');
        $this->db->where('id',$id);
        $query = $this->db->get();
        if($query->num_rows() == 1){
             return $query->row()->returnTime;
        } else {
            return "";
        }
       
    }
    function checkin($dataori){
        // $data = array(
        //     'id' => $dataori['id'] ,
        //  );

        $this->db->select('booking_id');
        $this->db->from('mas_bookings_attendance');
        $this->db->where('booking_id',$dataori['id']);
        $query = $this->db->get();
        if($query->num_rows() == 1){
             //update attendance
            date_default_timezone_set('UTC');

            $data = array(
            'in_time' =>  time() ,
             );
            $this->db->set('update_time', 'NOW()', FALSE);
             $this->db->where('booking_id', $dataori['id']);
             $this->db->update('mas_bookings_attendance', $data);
             return true;
        } else {
             //insert attendance

            date_default_timezone_set('UTC');

              $data = array(
            'in_time' =>  time() ,
            'booking_id' => $dataori['id'] ,
            'user_id' => $dataori['user_id'] ,
            // 'endtime' => $data['endtime'] ,
            // 'user_id' => $data['user_id'] ,
            // // 'fullName' => $data['inputadminname'] ,
            // 'room_id' => $data['room_id'] ,
            // 'pic_marked'=>$data['pic_marked'],
            // 'pic_1'=>$data['pic_1'],
            // 'pic_2'=>$data['pic_2'],
            // 'status'=>1,
            // 'display'=>1,
            // 'remark'=>$data['remark'],
         );
         // $this->db->set('update_time', 'NOW()', FALSE);
         $this->db->set('date', 'NOW()', FALSE);
         $this->db->set('create_time', 'NOW()', FALSE);
         $query=$this->db->insert('mas_bookings_attendance', $data);
         return $query;
            //end insert 
        }
    }
    function checkout($dataori){
        // $data = array(
        //     'id' => $dataori['id'] ,
        //  );

        $this->db->select('booking_id');
        $this->db->from('mas_bookings_attendance');
        $this->db->where('booking_id',$dataori['id']);
        $query = $this->db->get();
        if($query->num_rows() == 1){
             //update attendance
            date_default_timezone_set('UTC');

            $data = array(
            'out_time' =>  time() ,
             );
            $this->db->set('update_time', 'NOW()', FALSE);
             $this->db->where('booking_id', $dataori['id']);
             $this->db->update('mas_bookings_attendance', $data);
             return true;
        } else {
             //insert attendance

            date_default_timezone_set('UTC');

              $data = array(
            'out_time' =>  time() ,
            'booking_id' => $dataori['id'] ,
            'user_id' => $dataori['user_id'] ,
            // 'endtime' => $data['endtime'] ,
            // 'user_id' => $data['user_id'] ,
            // // 'fullName' => $data['inputadminname'] ,
            // 'room_id' => $data['room_id'] ,
            // 'pic_marked'=>$data['pic_marked'],
            // 'pic_1'=>$data['pic_1'],
            // 'pic_2'=>$data['pic_2'],
            // 'status'=>1,
            // 'display'=>1,
            // 'remark'=>$data['remark'],
         );
         // $this->db->set('update_time', 'NOW()', FALSE);
         $this->db->set('date', 'NOW()', FALSE);
         $this->db->set('create_time', 'NOW()', FALSE);
         $query=$this->db->insert('mas_bookings_attendance', $data);
         return $query;
            //end insert 
        }
    }
    

    //new latepoint function
    function  get_total_amount_paid_from_transactions($id){
        $transactions=$this->transaction_model->getAllTransactions($id);
        $total =0;
        foreach($transactions as $transaction){
            $total+=$transaction->amount;
        }
        return $total;

    }

    function get_default_payment_method(){
        if($this->payment_method){
            return $this->payment_method;
        }
        else{
            //not set as helper not set 2020-06-01
            // return OsPaymentsHelper::default_payment_method();
            return "cash";
        }
    }
    function delete_meta_by_key($meta_key){
        //not really know the usage
    }
    function get_payment_portion_nice_name(){
        //return partial payment name
        $paymentportion=array();
        $paymentportion[0] = "全數";
        $paymentportion[1] = "訂金";

        return $paymentportion;

    }
    function get_payment_method_nice_name(){
        //return partial payment name
        $paymentmethod[1] = "Jarvix";
        $paymentmethod=array();
        $paymentmethod[0] = "現金";
        $paymentmethod[2] = "EPS";
        $paymentmethod[3] = "CUP";
        $paymentmethod[4] = "VISA";
        $paymentmethod[5] = "MASTER";

        return $paymentmethod;

    }    
    function get_ical_download_link(){
        //not find the use
    }
    function get_print_link(){
        //not find the use
    }
    function get_meta_by_key($meta_key, $default = false){
        //not find the use
    }
    function save_meta_by_key($meta_key, $meta_value){
        //not find the use
    }
    function calculate_end_date($id){
        //return end date if start_time larger than 24*60 of booking duration
    }
    function calculate_end_time($id){
        $this->db->from('mas_bookings');
        $this->db->where('id',$id);
        $starttime=$this->db->get()->row()->starttime;

        $end_time = $starttime+$this->get_total_duration();
        // continues to next day?
        if($end_time > (24 * 60)){
          $end_time = $end_time - (24 * 60);
        }
        return $end_time;
    }
    function get_total_duration($id){
        $this->db->from('mas_bookings');
        $this->db->where('id',$id);
        $endtime=$this->db->get()->row()->endtime;
        $starttime=$this->db->get()->row()->starttime;

        $start_t = new DateTime($starttime);
        $current_t = new DateTime($endtime);
        $difference = $start_t ->diff($current_t );
        $return_time = $difference ->format('%H:%I:%S');

        return $return_time;
    }
    function get_start_time_shifted_for_customer(){
    }
    function get_end_time_shifted_for_customer(){
    }

    function get_nice_created_at(){
        $this->db->from('mas_bookings');
        $this->db->where('id',$id);
        $createtime=$this->db->get()->row()->create_time;
    return $createtime;
  }
    // ONLY USED ON LAST STEP OF BOOKING, TO CONVERT SELECTED BOOKING TIME FROM CUSTOMER ZONE TO OUR INTERNAL TIMEZONE
  // DO NOT USE ANYWHERE ELSE BECAUSE IT MODIFIES ACTUAL VALUES
    function apply_customer_timeshift(){
        //may be switch the the time zone to 8 hours later
        //not really use at all
        $shift_in_minutes = $this->customer->get_timeshift_in_minutes();
        $this->start_time = $this->start_time - $shift_in_minutes;
        if($this->start_time < 0){
          $date_obj = new OsWpDateTime($this->start_date);
          $this->start_date = $date_obj->modify('-1 day')->format('Y-m-d');
          $this->start_time = $this->start_time + (24 * 60);
        }elseif($this->start_time > (24 * 60)){
          $date_obj = new OsWpDateTime($this->start_date);
          $this->start_date = $date_obj->modify('+1 day')->format('Y-m-d');
          $this->start_time = $this->start_time - (24 * 60);
        }
  }

    function save_from_booking_form(){
        //1.check current logged in user
        //2.check service id
        //3.if any agent selected
        //4.get agent id from OsBookingHelpher


    }
    function get_nice_status($id){
        $this->db->from('mas_bookings');
        $this->db->where('id',$id);
     }

    //end new latepoint function

    function getAllRoom($id) {
        $this->db->from('mas_room');
        $this->db->where('shop_id',$id);
        $query = $this->db->get();
        return $query->result();
    }

     function room_exists($shop_id,$name){
        // $this->db->from('adminUsers');
        $this->db->where('LOWER(name)', $name);
        $this->db->where('shop_id', $shop_id);
        $query = $this->db->get('mas_room');
        if($query->num_rows() == 1){
            return false;
        } else {
            return true;
        }
    }
    
   
    function getBannerAll()
    {
        
        $this->db->from('frontendUsers');
        // $this->db->where(array('show' => 1));
        // $this->db->order_by('rank');
        $query = $this->db->get();
        return $query->result();
    }


    function checking(){

    	$userid = $this->session->userdata('userid');
    	$username = $this->session->userdata('username');
    	$fullName = $this->session->userdata('fullName');
    	$logged_in = $this->session->userdata('logged_in');
    	$secret = $this->session->userdata('secret');
    	$usertype = $this->session->userdata('usertype');

    	$passLogin=false;
    	if($usertype=="frontenduser"){
    		if($logged_in==false){
    			return false;
    		}
    		if(empty($userid)){
    			return false;
    		}
    		if(empty($secret)){
    			return false;
    		}
    		$this->db->where('id',$userid);
        	$this->db->where('secret',$secret);
        	if($this->db->get('frontendUsers')->row_array()){
        		$passLogin=true;
        		return true;
        	}	
        	else{
        		return false;
        	}

    	}//if($usertype=="frontenduser"){
    	if($usertype=="backenduser"){
    	    if($logged_in==false){
    			return false;
    		}
    		if(empty($userid)){
    			return false;
    		}
    		if(empty($secret)){
    			return false;
    		}
    		$this->db->where('id',$userid);
        	$this->db->where('secret',$secret);
        	if($this->db->get('adminUsers')->row_array()){
        		$passLogin=true;
        		return true;
        	}	
        	else{
        		return false;
        	}
    	
    	}
    }
 }