<?php

class Visits_model extends CI_Model {

    function __construct() {
        // Call the Model constructor
        parent::__construct();
         
    }
    function get_valid_visits(){
        
        $today = date('Y-m-d');
        $tomorrow= date('Y-m-d H:i:s', strtotime('tomorrow'));
        $this->db->select('*, date_format(visit_service_start, "%d-%m-%Y %H:%i") as mDate', false);
        $this->db->join('customer_visits', 'visit_services.customer_visit_id = customer_visits.id_customer_visits');
        $this->db->join('customers', 'customers.id_customers = customer_visits.customer_id');
        $this->db->where('visit_services.visit_service_start <', $tomorrow);
        $this->db->where('visit_services.visit_service_start >', $today);
        $this->db->where('visit_status <>', 'canceled');
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $this->db->where('visit_service_status','Active');
        $this->db->group_by('visit_services.customer_visit_id');
        $query = $this->db->get('visit_services');
       
        return $query->result_array();
        
    }
    
    function get_visits() {
        $today = date('Y-m-d');
        $tomorrow= date('Y-m-d H:i:s', strtotime('tomorrow'));
        $this->db->select('*, date_format(visit_service_start, "%d-%m-%Y %H:%i") as mDate', false);
        $this->db->join('customer_visits', 'visit_services.customer_visit_id = customer_visits.id_customer_visits');
        $this->db->join('customers', 'customers.id_customers = customer_visits.customer_id');
        $this->db->where('visit_services.visit_service_start <', $tomorrow);
        $this->db->where('visit_services.visit_service_start >', $today);
        $this->db->where('visit_status =', 'open');
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $this->db->where('visit_service_status','Active');
        $this->db->group_by('visit_services.customer_visit_id');
        $query = $this->db->get('visit_services');
       
        return $query->result_array();
    }
    
    
    function get_open_visits() {
        echo $this->session->userdata('businessid'); exit();
        $this->db->select('*, date_format(visit_service_start, "%d-%m-%Y %H:%i") as mDate', false);
        $this->db->join('customer_visits', 'visit_services.customer_visit_id = customer_visits.id_customer_visits');
        $this->db->join('customers', 'customers.id_customers = customer_visits.customer_id');
        $this->db->where('visit_status =', 'open');
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $this->db->where('visit_service_status','Active');
        $this->db->group_by('visit_services.customer_visit_id');
        $this->db->order_by('date(visit_service_start)', 'desc', false);
        $query = $this->db->get('visit_services');
      
        return $query->result_array();
    }
        
    function open_visit_list() {
        $today=date('Y-m-d');
        
       
           $sql="SELECT id_customer_visits, id_customers, customer_name, customer_cell, visit_service_start, date_format(visit_service_start, '%d-%m-%Y %H:%i') as mDate 
                FROM customer_visits 
                JOIN visit_services ON visit_services.customer_visit_id = customer_visits.id_customer_visits 
                and visit_service_status='Active' 
                JOIN customers ON customers.id_customers = customer_visits.customer_id 
                WHERE visit_status = 'open' AND customer_visits.business_id = '".$this->session->userdata('businessid')."'
                and date_format(visit_service_start, '%Y-%m-%d') = '".$today."'
                group by id_customer_visits
                ORDER BY date_format(visit_service_start, '%Y-%m-%d %H:%i') DESC";
       
        
      
        $query=$this->db->query($sql);
        
        return $query->result_array();
    }
    
    function day_open_visit_list($today=null) {
        if($today==null){
            $today = date('Y-m-d');
        }
           $sql="SELECT id_customer_visits, id_customers, customer_name, customer_cell, visit_service_start, date_format(visit_service_start, '%d-%m-%Y %H:%i') as mDate 
                FROM customer_visits 
                JOIN visit_services ON visit_services.customer_visit_id = customer_visits.id_customer_visits 
                and visit_service_status = 'Active' 
                JOIN customers ON customers.id_customers = customer_visits.customer_id 
                WHERE visit_status = 'open' AND customer_visits.business_id = '".$this->session->userdata('businessid')."'
                and date_format(visit_service_start, '%Y-%m-%d') = '".$today."'
                group by id_customer_visits
                ORDER BY date_format(visit_service_start, '%Y-%m-%d %H:%i') DESC";
       
        
      
        $query=$this->db->query($sql);
        
        return $query->result_array();
    }
    
    function inservice_visit_list() {
        $today=date('Y-m-d');
        
        $sql="SELECT id_customer_visits, id_customers, customer_name, customer_cell, visit_service_start, date_format(visit_service_start, '%d-%m-%Y %H:%i') as mDate 
                FROM customer_visits 
                JOIN visit_services ON visit_services.customer_visit_id = customer_visits.id_customer_visits 
                AND visit_service_status='Active' 
                JOIN customers ON customers.id_customers = customer_visits.customer_id 
                WHERE visit_status = 'open' AND customer_visits.business_id = '".$this->session->userdata('businessid')."'
                and inservice = 'Yes'
                and date_format(visit_service_start, '%Y-%m-%d') = '".$today."'
                group by id_customer_visits
                ORDER BY date_format(visit_service_start, '%Y-%m-%d %H:%i') DESC";
     
        
      
        $query=$this->db->query($sql);
        
        return $query->result_array();
    }
    
    function check_color($colorcode){
        $this->db->select('*');
        $this->db->where('visit_color', $colorcode);
        $this->db->where('visit_status', 'open');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customer_visits');
        return $query->row();
    }
    
    function update_visit(){
         // Unescape the string values in the JSON array
        $tableData = stripcslashes($this->input->post('visitdata', TRUE));
        $visitdate = stripslashes($this->input->post('visit-date', TRUE));

        // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
        
        // now $tableData can be accessed like a PHP array
        //echo $tableData[0]['servicename'];
        //echo $this->input->post('visitid');
        
        $visit_id = $this->input->post('visitid', TRUE);
        
        //update customer_visit
        
        $this->db->where('customer_visit_id', $visit_id);
        //$this->db->delete('visit_services');
        $this->db->update('visit_services', array('visit_service_status'=>'Cancelled'));
        
        $this->db->where('customer_visit_id', $visit_id);
        //$this->db->delete('visit_service_staffs');
        $this->db->update('visit_service_staffs', array('visit_service_staff_status'=>'Cancelled'));
        
        $this->db->where('customer_visit_id', $visit_id);
        $this->db->delete('visit_service_products');
        
        // current date and time for the services
        $service_start_date_time = date('Y-m-d\TH:i:s', strtotime($visitdate));
        
        foreach($tableData as $row){
            
            $data = array(
                'business_id' => $this->session->userdata('businessid'),
                'customer_visit_id' => $visit_id,
                'service_id' => $row['serviceid'],
                'service_name' => $row['servicename'],
                'visit_service_start' => $service_start_date_time
            );
            
            $this->db->insert('visit_services', $data);
            
            $id_visit_services = $this->db->insert_id();
            
            $staff = array(
                'business_id' => $this->session->userdata('businessid'),
                'customer_visit_id' => $visit_id,
                'visit_service_id' => $id_visit_services,
                'staff_id' => $row['staffid'],
                'staff_name' => $row['staff']
            );
            $this->db->insert('visit_service_staffs', $staff);
            
            $product_ids = explode('|', $row['productid']);
            $product_names = explode('|', $row['productname']);
            
            $k = 0;
            foreach($product_ids as $product_id){
                if($product_id > 0 && !empty($product_id)){
                    $products = array(
                        'business_id' => $this->session->userdata('businessid'),
                        'customer_visit_id' => $visit_id,
                        'visit_service_id' => $id_visit_services,
                        'product_id' => $product_id,
                        'product_name' => $product_names[$k]
                    );
                    $this->db->insert('visit_service_products', $products);
                }
                $k++;
            }
           
            ///update staff status
//            $this->db->set('staff_available', $visit_id);
//            $this->db->where('business_id', $this->session->userdata('businessid'));
//            $this->db->where('time_out', null);
//            $this->db->where('staff_available', '');
//            $this->db->where('staff_id', $row['staffid']);
//            $this->db->update('staff_attendance');

        }
        
        return $visit_id;
    }
    
    function getinvoicedvisitbyid($visitid){
        
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = customer_visits.customer_id');
        $this->db->join("visit_services", "visit_services.customer_visit_id = customer_visits.id_customer_visits and visit_service_status='Active'");        
        $this->db->join("visit_service_staffs", "visit_services.id_visit_services = visit_service_staffs.visit_service_id and visit_service_staff_status='Active'");
        $this->db->join('visit_service_products', 'visit_services.id_visit_services = visit_service_products.visit_service_id', 'left');
        $this->db->where('visit_services.customer_visit_id =', $visitid);
        $this->db->where('visit_status =', 'invoiced');
        //$this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customer_visits');
       
        return $query->result_array();
    }
    
    function getopenvisitbyid($visitid, $anybusiness=false){
        
//        $variables = [$visitid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        //echo $fine; exit();
        
        
        $this->db->select('*, DATE_FORMAT(vs.visit_service_start, "%Y-%m-%d %k:%i:%s") AS visitdate, DATE_FORMAT(cv.advance_date, "%d-%m-%Y %k:%i") AS advance_date, DATE_FORMAT(cv.advance_date, "%Y-%m-%d") AS check_date');
        $this->db->join('customers c', 'cv.customer_id = c.id_customers');
        $this->db->join("visit_services vs", "vs.customer_visit_id = cv.id_customer_visits and vs.visit_service_status='Active'");
        $this->db->join('business_services bs', 'vs.service_id = bs.id_business_services');
        $this->db->join('service_category sc', 'bs.service_category_id = sc.id_service_category');
        $this->db->join('visit_service_products vsp', 'vs.id_visit_services = vsp.visit_service_id', 'left');
        $this->db->join("visit_service_staffs vss", "vs.id_visit_services = vss.visit_service_id and vss.visit_service_staff_status='Active'", 'left');
        $this->db->where('vs.customer_visit_id', $visitid);
        $this->db->where('cv.visit_status', 'open');
        if($anybusiness==false){
            $this->db->where('cv.business_id', $this->session->userdata('businessid'));
        }
        $this->db->group_by('vs.id_visit_services');
        $query = $this->db->get('customer_visits cv');
        //echo $query; exit();
        return $query->result_array();
    }
    function getopenvisitadvancebyid($visitid){
//        $variables = [$visitid];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*, date_format(advance_date, "%d-%m-%Y %h:%i") as date', false);
        $this->db->where('customer_visit_id',$visitid);
        $query = $this->db->get('visit_advance');
        
        return $query->result_array();
        
    }
    function getopenvisitadvancesumbyid($visitid){
//        $variables = [$visitid];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('sum(advance_amount) as advance_amount, advance_user, advance_mode', false);
        $this->db->where('customer_visit_id',$visitid);
        $this->db->group_by('customer_visit_id');
        $query = $this->db->get('visit_advance');
        
        return $query->result_array();
        
    }
    
    function getopenvisitadvancecommentsbyid($visitid){
//        $variables = [$visitid];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('advance_remarks', false);
        $this->db->where('customer_visit_id',$visitid);
        $query = $this->db->get('visit_advance');
        
        return $query->result_array();
        
    }
    
    function getadvancevisitbyid($visitid){
//        $variables = [$visitid];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*, DATE_FORMAT(vs.visit_service_start, "%Y-%m-%d %k:%i:%s") AS visitdate, DATE_FORMAT(cv.advance_date, "%d-%m-%Y %k:%i") AS advance_date , DATE_FORMAT(cv.created_on, "%d/%m/%Y") AS created_on');
        $this->db->join('customers c', 'cv.customer_id = c.id_customers');
        $this->db->join("visit_services vs", "vs.customer_visit_id = cv.id_customer_visits and vs.visit_service_status='Active'");
        $this->db->join('business_services bs', 'vs.service_id = bs.id_business_services');
        $this->db->join('service_category sc', 'bs.service_category_id = sc.id_service_category');
        //$this->db->join('visit_service_products vsp', 'vs.id_visit_services = vsp.visit_service_id', 'left');
        $this->db->join("visit_service_staffs vss", "vs.id_visit_services = vss.visit_service_id and vss.visit_service_staff_status= 'Active'");
        $this->db->where('vs.customer_visit_id', $visitid);
        //$this->db->where('cv.advance', 'true');
        $this->db->where('cv.visit_status <>', 'canceled');
        //$this->db->where('cv.business_id', $this->session->userdata('businessid'));
        //$this->db->group_by('vsp.product_name');
        $query = $this->db->get('customer_visits cv');
        
        return $query->result_array();
    }
    
    
    function getvisitbyid($visitid){
//        $variables = [$visitid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*');
        $this->db->join('customers', 'customers.id_customers = customer_visits.customer_id');
        $this->db->join('visit_services', "visit_services.customer_visit_id = customer_visits.id_customer_visits and visit_service_status='Active'");
        $this->db->where('customer_visit_id =', $visitid);
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customer_visits');
        return $query->result_array();
    }
    
    function getServicesByVisitId($id){
        $variables = [$id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $where = array(
            'business_id' => $this->session->userdata('businessid'),
            'customer_visit_id' => $id
        );
        
        $this->db->select('*');
        $this->db->where($where);
        $this->db->where('visit_service_status','Active');
        $query = $this->db->get('visit_services');
        
        return $query->result_array();
        
    }
    
    function getvisitbycid(){
//        $variables = [$this->input->post('customer_id', TRUE), $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        
        $this->db->select('*');
        $this->db->join('visit_services', "customer_visits.id_customer_visits = visit_services.customer_visit_id and visit_service_status='Active'");
        $this->db->where('customer_visits.customer_id', $this->input->post('customer_id', TRUE));
        $this->db->where('customer_visits.visit_status', 'open');
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customer_visits');
        
        return $query->result_array();
    }
    
    function getpassedvisitbycid(){
//        $variables = [$this->input->post('customer_id', TRUE), $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $today = date('Y-m-d');
        $this->db->select('id_customer_visits');
        $this->db->join('visit_services', "customer_visits.id_customer_visits = visit_services.customer_visit_id and visit_service_status='Active'");
        $this->db->where('customer_visits.customer_id', $this->input->post('customer_id', TRUE));
        $this->db->where('customer_visits.visit_status', 'open');
        $this->db->where('date(visit_services.visit_service_start) <=', $today);
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $this->db->order_by('id_customer_visits', 'desc');
        $this->db->limit(1);
        $query = $this->db->get('customer_visits');
        
        return $query->result_array();
    }
    
    function getvisitstaffs($visitid){
//        $variables = [$visitid];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*');
        $this->db->where('customer_visit_id', $visitid);
        $this->db->where('visit_service_staff_status','Active');
        $query = $this->db->get('visit_service_staffs');
        return $query->result_array();
    }
    
    function getvisitserviceproducts($visitid){
//        $variables = [$visitid];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        
        $this->db->select('*');
        $this->db->join('business_products','id_business_products = product_id');
        $this->db->join('visit_services',"id_visit_services=visit_service_id and visit_service_status='Active'");
        $this->db->where('visit_service_products.customer_visit_id', $visitid);
        $query = $this->db->get('visit_service_products');
        return $query->result_array();
    }
    
    function getvisitservices($visitid){
//        $variables = [$visitid];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('id_visit_services, vs.business_id, vs.customer_visit_id, vs.service_id, vs.service_name, visit_service_start, date_format(visit_service_start,"%d-%m-%Y %H:%s") as "vdate", '
                . 'visit_service_end, update_date, service_flag, vs.id_service_category, id_business_services, service_category_id, '
                . 'service_desc, created_date, bs.service_rate, service_active, commission_perc, '
                . 'service_color, service_duration, '
                . 'service_type_id, sc.service_category, service_category_active, '
                . 'service_category_image, id_service_types, st.service_type, service_type_image, '
                . 'service_type_active, id_visit_service_staffs, visit_service_id, staff_id, staff_name, loyalty_service, membership, 0 as option_number');
        $this->db->join('business_services bs', 'vs.service_id = bs.id_business_services');
        $this->db->join('service_category sc', 'sc.id_service_category = bs.service_category_id');
        $this->db->join('service_type st', 'sc.service_type_id = st.id_service_types');
        $this->db->join('visit_service_staffs ssf', "vs.id_visit_services = ssf.visit_service_id and ssf.visit_service_staff_status='Active'");
        $this->db->where('vs.customer_visit_id', $visitid);
        //$this->db->where('vs.business_id', $this->session->userdata('businessid'));
        $this->db->where('vs.service_flag', 'servicetype');
        $this->db->where('vs.visit_service_status','Active');
        $this->db->group_by('ssf.visit_service_id');
        $subQuery1 = $this->db->get_compiled_select('visit_services vs');
        
        
        $this->db->select('id_visit_services, vs.business_id, vs.customer_visit_id, vs.service_id, vs.service_name, visit_service_start, date_format(visit_service_start,"%d-%m-%Y %H:%s") as "vdate", '
                . 'visit_service_end, update_date, service_flag, vs.id_service_category as "id_service_category", id_business_services, '
                . 'pc.id_package_category as "service_category_id", service_desc, created_date, '
                . 'ps.service_rate as  "service_rate", service_active, commission_perc, service_color, service_duration, '
                . 'pc.package_type_id as "service_type_id", pc.service_category, '
                . 'service_category_active, service_category_image, id_package_type as "id_service_types", pt.service_type, '
                . 'service_type_image, service_type_active, id_visit_service_staffs, visit_service_id, staff_id, staff_name, loyalty_service, membership, ifnull(package_option_number,0) as option_number', false);
        $this->db->join('business_services bs', 'vs.service_id = bs.id_business_services');
        $this->db->join('package_services ps', 'vs.service_id = ps.service_id and vs.id_service_category=ps.package_category_id');
        $this->db->join('package_category pc', 'pc.id_package_category = ps.package_category_id');
        $this->db->join('package_type pt', 'pc.package_type_id = pt.id_package_type');
        $this->db->join('visit_service_staffs ssf', "vs.id_visit_services = ssf.visit_service_id and visit_service_staff_status='Active'");        
        $this->db->where('vs.customer_visit_id', $visitid);
       // $this->db->where('vs.business_id', $this->session->userdata('businessid'));
        $this->db->where('vs.service_flag', 'packagetype');        
        $this->db->where('vs.visit_service_status','Active');
        $this->db->group_by('ssf.visit_service_id');
        $subQuery2 = $this->db->get_compiled_select('visit_services vs');
        
        //echo $subQuery1;
        //echo $subQuery2; 
        $query = $this->db->query("select * from (".$subQuery1." UNION ".$subQuery2.") as unionTable order by visit_service_start");
        
        return $query->result_array();
    }
    
    function getlast4visits($customerid){
//        $variables = [$customerid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*, date_format(customer_visit_date,"%d-%m-%Y") as visit_date');
        $this->db->join('visit_services', "visit_services.customer_visit_id = customer_visits.id_customer_visits and visit_service_status='Active'");
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $this->db->where('visit_status =', 'invoiced');
        $this->db->where('customer_visits.customer_id', $customerid);
        $this->db->order_by('customer_visits.id_customer_visits DESC, service_id ASC');
        $this->db->limit(4);
        $query = $this->db->get('customer_visits');
                
        return $query->result_array();
    }
    
    function getstaffclient($visitid){
//        $variables = [$visitid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('customer_name, date_format(customer_visit_date,"%h:%i:%s") as "since", service_name');
        $this->db->join('customers', 'customers.id_customers = customer_visits.customer_id');
        $this->db->join('visit_services', "visit_services.customer_visit_id = customer_visits.id_customer_visits and visit_service_status='Active'");
        $this->db->where('customer_visits.business_id', $this->session->userdata('businessid'));
        $this->db->where('visit_status =', 'open');
        $this->db->where('id_customer_visits', $visitid);
        
        $query = $this->db->get('customer_visits');
        
        
        return $query->result_array();
    }
    
    
    function update_advance(){
//        $variables = [$this->input->post('visit_id', TRUE), $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
                
        
        $today = date('Y-m-d H:i');
        
        $visitid=$this->input->post('visit_id', TRUE);
        $amount=$this->input->post('advance_amount', TRUE);
        $mode = $this->input->post('advance_mode', TRUE)== 'check' ? 'bank' : $this->input->post('advance_mode', TRUE);
        $visit_advance_mode= $this->input->post('advance_mode', TRUE)== 'bank' ? 'check' : $this->input->post('advance_mode', TRUE);
        $inst=$this->input->post('advance_inst', TRUE);
        $comment=$this->input->post('advance_comment', TRUE);
        
        if(null !== $this->input->post('visit_customername', TRUE)){
            $customername=$this->input->post('visit_customername', TRUE);
            $customerid=$this->input->post('visit_customerid', TRUE);
        } else {
            $this->db->select('id_customers, customer_name');
            $this->db->join('customer_visits', 'customer_visits.customer_id = customers.id_customers');
            $this->db->where('id_customer_visits', $visitid);
            $query = $this->db->get('customers');
            $customer=$query->row();
            
            $customerid = $customer->id_customers;
            $customername = $customer->customer_name;
            
        }
        
        $advance_cccharge=$this->input->post('advance_cc_charge')==null ? 0: $this->input->post('advance_cc_charge');
        
        
        
       // if ((float)$amount>0){
            $this->db->set('advance_amount', $amount);
            $this->db->set('customer_visit_id', $visitid);
            $this->db->set('advance_mode', $visit_advance_mode);
            $this->db->set('advance_date', $today);
            $this->db->set('advance_inst', $inst);
            $this->db->set('advance_remarks', $comment);
            $this->db->set('advance_user', $this->session->userdata('username'));
            if(null!==$this->input->post('advance_cc_charge')){
                $this->db->set('advance_cc_charge', $this->input->post('advance_cc_charge'));
            }
            
            $this->db->insert('visit_advance');
            
            $advance_id=$this->db->insert_id();
        //}
        
        
        ////update visit
        
        $this->db->set('advance', 'true');            
        $this->db->where('id_customer_visits', $visitid);
        //$this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->update('customer_visits');
        
        ///update visit services
        $this->db->where('customer_visit_id', $visitid);
        $this->db->update('visit_services', array('update_date' => date('Y-m-d H:i:s')));
        
        
        ///create auto account voucher
        if($this->session->userdata('auto_voucher')=='Yes'){
            
            //get customer details
            $this->db->select("customer_name, id_customers");
            $this->db->join("customers", "customers.id_customers = customer_visits.customer_id");
            $this->db->where("id_customer_visits", $visitid);
            $query= $this->db->get("customer_visits");

            $customer = $query->row();
            
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(2);
            //var_dump ($account_heads); exit();
            foreach($account_heads as $ah){
                if($ah['transaction_type']=='debit'){
                   array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                } else {
                    array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                }
            }
            
            $bank_name='';
            //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => 'Advance Received against Visit ID: ' . $visitid . ' on '. date('d-m-Y').', from '.$customer->customer_name.' customer ID : '. $customer->id_customers,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $amount+$advance_cccharge,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$customer->id_customers,
                'business_partner_name'=>$customer->customer_name,
                'voucher_type'=>2,
                'payment_mode'=>$mode,
                'bank_name'=>$bank_name,
                'visit_id'=>$visitid,
                'visit_advance_id'=>$advance_id,
                'auto_voucher'=>'Yes',
                'sale_type'=>'service',
                
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                if($debit[2]=="paid_cash" && strtolower($mode) == "cash"){$debitamount= $amount+$advance_cccharge;}
                if($debit[2]=="paid_card" && strtolower($mode) == "card"){$debitamount= $amount+$advance_cccharge;}
                if($debit[2]=="paid_check" && strtolower($mode) == "bank"){$debitamount= $amount+$advance_cccharge;}
                if($debit[2]=="paid_voucher" && strtolower($mode) == "voucher"){$debitamount= $amount+$advance_cccharge;}
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'debit' => round($debitamount,2),
                    'credit' => 0,
                    'instrument_number' => $inst
                );
                //insert debit detail
                if($debitamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
            //enter credit entries
            foreach($credit_accounts as $credit_account){
                $creditamount=0;
                $credit = explode("|", $credit_account);
                //check entity
                
                if($credit[2]=="advance_amount"){$creditamount= $amount;}
                if($credit[2]=="cc_fee" && $advance_cccharge>0){$creditamount= $advance_cccharge;}
               
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'debit' => 0,
                    'credit' => round($creditamount,2),
                    'instrument_number' => $inst
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
        }
        
        
        return $visitid;
        
    }
    
    
    
    
    function update_advance_old(){
        
        $today = date('Y-m-d H:i');
        
        $visitid=$this->input->post('visit_id', TRUE);
        $amount=$this->input->post('advance_amount', TRUE);
        $mode=$this->input->post('advance_mode', TRUE);
        $inst=$this->input->post('advance_inst', TRUE);
        $comment=$this->input->post('advance_comment', TRUE);
        
        $this->db->set('advance_amount', $amount);
        if ((float)$amount>0){
            $this->db->set('advance', 'true');
            $this->db->set('advance_mode', $mode);
            $this->db->set('advance_date', $today);
            $this->db->set('advance_inst', $inst);
            $this->db->set('advance_comment', $comment);
        }
        $this->db->where('id_customer_visits', $visitid);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->update('customer_visits');
        
        return $visitid;
        
    } 
    
    
    function remove_advance(){
        
        $today = date('Y-m-d');
        
        $advanceid=$this->input->post('advance_id', TRUE);
    //    $visitid=$this->input->post('visit_id', TRUE);
        
        $this->db->select('*, date_format(advance_date, "%Y-%m-%d") as advdate');
        $this->db->where('id_visit_advance',$advanceid);
      //  $this->db->where('customer_visit_id',$visitid);
        $query = $this->db->get('visit_advance');
       
        $result=$query->row();
        
        if(isset($result->advdate)){
            if($result->advdate == $today || $this->session->userdata('role')=='Super User'){
                $this->db->where('id_visit_advance', $advanceid);
                $this->db->set('advance_amount',0);
                $this->db->set('advance_cc_charge',0);
             //   $this->db->where('customer_visit_id', $visitid);
                $this->db->update('visit_advance');
                
                //change account voucher status
                    $this->db->where('visit_advance_id', $advanceid);
                    $this->db->update('account_vouchers', array('voucher_status' => 'cancelled', 'cancelled_by' => $this->session->userdata('username'), 'cancelled_on' => date('Y-m-d H:i:s')));
                    
                
                
                echo 'Advance removed!';
            } else {
                echo 'Advances booked on previous dates can not be removed!';
            }
        } else {
            echo "Advance does not exist!";
        }
        
       
        
    } 
    
    public function create_booking(){
//        exit();
//        $variables = [$this->input->post('customer_id'), $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        if($this->input->post('customer_id')==0){ return 0; exit();}
        
        
        $booking = array(
            'business_id'=>$this->session->userdata('businessid'),
            'customer_id'=>$this->input->post('customer_id'),
            'package_id'=>$this->input->post('package_id'),
            'discount'=>$this->input->post('discount')
        );
        $this->db->insert('bookings', $booking);
        $booking_id = $this->db->insert_id();
        
        
        // Unescape the string values in the JSON array
        $tableData = stripcslashes($this->input->post('tabledata', TRUE));        
        // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
        //print_r($tableData);echo('<br>');
        // now $tableData can be accessed like a PHP array
//        echo '<pre>';
//         print_r($tableData);
//        exit();
        $visit_ids='';
        $data = [];
        
        
        if(SINGLE_PERIOD_BOOKING == TRUE){
            $paymentmode='cash';
            foreach($tableData as $row){
                if($this->input->post('advance_amount')>0){
                    $paymentmode=$row['payment_mode'];
                }
            }
            //add new customer_visit
            $visit = array(
                'business_id' => $this->session->userdata('businessid'),
                'customer_id' => $this->input->post('customer_id'),
                'customer_visit_date' => date('Y-m-d H:i:s'),
                'visit_color' => $this->input->post('visit_color'),
                'visit_color_type' => $this->input->post('visit_color_type'),
                'discount' => $this->input->post('discount'),
                'advance' => $this->input->post('advance'),
                'advance_amount' => $this->input->post('advance_amount'),
                'advance_mode' => $paymentmode,
                'advance_inst' => $this->input->post('advance_inst'),
                'advance_date' => date('Y-m-d H:i:s'),
                'advance_comment' => $this->input->post('visit_remarks'),
                'customer_visit_date'=>date('Y-m-d H:i:s'),
                'created_by'=>$this->session->userdata('username'),
                'referring_staff'=>$this->input->post('referring_staff'),                
                'customer_event_date'=> $this->input->post('event_date')!=null ? $this->input->post('event_date')!=''? $this->input->post('event_date') : null : null   
            );
            $this->db->insert('customer_visits', $visit);
            $visit_id = $this->db->insert_id();
        } 
        
        //process the table data
        foreach($tableData as $row){
            
            if(SINGLE_PERIOD_BOOKING == FALSE){
                //add new customer_visit
                $visit = array(
                    'business_id' => $this->session->userdata('businessid'),
                    'customer_id' => $this->input->post('customer_id'),
                    'customer_visit_date' => date('Y-m-d H:i:s'),
                    'visit_color' => $this->input->post('visit_color'),
                    'visit_color_type' => $this->input->post('visit_color_type'),
                    'discount' => $row['discount'],
                    'advance' => $this->input->post('advance'),
                    'advance_amount' => $row['advance'],
                    'advance_mode' => $row['payment_mode'],
                    'advance_inst' => $this->input->post('advance_inst'),
                    'advance_date' => date('Y-m-d H:i:s'),
                    'advance_comment' => $this->input->post('visit_remarks'),
                    'customer_visit_date'=>date('Y-m-d H:i:s'),
                    'created_by'=>$this->session->userdata('username'),
                    'referring_staff'=>$this->input->post('referring_staff'),                
                    'customer_event_date'=> $this->input->post('event_date')!=null ? $this->input->post('event_date')!=''? $this->input->post('event_date') : null : null   
                );
                $this->db->insert('customer_visits', $visit);
                $visit_id = $this->db->insert_id();
            } 
            //Add visit to booking
            $booking_visit = array(
                'booking_id'=>$booking_id,
                'visit_id'=>$visit_id,
                'category_id'=>$row['category_id']
            );
            $this->db->insert('booking_visits', $booking_visit);
            ////add new customer_visit end
            
            
            $id_package_type=$this->input->post('package_type_id');
            
            $this->db->select('*, package_services.service_rate as service_rate');
            $this->db->join('package_category', 'package_services.package_category_id = package_category.id_package_category');
            $this->db->join('package_type', 'package_type.id_package_type = package_category.package_type_id');
            $this->db->join('business_services', 'business_services.id_business_services=package_services.service_id');
            $this->db->where('package_category_id', $row['category_id']);
            $this->db->where('package_services_active', "Yes");
            $this->db->where('package_option_number', 0);
            $this->db->where('business_services.business_id', $this->session->userdata('businessid'));
            $visit_services=$this->db->get('package_services');            
            
            
            $service_flag="packagetype";
            $start = date('Y-m-d\TH:i:s', strtotime($row['day'].' '.$row['hour']));
            
            $i = 0; $lastduration=0; $newtime='';
            foreach($visit_services->result() as $vs){
                
                //get service start time
                if($i>0){ 
                    
                    $durCal =  explode(':',$lastduration);
                    $HoursInMin=0;
                    if(intval($durCal[0]) > 0){$HoursInMin = intval($durCal[0])*60;}
                    $newduration = $HoursInMin + $durCal[1]; 
                    $newduration = date_interval_create_from_date_string($newduration.' minutes');
                    $newstart=date_create($newtime);
                    $newtime=date_add($newstart, $newduration);
                    $newtime=date_format($newtime,"c");
                    $d=  explode('+', (string)$newtime);
                    $newtime=$d[0];
                    $lastduration=$vs->service_duration;
                } else {
                   $newtime=$start;
                   $lastduration=$vs->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];
                //
                
               //print_r($newtime);echo('<br>');
               // service start time in $newtime
               
                
                $serviceid=$vs->service_id;
                $servicename=$vs->service_name;
                $serviceqty=1;
                
                //echo $vs->package_service_optional;
                if($vs->package_service_optional=='Yes' ){
                    $serviceoptions = explode(",", $row['services']);
                    
                    foreach($serviceoptions as $serviceoption){
                        $passedservices= explode("|", $serviceoption);
                        //var_dump($passedservices);
                        //echo '<br>'.sizeof($passedservices).'<br>';
                        if(sizeof($passedservices)>1){
                            $passedreplace = $passedservices[0];
                            $passedreplacewith = $passedservices[1];
                            //echo $vs->service_id;
                            if($vs->service_id == $passedreplace){

                                $this->db->select('*');
                                $this->db->where('id_business_services', $passedreplacewith);
                                $q = $this->db->get('business_services');
                                $replace = $q->row();

                                $serviceid=$replace->id_business_services;
                                $servicename=$replace->service_name;
                                $serviceqty=$passedservices[2];
                              //  echo $serviceid;
                              //  echo $servicename;
                            }
                        }
                        //$serviceid=
                    }
                }
                $optional='';
                for($x=1; $x<=$serviceqty; $x++){
                    if($x>1){$optional = '(nc)';}
                    $data = array(
                        'business_id' => $this->session->userdata('businessid'),
                        'customer_visit_id' => $visit_id,
                        //'service_id' => $vs->service_id,
                        'service_id' => $serviceid,
                        //'service_name' => $vs->service_name,
                        'service_name' => rtrim($servicename.' '.$optional),
                        'service_flag' => $service_flag,
                        'id_service_category' => $vs->package_category_id,
                        'visit_service_start' => $newtime, //$start
                        'visit_service_end' => $newendtime, //end
                        'update_date' => date('Y-m-d H:i:s'),
                        's_rate'=>$vs->service_rate,
                        's_type'=>$vs->service_type,
                        's_category'=>$vs->service_category,
                        'id_service_type'=>$vs->id_package_type
                     );

                     $this->db->insert('visit_services', $data);
                     $id_visit_services = $this->db->insert_id();

                     //check shared staff
                     $block_other='No';

                     $this->db->select('staff_shared');
                     $this->db->where('id_staff=',$row['staffid']);
                     $query = $this->db->get('staff');
                     $blockstaff = $query->row();

                     if (isset($blockstaff))
                     { $block_other =  $blockstaff->staff_shared; }


                     //insert service staff 
                     $staff = array(
                         'business_id' => $this->session->userdata('businessid'),
                         'customer_visit_id' => $visit_id,
                         'visit_service_id' => $id_visit_services,
                         'staff_id' => $row['staffid'],
                         'staff_name' => $row['staffname'],
                         'block_other'=>$block_other
                     );
                    $this->db->insert('visit_service_staffs', $staff);

                    //insert service products

                     $this->db->select('*');
                     $this->db->join('business_products', 'business_products.id_business_products = services_products.business_product_id');
                     $this->db->where('business_service_id', $vs->service_id);
                     //$this->db->where('services_products.business_id', $this->session->userdata('businessid'));
                     $service_products=$this->db->get('services_products');
                     
                   
                     foreach($service_products->result() as $sp){
                         $products = array(
                             'business_id' => $this->session->userdata('businessid'),
                             'customer_visit_id' => $visit_id,
                             'visit_service_id' => $vs->service_id,
                             'product_id' => $sp->business_product_id,
                             'product_name' => $sp->product,
                             'product_qty' => $sp->usage_qty,
                             'product_unit' => $sp->measure_unit
                          );
                          $this->db->insert('visit_service_products', $products);
//                         print_r($products);echo('<br>');
                     }
                     $i++;
                 }
            }
            ///add advance
            $visit_adv_mode = $row['payment_mode']=='bank' ? 'check' : $row['payment_mode'];
            $advance_date = date('Y-m-d H:i:s', strtotime($row['advance_date']. ' '.date("H:i:s")));
            
            $adv=array(
                'customer_visit_id' => $visit_id,
                'advance_amount' => $row['advance'],
                'advance_mode' => $row['payment_mode'],
                'advance_inst' => $row['instrument_number'],
                'advance_date' => $advance_date,
                'advance_user' => $this->session->userdata('username'),
                'advance_cc_charge' => $row['cccharge']
            );
            $this->db->insert('visit_advance', $adv);

           $advance_id = $this->db->insert_id();
           
            $mode = $row['payment_mode'];
            $amount = "" != $row['advance'] ? $row['advance'] : 0; 
            $advance_cccharge= "" != $row['cccharge'] ? $row['cccharge'] : 0;
            $inst=$row['instrument_number'];

        
            ///create auto account voucher
            if($this->session->userdata('auto_voucher')=='Yes'){

                //get customer details
                $this->db->select("customer_name, id_customers");
                $this->db->join("customers", "customers.id_customers = customer_visits.customer_id");
                $this->db->where("id_customer_visits", $visit_id);
                $query= $this->db->get("customer_visits");

                $customer = $query->row();

                $debit_accounts=[];
                $credit_accounts=[];

                $account_heads = $this->accounting_model->get_mapped_accounts(2);
                //var_dump ($account_heads); exit();
                foreach($account_heads as $ah){
                    if($ah['transaction_type']=='debit'){
                       array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                    } else {
                        array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                    }
                }

                $bank_name='';
                //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
                $data = array( 
                    'business_id' => $this->session->userdata('businessid'),
                    'description' => 'Advance Received against Visit ID: ' . $visit_id . ' on '. date('d-m-Y').', from '.$customer->customer_name.' customer ID : '. $customer->id_customers,
                    'voucher_date' => date('Y-m-d H:i:s'),
                    'voucher_amount' => $amount + $advance_cccharge,
                    'voucher_status' => 'Active',
                    'created_by' => $this->session->userdata('username'),
                    'cost_center'=> '1',
                    'cost_center_name'=> 'Front Desk',
                    'business_partner'=> 1,
                    'business_partner_id'=>$customer->id_customers,
                    'business_partner_name'=>$customer->customer_name,
                    'voucher_type'=>2,
                    'payment_mode'=>$mode,
                    'bank_name'=>$bank_name,
                    'visit_id'=>$visit_id,
                    'visit_advance_id'=>$advance_id,
                    'auto_voucher'=>'Yes',
                    'sale_type'=>'service',

                );

                $this->db->insert('account_vouchers', $data);
                $account_voucherid =  $this->db->insert_id();

                //enter debit entries
                foreach($debit_accounts as $debit_account){
                    $debitamount=0;
                    $debit = explode("|", $debit_account);
                    //check entity
                    if($debit[2]=="paid_cash" && strtolower($mode) == "cash"){$debitamount= $amount;}
                    if($debit[2]=="paid_card" && strtolower($mode) == "card"){$debitamount= $amount+$advance_cccharge;}
                    if($debit[2]=="paid_check" && strtolower($mode) == "check"){$debitamount= $amount;}
                    if($debit[2]=="paid_voucher" && strtolower($mode) == "voucher"){$debitamount= $amount;}

                    $data_detail=array(
                        'account_voucher_id' => $account_voucherid,
                        'account_head_id' => $debit[0],
                        'debit' => round($debitamount,2),
                        'credit' => 0,
                        'instrument_number' => $this->input->post('advance_inst')
                    );
                    //insert debit detail
                    if($debitamount>0){
                        $this->db->insert('account_voucher_detail', $data_detail);
                    }
                }
                //enter credit entries
                foreach($credit_accounts as $credit_account){
                    $creditamount=0;
                    $credit = explode("|", $credit_account);
                    //check entity

                    if($credit[2]=="advance_amount"){$creditamount= $amount;}
                    if($credit[2]=="cc_fee" && $advance_cccharge>0 && strtolower($mode) === "card"){$creditamount= $advance_cccharge;}


                    $data_detail=array(
                        'account_voucher_id' => $account_voucherid,
                        'account_head_id' => $credit[0],
                        'debit' => 0,
                        'credit' => round($creditamount,2),
                        'instrument_number' => $this->input->post('advance_inst')
                    );
                    //insert credit detail
                    if($creditamount>0){
                        $this->db->insert('account_voucher_detail', $data_detail);
                    }
                }
            }
            $visit_ids = $visit_ids."|".$visit_id;
        }
        if(SINGLE_PERIOD_BOOKING == FALSE){
            return "success".$visit_ids;
        }else{
            return "success|".$visit_id;
        }
        
    }
    

    public function create_dynamic_booking(){
//        exit();
//        $variables = [$this->input->post('customer_id'), $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        if($this->input->post('customer_id')==0){ return 0; exit();}
        
        // Unescape the string values in the JSON array
        $tableData = stripcslashes($this->input->post('tabledata', TRUE));
        
        // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
        //print_r($tableData);echo('<br>');
        // now $tableData can be accessed like a PHP array
//        echo '<pre>';
//         print_r($tableData);
//        exit();
        $visit_ids='';
        $data = [];
        //process the table data
        foreach($tableData as $row){
            
            //add new customer_visit
            $visit = array(
                'business_id' => $this->session->userdata('businessid'),
                'customer_id' => $this->input->post('customer_id'),
                'customer_visit_date' => date('Y-m-d H:i:s'),
                'visit_color' => $this->input->post('visit_color'),
                'visit_color_type' => $this->input->post('visit_color_type'),
                'discount' => $this->input->post('discount'),
                'advance' => $this->input->post('advance'),
                'advance_amount' => $row['advance'],
                'advance_mode' => $row['payment_mode'],
                'advance_inst' => $this->input->post('advance_inst'),
                'advance_date' => date('Y-m-d H:i:s'),
                'advance_comment' => $this->input->post('visit_remarks'),
                'customer_visit_date'=>date('Y-m-d H:i:s'),
                'created_by'=>$this->session->userdata('username'),
                'referring_staff'=>$this->input->post('referring_staff')
            );
            $this->db->insert('customer_visits', $visit);
            $visit_id = $this->db->insert_id();
            ////add new customer_visit end
            
            
            $id_package_type=$this->input->post('package_type_id');
            
            $this->db->select('*');
            $this->db->join('business_services', 'business_services.id_business_services=package_services.service_id');
            $this->db->where('package_category_id', $row['category_id']);
            $this->db->where('package_services_active', "Yes");
            $this->db->where('package_option_number', 0);
            $this->db->where('business_id', $this->session->userdata('businessid'));
            $visit_services=$this->db->get('package_services');            
            
            
            $service_flag="packagetype";
            $start = date('Y-m-d\TH:i:s', strtotime($row['day'].' '.$row['hour']));
            
            $i = 0; $lastduration=0; $newtime='';
            foreach($visit_services->result() as $vs){
                
                //get service start time
                if($i>0){ 
                    
                    $durCal =  explode(':',$lastduration);
                    $HoursInMin=0;
                    if(intval($durCal[0]) > 0){$HoursInMin = intval($durCal[0])*60;}
                    $newduration = $HoursInMin + $durCal[1]; 
                    $newduration = date_interval_create_from_date_string($newduration.' minutes');
                    $newstart=date_create($newtime);
                    $newtime=date_add($newstart, $newduration);
                    $newtime=date_format($newtime,"c");
                    $d=  explode('+', (string)$newtime);
                    $newtime=$d[0];
                    $lastduration=$vs->service_duration;
                } else {
                   $newtime=$start;
                   $lastduration=$vs->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];
                //
                
               //print_r($newtime);echo('<br>');
               // service start time in $newtime
               
                
                $serviceid=$vs->service_id;
                $servicename=$vs->service_name;
                $serviceqty=1;
                
                //echo $vs->package_service_optional;
                if($vs->package_service_optional=='Yes' ){
                    $passedservices= explode("|", $row['services']);
                    //var_dump($passedservices);
                    //echo '<br>'.sizeof($passedservices).'<br>';
                    if(sizeof($passedservices)>1){
                        $passedreplace = $passedservices[0];
                        $passedreplacewith = $passedservices[1];
                        //echo $vs->service_id;
                        if($vs->service_id == $passedreplace){
                            
                            $this->db->select('*');
                            $this->db->where('id_business_services', $passedreplacewith);
                            $q = $this->db->get('business_services');
                            $replace = $q->row();
                            
                            $serviceid=$replace->id_business_services;
                            $servicename=$replace->service_name;
                            $serviceqty=$passedservices[2];
                          //  echo $serviceid;
                          //  echo $servicename;
                        }
                    }
                    //$serviceid=
                }
                $optional='';
                for($x=1; $x<=$serviceqty; $x++){
                    if($x>1){$optional = '(nc)';}
                    $data = array(
                         'business_id' => $this->session->userdata('businessid'),
                         'customer_visit_id' => $visit_id,
                         //'service_id' => $vs->service_id,
                         'service_id' => $serviceid,
                         //'service_name' => $vs->service_name,
                         'service_name' => rtrim($servicename.' '.$optional),
                         'service_flag' => $service_flag,
                         'id_service_category' => $vs->package_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();

                     //check shared staff
                     $block_other='No';

                     $this->db->select('staff_shared');
                     $this->db->where('id_staff=',$row['staffid']);
                     $query = $this->db->get('staff');
                     $blockstaff = $query->row();

                     if (isset($blockstaff))
                     { $block_other =  $blockstaff->staff_shared; }


                     //insert service staff 
                     $staff = array(
                         'business_id' => $this->session->userdata('businessid'),
                         'customer_visit_id' => $visit_id,
                         'visit_service_id' => $id_visit_services,
                         'staff_id' => $row['staffid'],
                         'staff_name' => $row['staffname'],
                         'block_other'=>$block_other
                     );
                    $this->db->insert('visit_service_staffs', $staff);

                    //insert service products

                     $this->db->select('*');
                     $this->db->join('business_products', 'business_products.id_business_products = services_products.business_product_id');
                     $this->db->where('business_service_id', $vs->service_id);
                     $this->db->where('business_id', $this->session->userdata('businessid'));
                     $service_products=$this->db->get('services_products');

                     foreach($service_products->result() as $sp){
                         $products = array(
                             'business_id' => $this->session->userdata('businessid'),
                             'customer_visit_id' => $visit_id,
                             'visit_service_id' => $vs->service_id,
                             'product_id' => $sp->business_product_id,
                             'product_name' => $sp->product,
                             'product_qty' => $sp->usage_qty,
                             'product_unit' => $sp->measure_unit
                          );
                          $this->db->insert('visit_service_products', $products);
                        // print_r($products);echo('<br>');
                     }
                     $i++;
                 }
            }
            ///add advance
            $visit_adv_mode = $row['payment_mode']=='bank' ? 'check' : $row['payment_mode'];
            $advance_date = date('Y-m-d H:i:s', strtotime($row['advance_date']));
            $adv=array(
                'customer_visit_id' => $visit_id,
                'advance_amount' => $row['advance'],
                'advance_mode' => $visit_adv_mode,
                'advance_inst' => $this->input->post('advance_inst'),
                'advance_date' => $advance_date,
                'advance_user' => $this->session->userdata('username'),
                'advance_cc_charge' => $row['cccharge']
            );
            $this->db->insert('visit_advance', $adv);

           $advance_id = $this->db->insert_id();
            $mode = $row['payment_mode'];
            $amount = $row['advance'];
            $advance_cccharge= NULL !== $row['cccharge'] ? $row['cccharge'] : 0;
            $inst=$this->input->post('advance_inst');

        
            ///create auto account voucher
            if($this->session->userdata('auto_voucher')=='Yes'){

                //get customer details
                $this->db->select("customer_name, id_customers");
                $this->db->join("customers", "customers.id_customers = customer_visits.customer_id");
                $this->db->where("id_customer_visits", $visit_id);
                $query= $this->db->get("customer_visits");

                $customer = $query->row();

                $debit_accounts=[];
                $credit_accounts=[];

                $account_heads = $this->accounting_model->get_mapped_accounts(2);
                //var_dump ($account_heads); exit();
                foreach($account_heads as $ah){
                    if($ah['transaction_type']=='debit'){
                       array_push($debit_accounts,$ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                    } else {
                        array_push($credit_accounts, $ah['account_head_id']."|".$ah['transaction_type']."|".$ah['entity_name']);
                    }
                }

                $bank_name='';
                //if(null!==$this->input->post('bank_accounts')){$bank_name=$this->input->post('bank_accounts');}
                $data = array( 
                    'business_id' => $this->session->userdata('businessid'),
                    'description' => 'Advance Received against Visit ID: ' . $visit_id . ' on '. date('d-m-Y').', from '.$customer->customer_name.' customer ID : '. $customer->id_customers,
                    'voucher_date' => date('Y-m-d H:i:s'),
                    'voucher_amount' => $amount+$advance_cccharge,
                    'voucher_status' => 'Active',
                    'created_by' => $this->session->userdata('username'),
                    'cost_center'=> '1',
                    'cost_center_name'=> 'Front Desk',
                    'business_partner'=> 1,
                    'business_partner_id'=>$customer->id_customers,
                    'business_partner_name'=>$customer->customer_name,
                    'voucher_type'=>2,
                    'payment_mode'=>$mode,
                    'bank_name'=>$bank_name,
                    'visit_id'=>$visit_id,
                    'visit_advance_id'=>$advance_id,
                    'auto_voucher'=>'Yes',
                    'sale_type'=>'service',

                );

                $this->db->insert('account_vouchers', $data);
                $account_voucherid =  $this->db->insert_id();

                //enter debit entries
                foreach($debit_accounts as $debit_account){
                    $debitamount=0;
                    $debit = explode("|", $debit_account);
                    //check entity
                    if($debit[2]=="paid_cash" && strtolower($mode) == "cash"){$debitamount= $amount;}
                    if($debit[2]=="paid_card" && strtolower($mode) == "card"){$debitamount= $amount+$advance_cccharge;}
                    if($debit[2]=="paid_check" && strtolower($mode) == "bank"){$debitamount= $amount;}
                    if($debit[2]=="paid_voucher" && strtolower($mode) == "voucher"){$debitamount= $amount;}

                    $data_detail=array(
                        'account_voucher_id' => $account_voucherid,
                        'account_head_id' => $debit[0],
                        'debit' => round($debitamount,2),
                        'credit' => 0,
                        'instrument_number' => $this->input->post('advance_inst')
                    );
                    //insert debit detail
                    if($debitamount>0){
                        $this->db->insert('account_voucher_detail', $data_detail);
                    }
                }
                //enter credit entries
                foreach($credit_accounts as $credit_account){
                    $creditamount=0;
                    $credit = explode("|", $credit_account);
                    //check entity

                    if($credit[2]=="advance_amount"){$creditamount= $amount;}
                    if($credit[2]=="cc_fee" && $advance_cccharge>0 && strtolower($mode) === "card"){$creditamount= $advance_cccharge;}


                    $data_detail=array(
                        'account_voucher_id' => $account_voucherid,
                        'account_head_id' => $credit[0],
                        'debit' => 0,
                        'credit' => round($creditamount,2),
                        'instrument_number' => $this->input->post('advance_inst')
                    );
                    //insert credit detail
                    if($creditamount>0){
                        $this->db->insert('account_voucher_detail', $data_detail);
                    }
                }
            }
            $visit_ids = $visit_ids."|".$visit_id;
        }
        
        return "success".$visit_ids;
        
    }
    
    
    public function getpackagedays($visitid){
//        $variables = [$visitid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select("id_service_category, service_category, date_format(visit_service_start, '%W, %D %M %Y %h:%i %p') as visit_date");
        $this->db->join("package_category pc", "pc.id_package_category = visit_services.id_service_category");
        $this->db->where("customer_visit_id=",$visitid);
        $this->db->where("visit_service_status","Active");
        $this->db->group_by("id_service_category, service_category");
        $query = $this->db->get('visit_services');
       
        return $query->result_array();

    }
    
    function reminder_message_update(){
        
        
        $data = array(
            'reminder_sms' => $this->input->post('reminder_sms'),
            'reminder_email' => $this->input->post('reminder_email'),
            'reminder_call' => $this->input->post('reminder_call')
        );

        if(null != $this->input->post('discount')){
            $data = array_merge($data, array('discount'=>$this->input->post('discount')));
        }

        //print_r($data);exit;
        $this->db->where('id_customer_visits', $this->input->post('customer_visit_id'));
        $this->db->update('customer_visits', $data);
        return $this->db->affected_rows();
    }
    
    function mark_inservice($visitid){
        $today = date('Y-m-d H:i:s');
        
        $data = array(
            'inservice' => 'Yes',
            'inservice_time' => $today
        );
        $this->db->where('id_customer_visits', $visitid);
        $this->db->update('customer_visits', $data);
        
        
        $data1 = array(
            'update_date' => $today
        );
        $this->db->where('customer_visit_id', $visitid);
        $this->db->update('visit_services', $data1);
        
        return $today;
        
    }
    
    function add_visit_remarks($visitid, $visitremarks){
        
        $data = array(
            'advance_comment' =>   $visitremarks          
        );
        $this->db->where('id_customer_visits', $visitid);
        $this->db->update('customer_visits', $data);
        return $this->db->affected_rows();
    }
    
    function add_visit_discount($visitid, $visitdiscount, $discountreason){
        
        $data = array(
            'discount' =>   $visitdiscount,
            'discount_reason' => $discountreason
        );
        $this->db->where('id_customer_visits', $visitid);
        $this->db->update('customer_visits', $data);
        return $this->db->affected_rows();
    }
    
    function getvisitserviceids($visitid){
        $variables = [$visitid, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('id_visit_services');        
        $this->db->where('customer_visit_id', $visitid);
        $this->db->where('visit_service_status','Active');
        $query = $this->db->get('visit_services');
        return $query->result_array();
        
    }
    
    function getvisitdiscount($visitid){
//        $variables = [$visitid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('id_customer_visits, ifnull(discount,0) as discount',false);        
        $this->db->where('id_customer_visits', $visitid);
        $query = $this->db->get('customer_visits');
        return $query->row();
        
        
    }
    
     function checkvariables($variables){
        
        $result=true;
        foreach($variables as $var){
        if(null == $var || $var == ''){
                $result=false;
            }
        }
        return $result;
    }
    
    function get_visit_service_count($service_id, $date){
        
         $sql = "SELECT id_business_services, business_services.service_name, '" .$date. "' as mdate,   
                ifnull(count(visit_services.id_visit_services),0) as totalcount,
                business_services.max_per_day,
                Case when business_services.max_per_day - ifnull(count(visit_services.id_visit_services),0) <=0 then 'Over Booked'
                when business_services.max_per_day - ifnull(count(visit_services.id_visit_services),0) = 0 then 'Booked'
                when business_services.max_per_day - ifnull(count(visit_services.id_visit_services),0) >= 0 then 'Available'
                End as service_status
                FROM business_services
               
                left join visit_services on visit_services.service_id = business_services.id_business_services 
                and visit_service_status='Active' 
                and date(visit_services.visit_service_start) = '".$date."'
                where business_services.id_business_services=".$service_id."
                group by id_business_services";
        
        $query =$this->db->query($sql);
        return $query->result_array();
    }
    
    
   function add_visit_with_receivable($customer_id, $customer_name, $staff_id, $service_id, $visit_date, $start, $end, $program_enrolled_service_id, $group_id=0, $group_visit_id=0){
       
       //insert visit
       $data = array(
           'business_id' => $this->session->userdata('businessid'),
           'visit_color' => '#512E5F',
           'customer_id' => $customer_id,
           'customer_visit_date' => $visit_date.' '.$start,
           'visit_status' => 'open',
           'visit_color_type' => 'Dark',
           'created_by' => $this->session->userdata('username'),
           'program_enrolled_service_id'=> $program_enrolled_service_id,
           'group_id'=>$group_id,
           'group_visit_id'=>$group_visit_id
         );
         
              
       $this->db->insert('customer_visits', $data);
       $visit_id = $this->db->insert_id();
       
       
       //insert visit service
       $this->db->select('id_business_services, id_service_category, id_service_types, service_name, service_category, service_type, service_rate');
       $this->db->join('service_category', 'service_category.id_service_category = business_services.service_category_id');
       $this->db->join('service_type', 'service_type.id_service_types = service_category.service_type_id');
       $this->db->where('id_business_services', $service_id);
       $query = $this->db->get('business_services');
       //echo $query; exit();
       $service_data=$query->row();
       
       
       $data = array(
           'business_id' => $this->session->userdata('businessid'),
           'customer_visit_id' => $visit_id,
           'service_id' => $service_id,
           'service_name' => $service_data->service_name,
           'visit_service_start' => $visit_date.'T'.$start,
           'visit_service_end' => $visit_date.'T'.$end,
           'update_date' => date('Y-m-d H:m:s'),
           'service_flag' => 'servicetype',
           'id_service_category' => $service_data->id_service_category           
         );   
       $this->db->insert('visit_services', $data);
       $visit_service_id = $this->db->insert_id();
       
       //insert visit staff
       $this->db->select('id_staff, staff_fullname');
       $this->db->where('id_staff', $staff_id);
       $query = $this->db->get('staff');
       //echo $query; exit();
       $staff_data=$query->row();
       
       
       $data = array(
           'business_id' => $this->session->userdata('businessid'),
           'customer_visit_id' => $visit_id,
           'visit_service_id' => $visit_service_id,
           'staff_id' => $staff_id,
           'staff_name' =>   $staff_data->staff_fullname      
         );   
       $this->db->insert('visit_service_staffs', $data);
       $visit_staff_id = $this->db->insert_id();
       
       return $visit_id; 
       
   }
    
   function check_staff_availability($staff_id, $start_time, $end_time, $visit_date){
       $sql = "SELECT '$start_time' testtime, visit_service_start, TIME( date_format(visit_services.visit_service_start, '%Y-%m-%d %H:%i')) startTime,
                TIME( date_format(visit_services.visit_service_end, '%Y-%m-%d %H:%i')) endtime,
               case 
               when TIME(date_format(visit_services.visit_service_start, '%Y-%m-%d %H:%i')) <= '$start_time' then 'no'
               else 'yes'
               end pass1,
               case 
               when TIME(date_format(visit_services.visit_service_end, '%Y-%m-%d %H:%i')) >= '$start_time' then 'no'
               else 'yes'
               end pass2
               FROM `visit_services`
               join visit_service_staffs on visit_service_staffs.visit_service_id=visit_services.id_visit_services
               join customer_visits on visit_services.customer_visit_id = customer_visits.id_customer_visits 
               where customer_visits.visit_status in ('open','invoiced') 
               and date(visit_service_start)='$visit_date' and staff_id='".$staff_id."'
               order by id_visit_services desc;";
       
       $query= $this->db->query($sql);
       
      // echo $sql; exit();
       $result = "passed";
       foreach($query->result() as $row){
           if($row->pass1=='no' && $row->pass2=='no'){$result='failed';}
       }
       return ($result);
   }
   
    function check_workstation_availability($staff_id, $start_time, $end_time, $visit_date){
        
        $this->db->select('floor_id, floor');
        $this->db->where('id_staff', $staff_id);
        $query = $this->db->get('staff');
        $staff=$query->row();
        
        $this->db->select('id_business_floors, floor_workstations');
        $this->db->where('id_business_floors', $staff->floor_id);
        $query = $this->db->get('business_floors');
        $floor=$query->row();
        $result='passed';
        
        if(null != $floor && empty($floor)==false){
            $sql = "SELECT id_customer_visits, floor_id, '".$start_time."' testtime, visit_service_start, 
                    TIME( date_format(visit_services.visit_service_start, '%Y-%m-%d %H:%i')) startTime,
                    TIME( date_format(visit_services.visit_service_end, '%Y-%m-%d %H:%i')) endtime,
                    case 
                        when TIME(date_format(visit_services.visit_service_start, '%Y-%m-%d %H:%i')) <= '".$start_time."' then 'no'
                    else 'yes'
                        end pass1,
                   case 
                   when TIME(date_format(visit_services.visit_service_end, '%Y-%m-%d %H:%i')) > '".$start_time."' then 'no'
                   else 'yes'
                   end pass2
                   FROM `visit_services`
                   join visit_service_staffs on visit_service_staffs.visit_service_id=visit_services.id_visit_services
                   join customer_visits on visit_services.customer_visit_id = customer_visits.id_customer_visits 
                    JOIN    staff on id_staff = visit_service_staffs.staff_id    
                   where customer_visits.visit_status in ('open','invoiced') 
                    AND DATE(visit_services.visit_service_start) = '$visit_date'
                    AND TIME(visit_services.visit_service_start) <= '".$start_time."'
                    AND TIME(visit_services.visit_service_end) >= '".$start_time."'
                    AND staff.floor_id = $floor->id_business_floors
                    order by id_visit_services desc;";

            $query = $this->db->query($sql);

            $total_visits = $query->num_rows();

            if($floor->floor_workstations > $total_visits){            
                $result = 'passed';            
            }else {            
                $result='failed';            
            }
        }else{
            $result='passed';
        }
       
        return $result;
   }
       
   
   
}
