<?php

class Selfservice_model extends CI_Model {

    function __construct() {
        // Call the Model constructor
        parent::__construct();
    }

   function get_available_staff(){
      
    $sql = "SELECT 
            id_staff, staff.staff_fullname, staff.staff_designation, visit_service_staffs.visit_service_end, count(id_visit_service_staffs) as visits
            FROM
            `staff`
                JOIN `staff_attendance` ON `staff_attendance`.`staff_id` = `staff`.`id_staff`
                and date(staff_attendance.time_in) = '".date('Y-m-d')."' 
                and  staff_attendance.time_in < now()
                and ifnull(staff_attendance.time_out,'')=''
                LEFT JOIN (
                    Select id_visit_service_staffs , visit_service_staffs.staff_id, 
                    max(date_format(date_add(visit_services.visit_service_end, interval 5 Minute),'%Y-%m-%d %H:%i:%s')) as visit_service_end
                    FROM visit_service_staffs
                    JOIN customer_visits on customer_visits.id_customer_visits=visit_service_staffs.customer_visit_id
                    JOIN visit_services on customer_visits.id_customer_visits=visit_services.customer_visit_id
                    and visit_service_status='Active' 
                    WHERE customer_visits.visit_status != 'canceled'
                    AND visit_service_staff_status='Active' 
                    AND date(visit_services.visit_service_start) = '".date('Y-m-d')."'                     
                    ) AS visit_service_staffs on visit_service_staffs.staff_id = staff.id_staff
            Where
                staff.staff_active='Y'
                and staff.staff_scheduler='On'
                and staff.business_id=".$this->session->userdata('businessid')."
            group by id_staff
            order by 5
            limit 1";

    //echo $sql; exit();
    $query = $this->db->query($sql);
    return $query->row();
  
   }

  
  function get_to_be_selected_staff(){
      
//      $this->db->select('id_staff, staff_fullname');
//      $this->db->where('staff.staff_fullname' , 'To Be Selected');
//      $this->db->or_where('staff.staff_firstname', 'Self-Service');
//      $this->db->where('staff.business_id' , $this->session->userdata('businessid'));
//      $query = $this->db->get('staff');
//      
      
      $Sql = "select id_staff, upper(staff_fullname) as staff_fullname 
              from staff 
              where staff.business_id = ".$this->session->userdata('businessid')." 
              and (upper(staff.staff_fullname) = 'TO BE SELECTED' OR upper(staff.staff_fullname) = 'SELF-SERVICE')";
      
      $query = $this->db->query($Sql);
      
      return $query->row();
  }
  




    public function add_visit($customer_id, $start, $businessid, $comment, $visit_id=0, $created_by='Online') {
        if ($visit_id == 0) {
            
            //$color = explode('|', $this->get_color_for_visit($last_color_code));
            $color = explode('|', $this->get_color_for_visit($start, $businessid));
            
            $visit = array(
                'business_id' => $businessid,
                'customer_id' => $customer_id,
                'visit_color' => $color[0],
                'visit_color_type' => $color[1],                
                'created_by'=>$created_by,
                'advance_comment'=>$comment
            );
            $this->db->insert('customer_visits', $visit);
            $visit_id = $this->db->insert_id();
            return $visit_id;
        } else {
            return $visit_id;
        }
    }
    
    function add_visit_services($customer_visit_id, $customer_id, $customer_name, $services, $staff, $staff_name, $start, $businessid, $loyaltyservice=null) {
        //print_r($start); exit();
      
            
//            $this->db->select('date_format(date_add(visit_service_end, interval 5 minute),"%Y-%m-%d %H:%i:%s") as visit_service_end');
//            $this->db->join('visit_service_staffs','visit_service_staffs.visit_service_id = visit_services.id_visit_services');
//            $this->db->join('customer_visits','customer_visits.id_customer_visits = visit_services.customer_visit_id');
//            $this->db->where('visit_service_staffs.staff_id', $staff);
//            $this->db->where('date(visit_services.visit_service_start)', date('Y-m-d'));
//            $this->db->where('visit_status !=', 'canceled');
//            $this->db->order_by('visit_service_staffs.id_visit_service_staffs', 'Desc');            
//            $this->db->limit(1);
//            $query = $this->db->get('visit_services');
//            
//            
//            
//            if($query->num_rows() > 0){
//                $last_service_time = $query->row();
//                if($last_service_time->visit_service_end > $start){
//                    $start =$last_service_time->visit_service_end;
//                }
//            }
      
        //$start = date('Y-m-d H:i:s');
        $this->db->select('id_business, business_opening_time, business_closing_time, rec_allow_prev as previous');
        $this->db->where('id_business', $businessid);
        $query = $this->db->get('business');
        $business=$query->row();
     
        $business_end_time = date("H:i:s",strtotime($business->business_closing_time.":00")) ;
        
        $bet =  date("Y-m-d H:i:s", strtotime($business->business_closing_time.":00")) ;
        if($bet < $start){
            $start = date('Y-m-d H:i:s', strtotime($bet. ' -20 minutes'));
        }
       //print_r($start);exit();
        
        $i = 0; $lastduration=0; 
        $s= explode(' ', $start);
        $newtime=$s[0].'T'.$s[1];
        //echo $newtime;
        foreach ($services as $service) {
            //print_r($service); exit();
            //get service details
            if($service['service_flag']=='servicetype'){
                $this->db->select('id_business_services as service_id, service_name, service_duration, "servicetype" as service_flag, service_category_id');
                $this->db->where('id_business_services', $service['service_id']);
                $query = $this->db->get('business_services');            
            }else{
                $this->db->select('id_business_services as service_id, service_name, service_duration, "packagetype" as service_flag, package_category_id as service_category_id');
                $this->db->join('package_services','package_services.service_id = business_services.id_business_services');
                $this->db->where('id_business_services', $service['service_id']);
                $query = $this->db->get('business_services');            
            }
            
            
            
            if($query->num_rows() == 1){
                $service_details=$query->row();
                // print_r($service_details); exit();
            }else{
                //service does not exist on the system
                $this->db->select('id_business_services as service_id, service_name, service_duration, "servicetype" as service_flag, service_category_id');
                $this->db->where('service_name', 'to be selected later');
                $query1 = $this->db->get('business_services');
                $service_details=$query1->row();
            }
            
            
            if(isset($service_details)){                
                if($i>0){ 

                    $durCal =  explode(':',$lastduration);
                    
                    
                    $HoursInMin=0;
                    if(intval($durCal[0]) > 0){$HoursInMin = intval($durCal)*60; }
                    $newduration = $HoursInMin + $durCal[1];
                    $newduration = date_interval_create_from_date_string($newduration.' minutes');
                    $newstart=date_create($start);
                    $newtime=date_add($newstart, $newduration);
                    $newtime=date_format($newtime,"c");
                    $d=  explode('+', (string)$newtime);
                    $newtime=$d[0];
                    //check business closing time
                    $thisstart=  explode('T', $newtime);
                    if($thisstart[1]>=$business_end_time){$newtime= str_replace(' ', 'T',$start);}

                    //check if duration is present
                    if($service_details->service_duration=="00:00:00"){$lastduration="00:15:00";}
                    else {
                        $lastduration=$service_details->service_duration;
                       // $lastduration="00:15:00";
                    }
                } else {                  
                  $lastduration=$service_details->service_duration;
                }
            
                //create endtime
                $HoursInMin=0; $newendtime='';
                $durCal =  explode(':',$lastduration);
                if(intval($durCal[0]) > 0){$HoursInMin = intval($durCal[0])*60; }
                $newduration = $HoursInMin + $durCal[1];
                $newduration = date_interval_create_from_date_string($newduration.' minutes');
                $newendtime=date_create($newendtime); 
                $newendtime = date_add(date_create($newtime), $newduration);
                $newendtime=date_format($newendtime,"c");
                $d=  explode('+', (string)$newendtime);
                $newendtime=$d[0];
                
                if(null!==$loyaltyservice){
                    $data = array(
                        'business_id' => $businessid,
                        'customer_visit_id' => $customer_visit_id,
                        'service_id' => $service_details->service_id,
                        'service_name' => $service_details->service_name,
                        'service_flag' => $service_details->service_flag,
                        'id_service_category' => $service_details->id_service_category,
                        'visit_service_start' => $newtime, //$start
                        'visit_service_end' => $newendtime, //end
                        'update_date' => date('Y-m-d H:i:s'),
                        'loyalty_service' => $loyaltyservice
                    );
                } else {
                    $data = array(
                        'business_id' => $businessid,
                        'customer_visit_id' => $customer_visit_id,
                        'service_id' => $service_details->service_id,
                        'service_name' => $service_details->service_name,
                        'service_flag' => $service_details->service_flag,
                        'id_service_category' => $service_details->service_category_id,
                        'visit_service_start' => $newtime, //$start
                        'visit_service_end' => $newendtime, //end
                        'update_date' => date('Y-m-d H:i:s')
                    );
                }
            
                $this->db->insert('visit_services', $data);
                $id_visit_services = $this->db->insert_id();

                //Staff
                $data = array(
                    'business_id' => $business->id_business,
                    'customer_visit_id' => $customer_visit_id,
                    'visit_service_id' => $id_visit_services,
                    'staff_id' => $staff,
                    'staff_name' => $staff_name,
                    'requested' => 'No',
                    'block_other' => 'No'
                );
                //var_dump($data);
                $this->db->insert('visit_service_staffs', $data);
                $i++;
            } 
        }
        
        return $customer_visit_id;
    }
 
    
    function get_color_for_visit($start, $businessid){
       $today=explode(' ',$start);
      
       $sql="
           select visit_color_code, visit_color_type from customer_visit_colors where visit_color_code not in(
            SELECT distinct(visit_color) 
            FROM customer_visits
            join visit_services on customer_visits.id_customer_visits = visit_services.customer_visit_id
            where date_format(visit_services.visit_service_start,'%Y-%m-%d') = '".$today[0]."'
            and visit_status != 'cancelled' and customer_visits.business_id = ".$businessid." order by id_visit_colors desc
            ) Limit 1";
        $query = $this->db->query($sql);        
        if ($query->num_rows() > 0) {
            $row = $query->row();
            return $row->visit_color_code.'|'.$row->visit_color_type;
        } else {
            //return the first color
            $this->db->select('visit_color_code, visit_color_type');
            //$this->db->where('business_id', $this->session->userdata('businessid'));
            $this->db->limit(1);
            $query = $this->db->get('customer_visit_colors');
            $row = $query->row();
            return $row->visit_color_code.'|'.$row->visit_color_type;
            
        }
        
    }
}