<?php

class Scheduler_model extends CI_Model {

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

    function day_visit_list($today=null) {

        if($today==null){
            $today = date('Y-m-d');
        }
         $today = date_format(date_create($today), '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 ,
                visit_status, visit_color, visit_color_type, program_enrolled_service_id
                FROM customer_visits 
                JOIN 
                (
                select min(visit_service_start) as visit_service_start, customer_visit_id from visit_services 
                where date(visit_service_start)='".$today."' and visit_service_status='Active' 
                group by customer_visit_id
                ORDER BY cast(visit_service_start as DATETIME) Asc
                ) as
                visit_services ON visit_services.customer_visit_id = customer_visits.id_customer_visits 
                
                JOIN customers ON customers.id_customers = customer_visits.customer_id 
                WHERE customer_visits.business_id = '".$this->session->userdata('businessid')."'
                and date(visit_service_start) = '".$today."'
                    ORDER BY cast(visit_service_start as DATETIME) Asc
                ";
       //echo $sql; exit();
        
      
        $query=$this->db->query($sql);
        
        return $query->result_array();
    }
    
    function getSingleVisit($visitid){
        
        $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 ,
                visit_status, reminder_call, reminder_sms, reminder_email, reminder_stricttime, 
                advance_comment, visit_color, visit_color_type, program_enrolled_service_id, 
                visit_service_start, visit_service_end, customer_visits.discount, 
                ifnull(customer_visits.discount_reason,'') as discount_reason, ifnull(visit_extra,'') visit_extra " ;

        if($this->session->userdata('hide_cell')=="Yes"){
            $sql.=" , 'N/A' as customer_cell ";
        }
        
        $sql.=" 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 customer_visits.id_customer_visits = '".$visitid."'                
                group by id_customer_visits
                ORDER BY date(visit_service_start), hour(visit_service_start), minute(visit_service_start) Asc";
       
        $query=$this->db->query($sql);
        
        return $query->row();
        
    }
    
    function getVisitStatus($id_visit_service){
        
        $this->db->select("customer_visits.visit_status");
        $this->db->join("visit_services", "visit_services.customer_visit_id = customer_visits.id_customer_visits");
        $this->db->where("visit_services.id_visit_services", $id_visit_service);       
        $query = $this->db->get("customer_visits");
        
        $visitstatus=$query->row();
        
        return $visitstatus->visit_status;
        
    }
    
    function get_blocking_events() {
        $variables = [$this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('block_events');
        return $query->result();
    }

    function update_block_event($id, $data) {
        $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'),
            'block_time_event_id' => $id
        );
        $this->db->where($where);
        $query = $this->db->update('block_staff_time', $data);
        return $query;
    }

    function get_staff_blocked_events($start, $end) {
        $variables = [$start, $end, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*');
        $this->db->join('block_events be', 'bst.block_event_id = be.id_block_events');
        $this->db->where('bst.business_id', $this->session->userdata('businessid'));
        $this->db->where('bst.start_time >', $start);
        $this->db->where('bst.end_time <', $end);
        $query = $this->db->get('block_staff_time bst');
        return $query->result();
    }

    function remove_staff_block_time($block_time_event_id) {
        $variables = [$block_time_event_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->where('block_time_event_id', $block_time_event_id);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->delete('block_staff_time');
        return $query;
    }

    function check_block_time($staff_id, $start) {
        $variables = [$staff_id, $start, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
       // $start = str_replace('T', ' ', $start);
        $this->db->select("*");
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('staff_id', $staff_id);
        $this->db->where('start_time  <=', $start);
        $this->db->where('end_time  >', $start);
        $query = $this->db->get('block_staff_time');
       // echo $query; exit();
        return $query->row();
    }

    function add_staff_block_time($data) {
        $this->db->insert('block_staff_time', $data);
        $insert_id = $this->db->insert_id();

        $this->db->where('id_staff_time_blocked', $insert_id);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->update('block_staff_time', array('block_time_event_id' => 'b' . $insert_id));

        return $insert_id;
    }

    function get_total_net_amount($staff_name, $calendar_date) {
        $variables = [$staff_name, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $today = $calendar_date;

        $datetime = new DateTime($today);
        $datetime->modify('+1 day');

        $tomorrow = $datetime->format('Y-m-d H:i:s');

        $this->db->select('SUM(ind.price) AS netAmount, SUM(in.balance) AS totalBalance, SUM(in.discount) AS totalDiscount');
        $this->db->join('invoice_details ind', 'in.id_invoice = ind.invoice_id');
        $this->db->where('in.business_id', $this->session->userdata('businessid'));
        $this->db->where('in.invoice_status', 'valid');
        $this->db->where('in.invoice_type', 'service');
        $this->db->where('ind.staff', $staff_name);
        //$this->db->where('ind.service_category', $service_category_name);
        $this->db->where('in.invoice_date >', $today);
        $this->db->where('in.invoice_date <', $tomorrow);

        //$this->db->group_by('ind.staff');
        //$this->db->group_by('ind.service_category');

        $query = $this->db->get('invoice in');

        return $query->row();
    }

    function get_net_amount($service_name, $staff_name, $calendar_date) {
        $variables = [$service_name, $staff_name, $calendar_date, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $today = $calendar_date;

        $datetime = new DateTime($today);
        $datetime->modify('+1 day');

        $tomorrow = $datetime->format('Y-m-d H:i:s');

        $this->db->select('SUM(ind.discounted_price) AS netAmount, SUM(ind.discount) AS discountSum');
        $this->db->join('invoice_details ind', 'inv.id_invoice = ind.invoice_id');
        $this->db->where('inv.business_id', $this->session->userdata('businessid'));
        $this->db->where('inv.invoice_status', 'valid');
        $this->db->where('inv.invoice_type', 'service');
        //$this->db->where('ind.staff', $staff_name);
        $this->db->where('ind.service_name', $service_name);
        $this->db->where('inv.invoice_date >', $today);
        $this->db->where('inv.invoice_date <', $tomorrow);
        $this->db->like('ind.staff', $staff_name);

        $query = $this->db->get('invoice inv');

        return $query->row();
    }

    function single_service_count($service_name, $staff_id, $calendar_date) {
        //$variables = [$service_name, $staff_id, $this->session->userdata('businessid')];
        //$fine = $this->checkvariables($variables);
        //if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $today = $calendar_date;

        $datetime = new DateTime($today);
        $datetime->modify('+1 day');

        $tomorrow = $datetime->format('Y-m-d H:i:s');

        $this->db->select('COUNT(id_staff_services) AS servicecount');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('service_name', $service_name);
        $this->db->where('staff_id', $staff_id);
        $this->db->where('staff_service_date >', $today);
        $this->db->where('staff_service_date <', $tomorrow);
        $this->db->where('visit_id !=', '');
        //$this->db->group_by('service_category');

        $query = $this->db->get('staff_services');

        return $query->row();
    }

    function provided_services_list($staff_id, $calendar_date) {
        $variables = [$staff_id, $calendar_date, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $today = $calendar_date;

        $datetime = new DateTime($today);
        $datetime->modify('+1 day');

        $tomorrow = $datetime->format('Y-m-d H:i:s');

        $this->db->select("*");
        $this->db->where('staff_id', $staff_id);
        $this->db->where('staff_service_date >', $today);
        $this->db->where('staff_service_date <', $tomorrow);
        $this->db->where('visit_id !=', '');
        $this->db->group_by('service_name');
        $query = $this->db->get('staff_services');

        return $query->result();
    }

    function total_products_sold($staff_name, $calendar_date) {
        $variables = [$staff_name, $calendar_date, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $today = $calendar_date;
        $datetime = new DateTime($today);
        $datetime->modify('+1 day');
        $tomorrow = $datetime->format('Y-m-d H:i:s');

        $this->db->select('SUM(invp.discounted_price) AS totalSale,count(invp.id_invoice_products) as retailcount');
        $this->db->join('invoice_products invp', 'inv.id_invoice = invp.invoice_id');
        $this->db->where('inv.business_id', $this->session->userdata('businessid'));
        $this->db->where('inv.invoice_status', 'valid');
        $this->db->where('inv.invoice_type', 'sale');
        $this->db->where('invp.staff_name', $staff_name);
        $this->db->where('inv.invoice_date >', $today);
        $this->db->where('inv.invoice_date <', $tomorrow);
        $this->db->group_by('invp.product_id');
        $query = $this->db->get('invoice inv');
        return $query->row();
    }

    function total_services_provided($staff_id, $calendar_date) {
        $variables = [$staff_id, $calendar_date, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $today = $calendar_date;

        $datetime = new DateTime($today);
        $datetime->modify('+1 day');

        $tomorrow = $datetime->format('Y-m-d H:i:s');

        $this->db->select('COUNT(id_invoice_staff) AS totalservices');
        $this->db->join('invoice', 'invoice.id_invoice = invoice_staff.invoice_id');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('staff_id', $staff_id);
        $this->db->where('invoice_date >', $today);
        $this->db->where('invoice_date <', $tomorrow);
        $this->db->where('invoice_status', 'valid');
        $this->db->where('sale_type', 'service');
        $this->db->group_by('invoice_staff.service_name');

        $query = $this->db->get('invoice_staff');

        return $query->row();
    }

//    function total_services_provided($staff_id){
//        
//        $where = array(
//            'vs.business_id' => $this->session->userdata('businessid'),
//            'cv.business_id' => $this->session->userdata('businessid'),
//            'cv.visit_status' => 'invoiced',
//            'vs.staff_ids' => $staff_id
//        );
//        
//        $this->db->select('vs.staff_names, COUNT(vs.staff_ids) as totalservices');
//        $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
//        $this->db->where($where);
//        $query = $this->db->get('visit_services vs');
//        
//        return $query->row();
//        
//    }

    function staff_details($staff_id) {
        $variables = [$staff_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('id_staff', $staff_id);
        $query = $this->db->get('staff');

        return $query->row();
    }

    function getvoucherbyid($voucher_id) {
        $variables = [$voucher_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*, date_format(voucher_date,"%d-%m-%Y") as formatted_voucher_date, date_format(valid_until,"%d-%m-%Y") as formatted_valid_until');
        $this->db->join('customers c', 'ov.customer_id = c.id_customers');
       // $this->db->where('ov.business_id', $this->session->userdata('businessid'));
        $this->db->where('ov.id_order_vouchers', $voucher_id);
        $query = $this->db->get('order_vouchers ov');

        return $query->row();
    }

    function getvoucherservices($ids) {
        $variables = [$ids, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*');
        $this->db->join('service_category sc', 'sc.id_service_category = bs.service_category_id');
        $this->db->where_in('bs.id_business_services', $ids);
        $this->db->where('bs.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('business_services bs');

        return $query->result();
    }

    function check_voucher_number($voucherno) {
        $variables = [$voucherno, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select("*");
        $this->db->where('voucher_number', $voucherno);
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('order_vouchers');
        return $query->num_rows();
    }

    function insert_voucher() {
        //exit();
        $variables = [$this->input->post('customer_id', TRUE), $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        
        $customer_id = htmlspecialchars($this->input->post('customer_id', TRUE));
        $customer_name = htmlspecialchars($this->input->post('customer_name', TRUE));
        
        $type = htmlspecialchars($this->input->post('type', TRUE));
        $price = htmlspecialchars($this->input->post('price', TRUE));
        $valid_until = htmlspecialchars($this->input->post('valid_until', TRUE));
        $voucher_number = htmlspecialchars($this->input->post('voucher_number_option', TRUE));
        $service_ids = htmlspecialchars($this->input->post('service_ids', TRUE));
        $service_names = htmlspecialchars($this->input->post('service_names', TRUE));
        $payment_mode = htmlspecialchars($this->input->post('payment_mode', TRUE));
        $instrument_number = $payment_mode=="Online" ? 'Online '.htmlspecialchars($this->input->post('instrument_number', TRUE))  : htmlspecialchars($this->input->post('instrument_number', TRUE));
        $voucher_date = date('Y-m-d H:i:s');
        $voucher_heading=htmlspecialchars($this->input->post('voucher_heading', TRUE));
        $voucher_tax = null == $this->input->post('voucher_tax') ? 0 :  htmlspecialchars($this->input->post('voucher_tax', TRUE));
        $voucher_cccharge = null == $this->input->post('voucher_cccharge') ? 0 : htmlspecialchars($this->input->post('voucher_cccharge', TRUE));
        
        $paid_cash=0; $paid_card=0; $paid_check=0;
        
        if($payment_mode=="Cash"){
            $paid_cash=$price;
        } else if($payment_mode=="Card"){
            $paid_card=$price;
        } else if($payment_mode=="Check"){
            $paid_check=$price;
        } else if($payment_mode=="Online"){
            $paid_check=$price;
            $payment_mode="Check";
        }
        
        

        $data = array(
            'business_id' => $this->session->userdata('businessid'),
            'customer_id' => $customer_id,
            'voucher_number' => 'C'.$voucher_number,
            'type' => $type,
            'amount' => $price+$voucher_tax,
            'remaining_amount' => $price+$voucher_tax,
            'service_ids' => $service_ids,
            'service_names' => $service_names,
            'remaining_service_ids' => $service_ids,
            'voucher_date' => $voucher_date,
            'valid_until' => $valid_until . ' 23:59:59',
            'payment_mode' => $payment_mode,
            'instrument_number' => $instrument_number,
            'voucher_heading' => $voucher_heading,
            'paid_cash' => $payment_mode=='Cash' ? $paid_cash+$voucher_tax : $paid_cash,
            'paid_card' => $payment_mode=='Card' ?  $paid_card+$voucher_tax+$voucher_cccharge : $paid_card,
            'paid_check' => $payment_mode=='Check' ? $paid_check+$voucher_tax : $paid_check,
            'created_by' => $this->session->userdata('username'),
            'voucher_tax' => $voucher_tax,
            'voucher_cccharge' => $voucher_cccharge,
            'voucher_value'=>$price
        );

        $this->db->insert('order_vouchers', $data);
        
        $voucher_id = $this->db->insert_id();
        
        if (empty($voucher_number)) {
           $this->db->set('voucher_number','C'.$voucher_id);
           $this->db->where('id_order_vouchers',$voucher_id);
           $this->db->update('order_vouchers');
            
           $voucher_number='C'.$voucher_id;
        }
        
        //create auto account voucher       
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(9);
            //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' => 'Gift Voucher Sold with Number ' . $voucher_id . ' on '. date('d-m-Y').', for '.$customer_name.' customer ID : '. $customer_id,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $price+$voucher_tax,
                '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,
                'business_partner_name'=>$customer_name,
                'voucher_type'=>2,
                'payment_mode'=>$payment_mode,
                'bank_name'=>$bank_name,
                
                'auto_voucher'=>'Yes',
                'sale_type'=>'service',
                'order_voucher_id'=>$voucher_id
            );

            $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" && $paid_cash > 0){$debitamount= $paid_cash+$voucher_tax;}
                if($debit[2]=="paid_card" && $paid_card > 0){$debitamount= $paid_card+$voucher_tax;}
                if($debit[2]=="paid_check" && $paid_check > 0){$debitamount= $paid_check+$voucher_tax;}
               //if($debit[2]=="balance"){$debitamount= $balance;}
               // if($debit[2]=="sale_discount"){$debitamount= $totalservicediscount + $discount;}
               // if($debit[2]=="retained_amount_used"){$debitamount= $retained_amount_used;}
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'debit' => round($debitamount,2),
                    'credit' => 0
                );
                //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]=="voucher_amount"){$creditamount= $price + $voucher_tax;}
                
               // if($credit[2]=="sales_tax"){$creditamount= $voucher_tax;}
               // if($credit[2]=="cc_fee"){$creditamount= $cc_charge;}
               // if($credit[2]=="retained_amount"){$creditamount= $customer_advance==='true' ? $returnamount: 0;}
               // if($credit[2]=="cc_tip"){$creditamount= $cctip;}
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
        }
        
        return $voucher_id . '|' . $voucher_number;
    }


    
    
    
    function get_all_staff() {
        $variables = [$this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        
        if($this->session->userdata('common_products')=='Yes'){
            $where = "(staff.business_id=". $this->session->userdata('businessid') ." OR staff.staff_shared = 'Yes') ";
        }else{
            $where="staff.business_id = ".$this->session->userdata('businessid');
        }
        
        $this->db->select('*');
        $this->db->where($where);
        $this->db->order_by('id_staff', 'ASC');
        $query = $this->db->get('staff');

        return $query->result();
    }

    function get_color_numbers_by_type_id($type_id) {
        $variables = [$type_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('type_id', $type_id);
        $this->db->where('status', 'Yes');
        $this->db->order_by('id', 'ASC');
        $query = $this->db->get('color_number');

        return $query->result();
    }

    function getcolortypes() {
        $variables = [ $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'),
            'status' => 'Yes'
        );

        $this->db->select('*');
        $this->db->where($where);
        $query = $this->db->get('color_types');

        return $query->result();
    }

    function getopenorderbyid($orderid, $orderstatus = null) {
        $variables = [$orderid, $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_orders.customer_id');
        $this->db->join('order_products', 'order_products.customer_order_id = customer_orders.id_customer_order', 'left');
        $this->db->join('business_products', 'business_products.id_business_products = order_products.product_id');
        $this->db->join('business_brands', 'business_brands.id_business_brands = business_products.brand_id');
        $this->db->where('id_customer_order =', $orderid);
        if($orderstatus==0){
            $this->db->where('order_status !=', 'invoiced');
        }
        $this->db->where('customer_orders.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customer_orders');
        return $query->result_array();
    }

    function getorderbyid($orderid, $orderstatus = null) {
        $variables = [$orderid, $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_orders.customer_id');
        $this->db->join('order_products', 'order_products.customer_order_id = customer_orders.id_customer_order');
        $this->db->join('business_products', 'business_products.id_business_products = order_products.product_id');
        $this->db->join('business_brands', 'business_brands.id_business_brands = business_products.brand_id');        
        $this->db->where('customer_orders.id_customer_order =', $orderid);
        $this->db->where('customer_orders.business_id', $this->session->userdata('businessid'));
        $query = $this->db->get('customer_orders');
       // echo $query;
        return $query->result_array();
    }

    function getorderpayment($orderid){

        $account_id = 5;
        $sql = "select account_head_id from account_event_mapping where account_event_id = 1 and entity_name = 'balance' and business_id = ".$this->session->userdata('businessid');
        $query = $this->db->query($sql);
        $account_id = $query->row()->account_head_id;

        $mysql = "SELECT invoices.visit_id, sum(debit)-sum(credit) as balance
                    FROM account_vouchers 
                    JOIN account_voucher_detail on account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
                    JOIN (
                        SELECT id_invoice, visit_id FROM invoice
                        WHERE invoice.visit_id = ".$orderid."
                        AND invoice_type = 'sale') AS invoices 
                        ON invoices.id_invoice = account_vouchers.invoice_id AND account_vouchers.sale_type = 'sale'
                    WHERE account_voucher_detail.account_head_id = ".$account_id."
                    GROUP BY invoices.visit_id";

        $query = $this->db->query($mysql);
        return $query->result_array();            

    }

    function getVisitId($service_id) {
        $variables = [$service_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'),
            'id_visit_services' => $service_id,
        );

        $this->db->select('*');
        $this->db->where($where);
        $query = $this->db->get('visit_services');

        return $query->row();
    }

    function cancelVisit($customer_visit_id, $cancelreason='') {
        $variables = [$customer_visit_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $canceledby=$this->session->userdata('username');
        if($cancelreason==''){            
            $cancelreason=$this->input->post('cancelreason');            
        }
        $where = array(
            'business_id' => $this->session->userdata('businessid'),
            'id_customer_visits' => $customer_visit_id,
        );

        $this->db->where($where);
        $query = $this->db->update('customer_visits', array('visit_status' => 'canceled', 'cancelreason' => $cancelreason, 'canceled_by' => $this->session->userdata('username')));

        ///get all advance against visit and cancel vouchers
        $this->db->select("id_visit_advance");
        $this->db->where("customer_visit_id", $customer_visit_id);
        $advances = $this->db->get("visit_advance");
        foreach ($advances->result() as $advance){
            //change account voucher status
            $this->db->where('visit_advance_id', $advance->id_visit_advance);
            $this->db->update('account_vouchers', array('voucher_status' => 'cancelled', 'cancelled_by' => $this->session->userdata('username'), 'cancelled_on' => date('Y-m-d H:i:s')));
        }
                
        
        return $query;
    }
    
    function cancelVisitKeepAdv($customer_visit_id, $cancelreason='') {
        $variables = [$customer_visit_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $canceledby=$this->session->userdata('username');
        if($cancelreason==''){            
            $cancelreason=$this->input->post('cancelreason');            
        }
        $where = array(
            'business_id' => $this->session->userdata('businessid'),
            'id_customer_visits' => $customer_visit_id,
        );

        $this->db->where($where);
        $query = $this->db->update('customer_visits', array('visit_status' => 'AdvKeptcanceled', 'cancelreason' => $cancelreason, 'canceled_by' => $this->session->userdata('username')));

        return $query;
    }

    
    function cancelVisitRetainAdv($customer_visit_id, $cancelreason='', $event_id=28) {
        $variables = [$customer_visit_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
       // echo $event_id;exit();
        $canceledby=$this->session->userdata('username');
        if($cancelreason==''){            
            $cancelreason=$this->input->post('cancelreason');            
        }
        $where = array(
            'business_id' => $this->session->userdata('businessid'),
            'id_customer_visits' => $customer_visit_id,
        );

        if($event_id==27){
            $selectedoption='cancelledAdvReturned';
        } else if($event_id==28 || $event_id==29){
            $selectedoption='AdvKeptcanceled';
        }
        
        $this->db->where($where);
        $query = $this->db->update('customer_visits', array('visit_status' => $selectedoption, 'cancelreason' => $cancelreason, 'canceled_by' => $this->session->userdata('username')));

        
        
        //create auto account voucher       
        if($this->session->userdata('auto_voucher')=='Yes'){
            
            $customer_name='';
            $customer_id=0;
        
            //get advance collected account for event 28

            $advance_accounts  = $this->accounting_model->get_event_account($event_id, 'advance_amount');
            $advance_account = $advance_accounts->account_head_id;
            $advance_amount = 0;

            //get total advance collected against the visit
            $this->db->select("visit_id, business_partner_id, business_partner_name, sum(credit)-sum(debit) as 'advance_amount'");
            $this->db->join("account_voucher_detail as avd", "avd.account_voucher_id = account_vouchers.id_account_vouchers");
            $this->db->where("visit_id", $customer_visit_id);
            $this->db->where("account_head_id", $advance_account);
            $this->db->where("voucher_status","Active");
            $this->db->where("business_id", $this->session->userdata('businessid'));
            $this->db->group_by('visit_id');        
            $advances = $this->db->get("account_vouchers");
            //echo sizeof($advances->result()); exit();
            if(sizeof($advances->result())>=1){
            
                foreach ($advances->result() as $advance){
                    $customer_name=$advance->business_partner_name;            
                    $customer_id=$advance->business_partner_id;
                    $advance_amount=$advance->advance_amount;
                }
            } else {
                $this->db->select("customer_visit_id, id_customers, customer_name, sum(visit_advance.advance_amount) as advance_amount");
                $this->db->join("customer_visits","id_customer_visits = customer_visit_id");
                $this->db->join("customers","id_customers = customer_id");
                $this->db->where("customer_visit_id", $customer_visit_id);
                
                $this->db->group_by('customer_visit_id');        
                $advances = $this->db->get("visit_advance");
                //print_r($advances->result()); exit();
                 foreach ($advances->result() as $advance){
                    $customer_name=$advance->customer_name;            
                    $customer_id=$advance->id_customers;
                    $advance_amount=$advance->advance_amount;
                }
            }
            
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts($event_id);
            //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');}
            
            $description = 'Advance Retained in Customer Account on Visit Cancellation for Visit ID ' . $customer_visit_id . ' on '. date('d-m-Y').', for '.$customer_name.' customer ID : '. $customer_id;
            $voucher_type=3;
            if($event_id==27){
                $description ='Advance Returned to Customer on Visit Cancellation for Visit ID ' . $customer_visit_id . ' on '. date('d-m-Y').', for '.$customer_name.' customer ID : '. $customer_id;
                $voucher_type=1;
            } else if($event_id==29){
                $description ='Advance Kept as Sale on Visit Cancellation for Visit ID ' . $customer_visit_id . ' on '. date('d-m-Y').', for '.$customer_name.' customer ID : '. $customer_id;
                $voucher_type=2;
            }
            
            $data = array( 
                'business_id' => $this->session->userdata('businessid'),
                'description' => $description,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $advance_amount,
                '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,
                'business_partner_name'=>$customer_name,
                'voucher_type'=> $voucher_type,
                'payment_mode'=>'Cash',
                'bank_name'=>$bank_name,                
                'auto_voucher'=>'Yes',
                'sale_type'=>'service',
                'visit_id'=>$customer_visit_id
            );

            $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]=="advance_amount"){$debitamount= $advance_amount;}
                
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'debit' => round($debitamount,2),
                    'credit' => 0
                );
                //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]=="retained_amount"){$creditamount= $advance_amount;}
                if($credit[2]=="cash"){$creditamount= $advance_amount;}
                if($credit[2]=="sale_amount"){
                    
                    $taxperc = $this->business_model->get_tax_perc('service','All');
                    $tax_perc = $taxperc->tax_percentage;
                    $taxamount= ($advance_amount*$tax_perc)/100;
                    
                    $creditamount= $advance_amount-$taxamount;
                    
                    
                }
                if($credit[2]=="sales_tax"){
                    
                    
                    $taxperc = $this->business_model->get_tax_perc('service','All');
                    $tax_perc = $taxperc->tax_percentage;
                    $creditamount= ($advance_amount*$tax_perc)/100;
                    
                }
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'debit' => 0,
                    'credit' => round($creditamount,2)
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
        }
        
        
        
        return $query;
    }
    
    
    
    function allVisitServices($customer_visit_id) {
        $variables = [$customer_visit_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' => $customer_visit_id,
            'visit_service_status' => 'Active'
        );

        $this->db->select('*');
        $this->db->where($where);
        $query = $this->db->get('visit_services');

        return $query->result();
    }

    function removeVisitService($id) {
        $variables = [$id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->where('id_visit_services', $id);
        $query = $this->db->update('visit_services', array('visit_service_status'=>'Cancelled'));
        //$query = $this->db->delete('visit_services');
        return $query;
    }

    function updateVisit($id, $old_staff_id, $staffData, $serviceData, $visitid, $idvisitservicestaff=null) {
        //echo $visitid; exit();       
        
        $variables = [$id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        //var_dump($id_visit_service_staff);
        // exit();
//        if(STICKY_VISITS == false){

            if(null != $idvisitservicestaff){
                $where = array(
                    'business_id' => $this->session->userdata('businessid'),                    
                    'id_visit_service_staffs' => $idvisitservicestaff
                );
            } else {
                $where = array(
                    'business_id' => $this->session->userdata('businessid'),
                    'visit_service_id' => $id,
                    'staff_id' => $old_staff_id,
                    'id_visit_service_staffs' => $idvisitservicestaff
                );
            }
//        }else{
//            $where = array(
//                'business_id' => $this->session->userdata('businessid'),
//                'customer_visit_id' => $visitid,
//                'staff_id' => $old_staff_id
//            );
//        }

        $this->db->where($where);
        $query = $this->db->update('visit_service_staffs', $staffData);

        ///service
        
//        if(STICKY_VISITS == false){
            $where = array(
                'business_id' => $this->session->userdata('businessid'),
                'id_visit_services' => $id
            );
//        } else {
//            
//            $where = array(
//                'business_id' => $this->session->userdata('businessid'),
//                'customer_visit_id' => $visitid
//            );
//            
//        }
            
        $this->db->where($where);
        $query = $this->db->update('visit_services', $serviceData);

        return $query;
    }
    
    
    function updateInvoiceStaff($id, $old_staff_id, $staffData) {
        $variables = [$id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
//        var_dump($staffData);
//        echo $old_staff_id;
//        echo $id;
//         exit();
        

            $this->db->where('visit_staff_id = '.$id);        
            $query = $this->db->update('invoice_staff', $staffData);

            return $query;
        
    }
    

    function getStaff($id) {
        $variables = [$id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        

        $this->db->select('*');
        $this->db->where('s.id_staff' , $id);
        $query = $this->db->get('staff s');

        return $query->row();
    }

    function getStaffDetails($staff_id, $event_id) {
        $variables = [$staff_id, $event_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*');
        $this->db->join('block_staff_time bst', 's.id_staff = bst.staff_id');
        $this->db->where('bst.id_staff_time_blocked' , $event_id);
        $query = $this->db->get('staff s');
       
        return $query->row();
    }

    function getVisitDetails($id) {
        
        $variables = [$id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        
        
        if($this->session->userdata('hide_cell') && $this->session->userdata('hide_cell')=="Yes"){
            $this->db->select('*, "" as customer_cell');
        }else {
            $this->db->select('*');
        }
        
        
        $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
        $this->db->join('customers c', 'cv.customer_id = c.id_customers');
        $this->db->join('business_services bs', 'bs.id_business_services = vs.service_id');
        $this->db->join('service_category sc', 'bs.service_category_id = sc.id_service_category');
        $this->db->join('visit_service_staffs vss', 'vs.id_visit_services = vss.visit_service_id');
        $this->db->where('vs.id_visit_services', $id);
        $this->db->where('vs.visit_service_status','Active');
        $query = $this->db->get('visit_services vs');

        return $query->result_array();
    }

    function getinvoicebyvisit($id){
        
        $variables = [$id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        
        $this->db->select('inv.id_invoice');
        $this->db->where('inv.visit_id', $id);
        $query = $this->db->get('invoice inv');
        return $query->row();
    }
    
    function getVisitInvoiceId($id) {
        $variables = [$id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $where = array(
            
            'inv.invoice_status' => 'valid',
            'vs.id_visit_services' => $id,
            'inv.invoice_type' => 'service'
        );

        $this->db->select('inv.id_invoice');
        $this->db->join('invoice inv', 'vs.customer_visit_id = inv.visit_id');
        $this->db->where($where);
        $query = $this->db->get('visit_services vs');

        return $query->row();
    }
    
    
    function getInvoiceByVisitId($id) {
        $variables = [$id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $where = array(
            
            'inv.invoice_status' => 'valid',
            'inv.visit_id' => $id,
            'inv.invoice_type' => 'service'
        );

        $this->db->select('inv.id_invoice');        
        $this->db->where($where);
        $query = $this->db->get('invoice inv');

        return $query->row();
    }
    
    
    
   
    function getStaffServicesByVisitId($id){
        $variables = [$id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*', false);        
        $this->db->join("visit_service_staffs", "id_visit_services = visit_service_id and visit_service_staff_status= 'Active'");
        $this->db->where('visit_services.customer_visit_id' , $id);
        $this->db->where('visit_service_status','Active');
        $query = $this->db->get('visit_services');
        //echo $query; exit();
        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();}
        

        $this->db->select('*');        
        $this->db->where('customer_visit_id' , $id);
        $this->db->where('visit_service_status','Active');
        $query = $this->db->get('visit_services');

        return $query->result_array();
    }
    
    function getserviceprice($flag,$serviceid,$categoryid){
        $variables = [$serviceid, $categoryid, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        if($flag=="servicetype"){
            $this->db->select('service_rate');        
            $this->db->where('id_business_services' , $serviceid);
            $query = $this->db->get('business_services');
        } else{
            $this->db->select('service_rate');        
            $this->db->where('service_id' , $serviceid);
            $this->db->where('package_category_id' , $categoryid);
            $query = $this->db->get('package_services');
        }
         return $query->row();
    }

    function getOpenVisitsAfterAdd() {
        $variables = [$this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $where = array(
            'vs.business_id' => $this->session->userdata('businessid'),
            'cv.visit_status' => 'open'
        );

        $this->db->select("*", false);
//        $this->db->select("CASE
//	WHEN visit_service_end = '' THEN concat(substr(visit_service_start, 1, instr(visit_service_start,'T')), addtime(substr(visit_service_start, instr(visit_service_start,'T')+1,10), service_duration)) 
//        WHEN visit_service_end IS NULL THEN concat(substr(visit_service_start, 1, instr(visit_service_start,'T')), addtime(substr(visit_service_start, instr(visit_service_start,'T')+1,10), service_duration)) 
//	WHEN visit_service_end = visit_service_start THEN concat(substr(visit_service_start, 1, instr(visit_service_start,'T')), addtime(substr(visit_service_start, instr(visit_service_start,'T')+1,10), service_duration))  ELSE visit_service_end
//        END as 'visit_service_end'", false);
        $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
        $this->db->join('customers c', 'cv.customer_id = c.id_customers');
        $this->db->join("visit_service_staffs vss", "vs.id_visit_services = vss.visit_service_id and vss.visit_service_staff_status ='Active'");
        $this->db->join('business_services bs', 'bs.id_business_services = vs.service_id');
        $this->db->where('vs.business_id', $this->session->userdata('businessid'));
        $this->db->where('cv.visit_status !=', 'cancelled');
        $this->db->where('vs.visit_service_status', 'Active');
        $this->db->order_by('id_visit_services');
        $query = $this->db->get('visit_services vs');
        //echo $query; exit();
        return $query->result_array();
    }
    
    function getLastVisitColor($start, $end) {
        $variables = [$start, $end, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        //Get visit services
        $this->db->select('visit_color');
        $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
        $this->db->where('vs.business_id', $this->session->userdata('businessid'));
        $this->db->where('vs.visit_service_start >', $start);
        $this->db->where('vs.visit_service_start <', $end);
        $this->db->where('cv.visit_status !=', 'canceled');
        $this->db->order_by('cv.id_customer_visits', 'DESC');
        $this->db->limit(1);
        $query = $this->db->get('visit_services vs');
        $row = $query->row();   
        
        if($row){
            return $row->visit_color;
        } else{
            return "#641E16";
        }
    }
    
    function visitCount($start, $end) {
        $variables = [$start, $end, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        //Get visits 
        $this->db->select('id_customer_visits');
        $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
        $this->db->where('vs.business_id', $this->session->userdata('businessid'));
        $this->db->where('vs.visit_service_start >', $start);
        $this->db->where('vs.visit_service_start <', $end);
        $this->db->where('cv.visit_status !=', 'canceled');
        $this->db->where('cv.visit_status !=', 'AdvKeptcanceled');
        $this->db->group_by('id_customer_visits');
        
        $query = $this->db->get('visit_services vs');
        return $query->num_rows();
        
    }

    function serviceCount($start, $end) {
        $variables = [$start, $end, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        //Get visit services
        $this->db->select('count(id_visit_services) as total, sum(business_services.service_rate) as forecast');
        $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
        $this->db->join('business_services', 'vs.service_id=business_services.id_business_services');
        $this->db->where('vs.business_id', $this->session->userdata('businessid'));
        $this->db->where('vs.visit_service_start >', $start);
        $this->db->where('vs.visit_service_start <', $end);
        $this->db->where('vs.visit_service_status','Active');
        $this->db->where('cv.visit_status !=', 'canceled');
        $this->db->where('cv.visit_status !=', 'AdvKeptcanceled');
        //$this->db->group_by('id_customer_visits');
        $this->db->group_by('vs.business_id');
        $query = $this->db->get('visit_services vs');
       
       // echo $query; exit();
        
        return $query->row();
    }

    
    function getOpenVisitsByDate($start, $end, $sh=false, $stickyvisits=false) {
        $variables = [$start, $end, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        //Get visit services

        $array1 = array();
        $array2 = array();

            if($this->session->userdata('common_products')=='Yes'){
                $where =  "(vs.business_id = ". $this->session->userdata('businessid')." OR vss.block_other = 'Yes') ";
            } else {
                $where =  "vs.business_id = ". $this->session->userdata('businessid')." ";
            } 
                $this->db->select("cv.visit_status, id_visit_services, id_customer_visits, id_visit_service_staffs,
                    vss.staff_id, c.customer_name, c.customer_cell,
                    sc.service_category, bs.service_name, bs.service_color, bs.service_rate,
                    cv.visit_color, cv.visit_color_type, cv.program_enrolled_service_id,
                    vss.block_other, 
                    cv.business_id, b.business_name,
                    visit_service_start, visit_service_end, 
                    inservice, vss.requested, reminder_stricttime, promo, advance, reminder_sms, reminder_call, reminder_email, vss.additional_staff,
                    c.customer_type, membership, vss.id_visit_service_staffs, ifnull(visit_extra,'') visit_extra");
                $this->db->select("bs.service_rate as rate, cv.created_by as 'by'", false);
                $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
                $this->db->join('customers c', 'cv.customer_id = c.id_customers');
                $this->db->join("visit_service_staffs vss", "vs.id_visit_services = vss.visit_service_id and vss.visit_service_staff_status='Active'");
                $this->db->join('business_services bs', 'bs.id_business_services = vs.service_id');
                $this->db->join('service_category sc', 'bs.service_category_id = sc.id_service_category');
                $this->db->join('business b', 'b.id_business = cv.business_id');
                $this->db->where($where);
                $this->db->where('vs.visit_service_start >', $start);
                $this->db->where('vs.visit_service_start <', $end);
                $this->db->where('vs.visit_service_status','Active'); 
            //    $this->db->where('cv.visit_status !=', 'canceled');
                $this->db->where('cv.visit_status !=', 'AdvKeptcanceled');
                if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                    $filter = "(`cv`.`visit_status` = 'open' OR `cv`.`invoice_seq` >0 )";
                    $this->db->where($filter);                    
                }
                $this->db->where('service_flag','servicetype');
//                if(STICKY_VISITS==true){
//                    $this->db->group_by('id_customer_visits');
//                }
                if($stickyvisits==true){
                    $this->db->order_by('id_customer_visits, id_visit_services');
                }
                $query = $this->db->get('visit_services vs');
              
                //echo $query; exit();
              
                $array1[] = $query->result_array();

                $this->db->select("cv.visit_status, id_visit_services, id_customer_visits, id_visit_service_staffs,
                    vss.staff_id, c.customer_name, c.customer_cell,
                    pc.service_category, bs.service_name, bs.service_color, ps.service_rate,
                    cv.visit_color, cv.visit_color_type, cv.program_enrolled_service_id,
                    vss.block_other,
                    cv.business_id, b.business_name,
                    visit_service_start, visit_service_end, 
                    inservice, vss.requested, reminder_stricttime, promo, advance, reminder_sms, reminder_call, reminder_email, , vss.additional_staff,
                    c.customer_type, membership, vss.id_visit_service_staffs, ifnull(visit_extra,'') visit_extra");
                $this->db->select("ps.service_rate as rate, cv.created_by as 'by'", false);
//                $this->db->select("CASE
//                WHEN visit_service_end = '' THEN concat(substr(visit_service_start, 1, instr(visit_service_start,'T')), addtime(substr(visit_service_start, instr(visit_service_start,'T')+1,10), service_duration)) 
//                WHEN visit_service_end IS NULL THEN concat(substr(visit_service_start, 1, instr(visit_service_start,'T')), addtime(substr(visit_service_start, instr(visit_service_start,'T')+1,10), service_duration)) 
//                WHEN visit_service_end = visit_service_start THEN concat(substr(visit_service_start, 1, instr(visit_service_start,'T')), addtime(substr(visit_service_start, instr(visit_service_start,'T')+1,10), service_duration))  ELSE visit_service_end
//                END as 'visit_service_end'", false);
                $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
                $this->db->join('customers c', 'cv.customer_id = c.id_customers');
                $this->db->join("visit_service_staffs vss", "vs.id_visit_services = vss.visit_service_id and vss.visit_service_staff_status='Active'");
                $this->db->join('package_services ps', 'ps.service_id = vs.service_id and ps.package_category_id=vs.id_service_category', 'left');
                $this->db->join('business_services bs', 'bs.id_business_services = ps.service_id', 'left');
                $this->db->join('package_category pc', 'pc.id_package_category = ps.package_category_id', 'left');
                $this->db->join('business b', 'b.id_business = cv.business_id');
                $this->db->where($where);
//                $this->db->where('pc.id_package_category =', $row->id_service_category);
                $this->db->where('vs.visit_service_start >', $start);
                $this->db->where('vs.visit_service_start <', $end);
                $this->db->where('vs.visit_service_status', 'Active');
               // $this->db->where('cv.visit_status !=', 'canceled');
                $this->db->where('cv.visit_status !=', 'AdvKeptcanceled');
                $this->db->where('service_flag !=','servicetype');
                if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                    $filter = "(`cv`.`visit_status` = 'open' OR `cv`.`invoice_seq` >0 )";
                    $this->db->where($filter);                    
                }
//                $this->db->where('vs.id_visit_services', $row->id_visit_services);
//                if(STICKY_VISITS==true){
//                    $this->db->group_by('id_customer_visits');
//                }
                if($stickyvisits==true){
                    $this->db->order_by('id_customer_visits, id_visit_services');
                }
                $query = $this->db->get('visit_services vs');
                
                //echo $query, exit();
                
                $array2[] = $query->result_array();

                $query = $this->db->query("SELECT MAX(update_date) AS most_update_date FROM visit_services ");
                $maxdate = $query->result_array();

        $array_merged = array_merge($array1, $array2, $maxdate);
      //  print_r($array_merged);
       
        
        return $array_merged;
    }

    function getOpenNewVisits($start, $last_update_date, $sh=false, $stickyvisits=false) {
        //echo $last_update_date; exit();
        $variables = [$start, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $tomorrow = date('Y-m-d', strtotime($start . '+1 day'));

        $array1 = array();
        $array2 = array();

        if($this->session->userdata('common_products')=='Yes'){
            $where =  "(vs.business_id = ". $this->session->userdata('businessid')." OR vss.block_other = 'Yes') ";
        } else {
            $where =  "vs.business_id = ". $this->session->userdata('businessid')." ";
        } 
                
                $this->db->select("cv.visit_status, id_visit_services, id_customer_visits, vss.id_visit_service_staffs,
                    vss.staff_id, c.customer_name, c.customer_cell,
                    sc.service_category, bs.service_name, bs.service_color, bs.service_rate,
                    cv.visit_color, cv.visit_color_type, cv.program_enrolled_service_id,
                    vss.block_other,
                    cv.business_id, 
                    visit_service_start, visit_service_end, 
                    inservice, vss.requested, reminder_stricttime, promo, advance, reminder_sms, reminder_call,
                     reminder_email,
                    c.customer_type, ifnull(visit_extra,'') visit_extra");
                $this->db->select("bs.service_rate as rate, cv.created_by as 'by'", false);
                $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
                $this->db->join('customers c', 'cv.customer_id = c.id_customers');
                $this->db->join("visit_service_staffs vss", "vs.id_visit_services = vss.visit_service_id and vss.visit_service_staff_status = 'Active'");
                $this->db->join('business_services bs', 'bs.id_business_services = vs.service_id');
                $this->db->join('service_category sc', 'bs.service_category_id = sc.id_service_category');
                $this->db->where($where);
                $this->db->where('vs.visit_service_start >', $start);
                $this->db->where('vs.visit_service_start <', $tomorrow);
                $this->db->where('vs.visit_service_status','Active');
                if($last_update_date!==''){
                    $this->db->where('vs.update_date >', $last_update_date);
                }

                $this->db->where('service_flag','servicetype');
                if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                    $filter = "(`cv`.`visit_status` = 'open' OR `cv`.`invoice_seq` >0 )";
                    $this->db->where($filter);                    
                }
                

                if($stickyvisits==true){
                    $this->db->order_by('id_customer_visits, id_visit_services');
                }
                $query = $this->db->get('visit_services vs');
               //echo $query; exit();

                $array1[] = $query->result_array();

                 $this->db->select("cv.visit_status, id_visit_services, id_customer_visits, id_visit_service_staffs,
                    vss.staff_id, c.customer_name, c.customer_cell,
                    pc.service_category, bs.service_name, bs.service_color, ps.service_rate,
                    cv.visit_color, cv.visit_color_type, cv.program_enrolled_service_id,
                    vss.block_other,
                    cv.business_id, 
                    visit_service_start, visit_service_end, 
                    inservice, vss.requested, reminder_stricttime, promo, advance, 
                    reminder_sms, reminder_call, reminder_email,
                    c.customer_type, ifnull(visit_extra,'') visit_extra");
                $this->db->select("ps.service_rate as rate, cv.created_by as 'by'", false);
//                $this->db->select("CASE
//                WHEN visit_service_end = '' THEN concat(substr(visit_service_start, 1, instr(visit_service_start,'T')), addtime(substr(visit_service_start, instr(visit_service_start,'T')+1,10), service_duration)) 
//                WHEN visit_service_end IS NULL THEN concat(substr(visit_service_start, 1, instr(visit_service_start,'T')), addtime(substr(visit_service_start, instr(visit_service_start,'T')+1,10), service_duration)) 
//                WHEN visit_service_end = visit_service_start THEN concat(substr(visit_service_start, 1, instr(visit_service_start,'T')), addtime(substr(visit_service_start, instr(visit_service_start,'T')+1,10), service_duration))  ELSE visit_service_end
//                END as 'visit_service_end'", false);
                $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
                $this->db->join('customers c', 'cv.customer_id = c.id_customers');
                $this->db->join("visit_service_staffs vss", "vs.id_visit_services = vss.visit_service_id and vss.visit_service_staff_status='Active'");
                $this->db->join('package_services ps', 'ps.service_id = vs.service_id and ps.package_category_id=vs.id_service_category');
                $this->db->join('business_services bs', 'bs.id_business_services = ps.service_id');
                $this->db->join('package_category pc', 'pc.id_package_category = ps.package_category_id');
                $this->db->where($where);
                $this->db->where('vs.visit_service_start >', $start);
                $this->db->where('vs.visit_service_start <', $tomorrow);
                $this->db->where('vs.visit_service_status','Active');
                if($last_update_date!==''){
                    $this->db->where('vs.update_date >', $last_update_date);
                }
               // $this->db->where('cv.visit_status !=', 'canceled');
                //$this->db->where('cv.visit_status !=', 'AdvKeptcanceled');
                $this->db->where('service_flag !=','servicetype');
                if($sh==true ||  $this->session->userdata('role')=="Sh-Users"){
                    $filter = "(`cv`.`visit_status` = 'open' OR `cv`.`invoice_seq` >0 )";
                    $this->db->where($filter);                    
                }
//                $this->db->where('vs.id_visit_services', $row->id_visit_services);
//                 if(STICKY_VISITS==true){
//                    $this->db->group_by('id_customer_visits');
//                }
                if($stickyvisits==true){
                    $this->db->order_by('id_customer_visits, id_visit_services');
                }
                $query = $this->db->get('visit_services vs');
                
                $array2[] = $query->result_array();


                
                $query = $this->db->query("SELECT MAX(update_date) AS most_update_date FROM visit_services ");
                $maxdate = $query->result_array();

        $array_merged = array_merge($array1, $array2, $maxdate);

        return $array_merged;
    }

    function getMaxVisitServiceId($start) {
        $variables = [$start, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $tomorrow = date('Y-m-d', strtotime($start . '+1 day'));

        $where = array(
            
            'vs.business_id' => $this->session->userdata('businessid')
        );

        $this->db->select_max('update_date');
        $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
        $this->db->where($where);
        $this->db->where('vs.visit_service_start >', $start);
        $this->db->where('vs.visit_service_start <', $tomorrow);
        //$this->db->where('vs.visit_service_status','Active');
        $this->db->where("cv.visit_status='open'");
        
        $query = $this->db->get('visit_services vs');

        return $query->row();
    }

    function getOpenVisitServicesById($id) {
        $variables = [$id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $where = array(
            
            'vs.business_id' => $this->session->userdata('businessid')
            
        );
        $this->db->select('*');
        $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
        $this->db->join('business_services bs', 'bs.id_business_services = vs.service_id');
        $this->db->where($where);
        $this->db->where('visit_service_status','Active');
        $query = $this->db->get('visit_services vs');

        return $query->result();
    }

    function getOpenVisits() {
        $variables = [$this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
      

        $this->db->select('*');
        $this->db->join('customer_visits cv', 'vs.customer_visit_id = cv.id_customer_visits');
        $this->db->join('customers c', 'cv.customer_id = c.id_customers');
        $this->db->join("visit_service_staffs vss", "vs.id_visit_services = vss.visit_service_id and vss.visit_service_staff_status='Active'");
//        $this->db->join('business_services bs', 'bs.id_business_services = vs.service_id');
//        $this->db->where($where);
        $this->db->or_where('cv.visit_status!=', 'invoiced');
        $this->db->where('vs.business_id =', $this->session->userdata('businessid'));
        $this->db->where('vs.visit_service_status','Active');
        $query = $this->db->get('visit_services vs');

        return $query->result();
    }

    function checkDuplicateServices($customer_visit_id) {
        $variables = [$customer_visit_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('service_id');
        $this->db->where('customer_visit_id', $customer_visit_id);
        $this->db->where('visit_service_status','Active');
        $query = $this->db->get('visit_services');

        $check = $query->result();
        if ($check) {
            $service_ids = array();

            foreach ($check as $c) {
                $service_ids[] = $c->service_id;
            }

            return $service_ids;
        }
    }
    
    function check_visit_services_staff($staff_ids, $visit_service_id){
        $variables = [$visit_service_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('staff_name');
        $this->db->where('visit_service_id', $visit_service_id);
        $this->db->where_in('staff_id', $staff_ids);
        $this->db->where('visit_service_staff_status','Active');
        $query = $this->db->get('visit_service_staffs');
        return $query->result();
    }

    function add_visit_services_staff($staff_ids, $staff_names, $visit_id, $visit_service_id,$visit_staff_id, $visit_status) {
//        $variables = [$visit_id, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
       
        $i = 0;
        
        foreach ($staff_ids as $staff_id) {
            $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_names[$i],
                'additional_staff' => 'Yes'
            );
            
            $this->db->insert('visit_service_staffs', $data);
            $last_vss_id = $this->db->insert_id();
            
            if(null != $visit_status && $visit_status=='invoiced'){
                $this->add_invoice_services_staff($staff_id, $staff_names[$i], $visit_id, $visit_staff_id, $last_vss_id);
            }
            
            $i++;
        }
        //update the price and commission distribution in the staff_invoice table
        if(null != $visit_status && $visit_status=='invoiced'){
            $sql = "SELECT id_invoice, id_invoice_staff, 
                invoice_staff.service_type, 
                invoice_staff.service_category, invoice_staff.service_name,
                business_services.commission_perc, business_services.helper_perc,
                id_invoice_staff, invoice_staff.additional_staff, invoice_details.price, invoice_details.discount, invoice_details.service_addition, 
                invoice_details.discounted_price, invoice_details.paid, invoice_details.invoice_discount, invoice_details.final_price,
                invoice_details.paid , additional_staff
                FROM 
                invoice_staff 
                join invoice on id_invoice=invoice_id
                join invoice_details on invoice_details.id_invoice_details = invoice_detail_id
                join business_services on id_business_services = invoice_details.service_id
                where invoice_status='valid' and invoice_details.visit_service_id =".$visit_service_id;        
            $query = $this->db->query($sql);   
        
            if ($query->num_rows() > 0) {
                $staff_count=$query->num_rows();
                $invoice_details =$query->result_array();
                foreach($invoice_details as $detail){
                    $data = array(
                        'price'=> $detail['price']/$staff_count,   
                        'discount'=> $detail['discount']/$staff_count,   
                        'service_addition'=> $detail['service_addition']/$staff_count,   
                        'discounted_price'=> $detail['discounted_price']/$staff_count,   
                        'invoice_discount'=> $detail['invoice_discount']/$staff_count,   
                        'final_price'=> $detail['final_price']/$staff_count,   
                        'paid'=> $detail['paid']/$staff_count,   
                        'commission'=> $detail['additional_staff']=='No' ? ($detail['final_price']*$detail['commission_perc']/100) / $staff_count : ($detail['final_price']*$detail['helper_perc']/100) / $staff_count
                    );
                    $this->db->where('invoice_staff.id_invoice_staff', $detail['id_invoice_staff']);
                    $this->db->update('invoice_staff', $data);
                }
            }
            
        }
        
        $this->db->where('id_visit_services', $visit_service_id);
        $this->db->update('visit_services', array('update_date' => date('Y-m-d H:i:s')));
        
        return $last_vss_id;
    }
    
    function add_invoice_services_staff($staff_id, $staff_name, $visit_id, $visit_staff_id, $new_visit_staff_id){
            
        $sql = "select * from invoice_staff join invoice on id_invoice = invoice_id where invoice.invoice_status='valid' additional_staff='No' and visit_staff_id = ".$visit_staff_id;        
        $query = $this->db->query($sql);   
        
        if ($query->num_rows() > 0) {
            
            $primary_staff_record = $query->row();
          
            $data = array(
                'business_id' => $primary_staff_record->business_id,
                'invoice_detail_id' => $primary_staff_record->invoice_detail_id,
                'invoice_id' => $primary_staff_record->invoice_id,
                'service_type' => $primary_staff_record->service_type,
                'service_category' => $primary_staff_record->service_category,
                'service_name' => $primary_staff_record->service_name,                    
                'staff_id' => $staff_id,
                'staff_name' => $staff_name,
                'price'=> $primary_staff_record->price,   
                'discount'=> $primary_staff_record->discount,   
                'service_addition'=> $primary_staff_record->service_addition,   
                'discounted_price'=> $primary_staff_record->discounted_price,   
                'invoice_discount'=> $primary_staff_record->invoice_discount,   
                'final_price'=> $primary_staff_record->final_price,   
                'paid'=> $primary_staff_record->paid,   
                'commission'=> $primary_staff_record->commission,   
                'requested'=> $primary_staff_record->requested,   
                'additional_staff' => 'Yes',
                'visit_staff_id'=> $new_visit_staff_id  
            );

            $this->db->insert('invoice_staff', $data);
            $last_id = $this->db->insert_id();

            return $last_id;
        } else {
            return 0;
        }
        
    }
    
    
    function change_visit_color($visit_id, $visit_color){
        $variables = [$visit_id, $visit_color, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        

        $this->db->where('id_customer_visits', $visit_id);
        $this->db->update('customer_visits', array('visit_color' => $visit_color));
        
        $this->db->where('customer_visit_id', $visit_id);
        $this->db->update('visit_services', array('update_date' => date('Y-m-d H:i:s')));
        
        return $visit_id;
        
    }
    
    //function get_color_for_visit($last_color_code){
    function get_color_for_visit($start){
        $variables = [$start, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
       $today=explode('T',$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 != 'canceled' and customer_visits.business_id = ".$this->session->userdata('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;
            
        }
        
    }

    function add_visit($customer_id, $visit_id, $last_color_code, $start) {
        $variables = [$customer_id, $visit_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        if($customer_id==0){ return 0; exit();}
        
        //check floor capacity
        
        
        
        ////if program
        $program_enrolled_service_id = null;
        if(null != $this->input->post('customer_enrollment_id') && $this->input->post('customer_enrollment_id')!=''){
            $service_ids = explode(',', $this->input->post('service_ids', TRUE));
            
            $this->db->select('id_program_enrolled_services');
            $this->db->join('program_enrollment','program_enrollment.id_program_enrollment = program_enrolled_services.program_enrollment_id');
            $this->db->where('program_enrollment.customer_id', $customer_id);
            $this->db->where('program_enrollment.id_program_enrollment', $this->input->post('customer_enrollment_id'));
            $this->db->where('program_enrolled_services.service_status','Active');
            $this->db->where('program_enrolled_services.service_id',$service_ids[0]);
            $this->db->order_by('id_program_enrolled_services', 'DESC');
            $query = $this->db->get('program_enrolled_services');

            if($query->num_rows()>0){
                $enrolled_service_id=$query->row();
                $program_enrolled_service_id = $enrolled_service_id->id_program_enrolled_services;
            }
        }
        
        if ($visit_id == 0) {
            //$color = explode('|', $this->get_color_for_visit($last_color_code));
            $color = explode('|', $this->get_color_for_visit($start));
            
            $visit = array(
                'business_id' => $this->session->userdata('businessid'),
                'customer_id' => $customer_id,
                'visit_color' => $color[0],
                'visit_color_type' => $color[1],
                'reminder_stricttime'=>htmlspecialchars($this->input->post('stricttime', TRUE)),
                'customer_visit_date'=>date('Y-m-d H:i:s'),
                'created_by'=>$this->session->userdata('username'),
                'discount'=>$this->input->post('discount'),
                'discount_reason'=>$this->input->post('discount_reason'),
                'program_enrolled_service_id'=>$program_enrolled_service_id
            );
            $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) {
        $variables = [$customer_visit_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        if($customer_visit_id==0){ return 0; exit();}
        
        
        $this->db->select('id_business, business_opening_time, business_closing_time, rec_allow_prev as previous');
        $this->db->where('id_business', $this->session->userdata('businessid'));
        $query = $this->db->get('business');
        $business=$query->row();
        
        $business_end_time = date("H:i:s",strtotime($business->business_closing_time.":00")) ;
        
        $customer_id = htmlspecialchars($this->input->post('customer_id', TRUE));
        $customer_name = htmlspecialchars($this->input->post('customer_name', TRUE));
        
        $staff_id = htmlspecialchars($this->input->post('staff_id', TRUE));
        $staff_name = htmlspecialchars($this->input->post('staff_name', TRUE));
        $start = htmlspecialchars($this->input->post('start', TRUE));
        $requested=$this->input->post('requested');
        $promo=$this->input->post('promo');
        
        
        $service_ids = explode(',', $this->input->post('service_ids', TRUE));
        $service_names = explode(',', $this->input->post('service_names', TRUE));
        $service_duration = explode(',', $this->input->post('service_duration', TRUE));
        $service_type = explode(',', $this->input->post('service_type', TRUE));
        $service_category = explode(',', $this->input->post('service_category', TRUE));
        $service_rate = explode(',', $this->input->post('service_rate', TRUE));
        $id_service_type= explode(',', $this->input->post('id_service_type', TRUE));
       // echo $this->input->post('service_duration', TRUE); exit();
        
        $service_flags = explode(',', $this->input->post('service_flag', TRUE));
        $id_service_categories = $this->input->post('id_service_categories', TRUE);

        $product_ids = $this->input->post('product_ids', TRUE);
        $product_service_ids = $this->input->post('product_service_ids', TRUE);
        $product_names = $this->input->post('product_names', TRUE);
        $qty = $this->input->post('qty', TRUE);
        $unit = $this->input->post('unit', TRUE);
        
        
        $crosssell = $this->input->post('crosssell', TRUE);
        

        $i = 0; $lastduration=0; $newtime='';
        foreach ($service_ids as $service_id) {
            
            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];
                //check business closing time
                $thisstart=  explode('T', $newtime);
                if($thisstart[1]>=$business_end_time){$newtime=$start;}
                 
                //check if duration is present
                if($service_duration[$i]=="00:00:00"){$lastduration="00:15:00";}
                else {$lastduration=$service_duration[$i];}
            } else {
                $newtime=$start;
                $lastduration=$service_duration[$i];
               
            }
            
            //create endtime
            $HoursInMin=0; $newendtime='';
            $durCal =  explode(':',$lastduration);
            if(intval($durCal[0]) > 0){$HoursInMin = intval($durCal[0])*60; }
            $newduration = $HoursInMin + $durCal[1];
            //print_r($newduration); exit();
            $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>');
//            print_r($lastduration);echo('<br>');
//            print_r($newendtime);echo('<br>');
//            exit();
            if($this->input->post('loyalty_service')){
                $data = array(
                    'business_id' => $this->session->userdata('businessid'),
                    'customer_visit_id' => $customer_visit_id,
                    'service_id' => $service_id,
                    'service_name' => $service_names[$i],
                    'service_flag' => $service_flags[$i],
                    'id_service_category' => $id_service_categories[$i],
                    'visit_service_start' => $newtime, //$start
                    'visit_service_end' => $newendtime, //end
                    'update_date' => date('Y-m-d H:i:s'),
                    'loyalty_service' => $this->input->post('loyalty_service'),
                    'promo'=>$this->input->post('promo'),
                    'crosssell'=>$crosssell,
                    's_rate'=>$service_rate[$i],
                    's_type'=>$service_type[$i],
                    's_category'=>$service_category[$i],
                    'id_service_type'=>$id_service_type[$i]
                );
            } else {
                $data = array(
                    'business_id' => $this->session->userdata('businessid'),
                    'customer_visit_id' => $customer_visit_id,
                    'service_id' => $service_id,
                    'service_name' => $service_names[$i],
                    'service_flag' => $service_flags[$i],
                    'id_service_category' => $id_service_categories[$i],
                    'visit_service_start' => $newtime, //$start
                    'visit_service_end' => $newendtime, //end
                    'update_date' => date('Y-m-d H:i:s'),
                    'promo'=>$this->input->post('promo'),
                    'crosssell'=>$crosssell,
                    's_rate'=>$service_rate[$i],
                    's_type'=>$service_type[$i],
                    's_category'=>$service_category[$i],
                    'id_service_type'=>$id_service_type[$i]
                );
            }
            
            $this->db->insert('visit_services', $data);
            $id_visit_services = $this->db->insert_id();
            
            //multiple staff
            
            $s= explode(',',$staff_id);
            $sn= explode(',',$staff_name);
            if($requested == null){$requested='';}
            $r= explode(',',$requested);
            for($x=0; $x< sizeof($s); $x++){
                $block_other='No';
                    
                $this->db->select('staff_shared');
                $this->db->where('id_staff=',$s[$x]);
                $query = $this->db->get('staff');
                $blockstaff = $query->row();

                if (isset($blockstaff))
                { $block_other =  $blockstaff->staff_shared; }
                
                $staff = array(
                    'business_id' => $this->session->userdata('businessid'),
                    'customer_visit_id' => $customer_visit_id,
                    'visit_service_id' => $id_visit_services,
                    'staff_id' => $s[$x],
                    'staff_name' => $sn[$x],
                    'requested' => $r[$x],
                    'block_other' => $block_other
                );
                
                $this->db->insert('visit_service_staffs', $staff);
            }
            //
            $k = 0;

            if ($product_ids) {
                foreach ($product_ids as $product_id) {
                    if ($product_service_ids[$k] == $service_id) {
                        $products = array(
                            'business_id' => $this->session->userdata('businessid'),
                            'customer_visit_id' => $customer_visit_id,
                            'visit_service_id' => $id_visit_services,
                            'product_id' => $product_id,
                            'product_name' => $product_names[$k],
                            'product_qty' => $qty[$k],
                            'product_unit' => $unit[$k]
                        );
                        $this->db->insert('visit_service_products', $products);
                    }
                    $k++;
                }
            }

            $i++;
        }

        //$data = $this->getMaxVisitServiceId(date('Y-m-d', strtotime($start)));

        return $this->db->insert_id();
    }

    function add_visit_staff($customer_visit_id) {
        $variables = [$customer_visit_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        if($customer_visit_id==0){ return 0; exit();}
         
         
        $staff_id = htmlspecialchars($_POST['staff_id']);
        $staff_name = htmlspecialchars($_POST['staff_name']);

        $data = array();

        $i = 0;
        foreach ($service_ids as $service_id) {
            $data[] = array(
                'business_id' => $this->session->userdata('businessid'),
                'customer_visit_id' => $customer_visit_id,
                'service_id' => $service_id,
                'service_name' => $service_names[$i],
                'staff_ids' => $staff_id,
                'staff_names' => $staff_name,
                'visit_service_start' => $start
            );
            $i++;
        }

        $this->db->insert_batch('visit_service_staffs', $data);

        return $this->db->insert_id();
    }

    function check_services_extra($service_visit_id) {
        $variables = [$service_visit_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        

        $this->db->select('visit_services_id');
        $this->db->where('visit_services_id', $service_visit_id);
        $query = $this->db->get('visit_services_extras');

        if ($query->num_rows() > 0) {
            return $query->row();
        }
    }

    function remove_services_extra($service_visit_id) {
       $variables = [$service_visit_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        

        $this->db->select('visit_services_id');
        $this->db->where('visit_services_id', $service_visit_id);
        $query = $this->db->get('visit_services_extras');

        if ($query->num_rows() > 0) {

            $this->db->where('visit_services_id', $service_visit_id);
            $query = $this->db->delete('visit_services_extras');
            return $query;
        }
    }

    function update_services_extra($service_visit_id, $data) {

        $variables = [$service_visit_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->where('visit_services_id', $service_visit_id);
        $query = $this->db->update('visit_services_extras', $data);
        return $query;
    }

    function add_services_extra($data) {
        $variables = [$data, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->insert('visit_services_extras', $data);
        return $this->db->insert_id();
    }

    function update_visit_time($data, $visitid, $service_id, $visit_sid) {
       
        $variables = [$visitid, $service_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->where(
                array(
                    'customer_visit_id' => $visitid,
                    'service_id' => $service_id,
                    'id_visit_services' => $visit_sid
                )
        );

        $this->db->update('visit_services', $data);
    }

    function update_visit_service($data, $visit_service_id) {
        
        $variables = [$visit_service_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->where('id_visit_services' , $visit_service_id);
        $query = $this->db->update('visit_services', $data);

        return $query;
    }

    
    function staff_count(){
        $variables = [ $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        if($this->session->userdata('common_products')=='Yes'){
            $where="(staff.business_id = ".$this->session->userdata('businessid')." OR staff.staff_shared = 'Yes')";
        }else{
            $where="staff.business_id = ".$this->session->userdata('businessid');
        }
        
        $this->db->select('count(*) staff_count');
        $this->db->where($where);
        $this->db->where('staff_active', 'Y');
        $this->db->where('staff_scheduler', 'On');
        
        $query = $this->db->get('staff');

        return $query->row();
    }
    
    function staff_shift_count($shiftid){
        $variables = [$shiftid, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        if($this->session->userdata('common_products')=='Yes'){
            $where="(staff.business_id = ".$this->session->userdata('businessid')." OR staff.staff_shared = 'Yes')";
        }else{
            $where="staff.business_id = ".$this->session->userdata('businessid');
        }
        
        $this->db->select('count(*) staff_count');
        $this->db->join('shift_staff', 'shift_staff.staff_id = staff.id_staff');
        $this->db->where('shift_id', $shiftid);
        $this->db->where($where);
        $this->db->where('staff_active', 'Y');
        $this->db->where('staff_scheduler', 'On');
        $query = $this->db->get('staff');

        return $query->row();
    }
    
    function staff_list($off_set=0, $limit=0) {
        $variables = [$this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        if($this->session->userdata('common_products')=='Yes'){
            $where="(business_id = ".$this->session->userdata('businessid')." OR staff.staff_shared = 'Yes')";
        }else{
            $where="business_id = ".$this->session->userdata('businessid');
        }
        
        $this->db->select('*');
        $this->db->where($where);
        $this->db->where('staff_active', 'Y');
        $this->db->where('staff_scheduler', 'On');
        // if(defined('HIDE_OFFDAY')){if(HIDE_OFFDAY==true){   
        //     $today = date('D');          
        //     $this->db->where("staff.week_day_off NOT LIKE", "'%".$today."%'", false);
        // }}

        //$this->db->order_by('floor_id','Desc');
        $this->db->order_by('staff_order', 'ASC');
        $this->db->offset($off_set);
        if($limit>0){
            $this->db->limit($limit);
        }
        $query = $this->db->get('staff');
       // echo $query; exit();
        return $query->result();
    }
    
    function staff_shift_list($shiftid, $off_set=0, $limit=0) {
        $variables = [$shiftid, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        if($this->session->userdata('common_products')=='Yes'){
            $where="(staff.business_id = ".$this->session->userdata('businessid')." OR staff.staff_shared = 'Yes')";
        }else{
            $where="staff.business_id = ".$this->session->userdata('businessid');
        }
        
        $this->db->select('*');
        $this->db->join('shift_staff', 'shift_staff.staff_id = staff.id_staff');
        $this->db->where($where);
        $this->db->where('shift_id', $shiftid);        
        $this->db->where('staff_active', 'Y');
        $this->db->where('staff_scheduler', 'On');
        $this->db->order_by('staff_order', 'ASC');
        $this->db->offset($off_set);
        if($limit>0){
            $this->db->limit($limit);
        }
        $query = $this->db->get('staff');

        return $query->result();
    }
    

    function staff_info($business_id, $staff_id) {
        $variables = [$staff_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*');
        $this->db->where('id_staff' , $staff_id);
        $query = $this->db->get('staff');

        return $query->row();
    }

    function getOnlineStaff($business_id, $staff_id) {
        $variables = [$staff_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        
        $sql = " SELECT * FROM staff s 
                JOIN staff_attendance sa ON s.id_staff = sa.staff_id where";
        
        if($this->session->userdata('common_products')=='Yes'){
            $sql .=" (staff.business_id = ".$this->session->userdata('businessid')." OR staff.staff_shared = 'Yes') AND";
        }else{
            $sql .=" staff.business_id = ".$this->session->userdata('businessid')." AND ";
        }
        $sql .=" s.id_staff = ".$staff_id." AND 
                sa.staff_id = ".$staff_id." AND 
                sa.time_in BETWEEN NOW() AND sa.time_in ";
        
        $query = $this->db->query($sql);              
                
        return $query->row();
    }


    function get_blockstaff_by_id() {
        
        $variables = [$this->input->post('staff_id'), $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*');
        $this->db->where('staff_id', $this->input->post('staff_id'));
        $this->db->like('start_time', $this->input->post('block_calendar_date'), 'after');
        $query = $this->db->get('block_staff_time');
        return $query->row();
    }

    function get_eventstaff_by_id() {
        $variables = [$this->input->post('staff_id'), $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 vs", "vs.customer_visit_id = cv.id_customer_visits and vs.visit_service_status='Active'");
        $this->db->join("visit_service_staffs vss", "vss.customer_visit_id = cv.id_customer_visits and vss.visit_service_staff_status='Active'");
        $this->db->where('vss.staff_id', $this->input->post('staff_id'));
        $this->db->where('cv.visit_status <>', 'canceled');

        if ($this->input->post('tagged') && $this->input->post('tagged') === "fullday") {
            
            $this->db->where("date_format(vs.visit_service_start,'%Y-%m-%d') = '".$this->input->post('block_calendar_date')."'");
            
        } else if ($this->input->post('tagged') && $this->input->post('tagged') === "halfday") {
            
            $block_calendar_date = $this->input->post('block_calendar_date');
            $start = $this->input->post('block_start_time', TRUE);
            $start = explode(':', $start);
            $start = $start[0];

            //calculation for end time;
            $end = $this->input->post('block_end_time', TRUE);
            $end = explode(':', $end);
            $end = $end[0];

            $half_day = $end - $start;
            $endtime = $half_day / 2;
            $end = $endtime + $start;
            $end = round($end);
            $end = $end.':00:00';
            //$end = $block_calendar_date.'T'.$end;
             
            $this->db->where("date_format(vs.visit_service_start,'%H:%i:%s') <= '".$end."'");
            $this->db->where("date_format(vs.visit_service_start,'%Y-%m-%d') = '".$block_calendar_date."'");
        }
        
        $query = $this->db->get('customer_visits cv');
       
        return $query->row();
    }

    function get_staffname($staff_id) {
        $variables = [$staff_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $this->db->select('*');
        $this->db->where('id_staff', $staff_id);
        $query = $this->db->get('staff');
        $query = $query->row();
        return $query->staff_fullname;
    }
    
    function reminder_message_update(){
        
        $reminder = $this->input->post('reminder');//value Y|N
        $tagged = $this->input->post('tagged');//Column Name like reminder_sms|reminder_call|reminder_email
        
        if(substr($tagged, -1) == "1"){$tagged = str_replace("1","", $tagged);}
        
        
        if($tagged == "reminder_requested"){ //handle requested seperately and update the visit_service_staffs
            $requested = "No";
            if($this->input->post('reminder')=="Y"){$requested="Yes";}
            $data = array(
                'requested' => $requested
            );
            $this->db->where('id_visit_service_staffs', $this->input->post('id_visit_service_staff'));
            $this->db->update('visit_service_staffs', $data);
            
            $this->db->where('customer_visit_id', $this->input->post('customer_visit_id'));
            $this->db->update('visit_services', array('update_date' => date('Y-m-d H:i:s')));
            
            return $this->db->affected_rows();
            
            
        } else if ($tagged == "reminder_promo"){
            $promo = "No";
            if($this->input->post('reminder')=="Y"){$promo="Yes";}
            $data = array(
                'promo' => $promo
            );
            $this->db->where('id_visit_services', $this->input->post('id_visit_services'));
            $this->db->update('visit_services', $data);
            
            $this->db->where('customer_visit_id', $this->input->post('customer_visit_id'));
            $this->db->update('visit_services', array('update_date' => date('Y-m-d H:i:s')));
            
            return $this->db->affected_rows();
            
        } else {
        
            $data = array(
                $tagged => $reminder
            );
            //print_r($data);exit;
            $this->db->where('id_customer_visits', $this->input->post('customer_visit_id'));
            $this->db->update('customer_visits', $data);
            
            $this->db->where('customer_visit_id', $this->input->post('customer_visit_id'));
            $this->db->update('visit_services', array('update_date' => date('Y-m-d H:i:s')));
            
            return $this->db->affected_rows();
        }
    }

    function staff_day_services($staff_id, $calendar_date){
        $variables = [$staff_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $today = $calendar_date;
        $datetime = new DateTime($today);
        $datetime->modify('+1 day');
        $tomorrow = $datetime->format('Y-m-d H:i:s');
         
        $sql="select invoice_staff.staff_id, invoice_staff.staff_name, invoice_staff.service_name, invoice_staff.service_category
            , count(a.id_invoice) count,
            sum(invoice_staff.discounted_price) discounted_price, sum(invoice_staff.discount) discount, sum(invoice_staff.paid) 'revenue_share'
            from invoice_staff
            join invoice_details on invoice_details.id_invoice_details = invoice_staff.invoice_detail_id 
            join (
            SELECT id_invoice, visit_services.service_id, id_service_category, visit_service_staffs.staff_id, visit_service_staffs.staff_name, visit_services.service_name
                            From visit_service_staffs
                       join visit_services on visit_services.id_visit_services = visit_service_staffs.visit_service_id
                       and visit_service_status='Active' 
                               join customer_visits on customer_visits.id_customer_visits = visit_services.customer_visit_id	
                       join invoice on invoice.visit_id = customer_visits.id_customer_visits
                       where visit_service_start  >= '".$today."' 
                       and visit_service_start < '".$tomorrow."' 
                       and visit_service_staffs.staff_id = ".$staff_id." 
                       and invoice_status='valid' and customer_visits.visit_status='invoiced'
                       and ifnull(reference_invoice_number,'') = ''
                       and invoice.invoice_type ='service'
                       and visit_service_staff_status='Active' 
            ) as a on a.staff_id = invoice_staff.staff_id 
            and a.service_id = invoice_details.service_id
            and a.id_invoice = invoice_details.invoice_id
            group by invoice_staff.staff_id, invoice_staff.staff_name, invoice_staff.service_name, invoice_staff.service_category
            order by 5 desc;";
        
     //  echo $sql; exit();
        $query = $this->db->query($sql);
                
        return $query->result();
        
        
    }
    
    
    function staff_day_recoveries($staff_id, $calendar_date){
        $variables = [$staff_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $today = $calendar_date;
        $datetime = new DateTime($today);
        $datetime->modify('+1 day');
        $tomorrow = $datetime->format('Y-m-d H:i:s');
                
        $sql = "SELECT staff_id, staff_name, staff_services.service_name, staff_services.service_category, count(id_staff_services) count, 
           sum(staff_services.discounted_price) discounted_price, sum(staff_services.discount) discount, sum(paid) 'revenue_share'
           FROM staff_services
           join invoice on invoice.id_invoice = staff_services.invoice_id
           where invoice_date  >= '".$today."' 
           and invoice_date  < '".$tomorrow."' 
           and staff_id = ".$staff_id." 
           and invoice_status='valid'
           and ifnull(reference_invoice_number,'') <> ''
           and staff_services.sale_type='service'
           group by staff_id, staff_name, service_name, service_category
           order by 5 desc;";
        
        $query = $this->db->query($sql);
                
        return $query->result();
        
        
    }

    public function change_date($date, $visit_service_id){
        
        $variables = [$visit_service_id, $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
               
        $this->db->select("substr(visit_service_start, LOCATE('T',visit_service_start), length(visit_service_start)) as vss", False);
        $this->db->select("substr(visit_service_end, LOCATE('T',visit_service_end), length(visit_service_end)) as vse", False);
        $this->db->where('id_visit_services=', $visit_service_id);
        $query=$this->db->get('visit_services');
        
        $row = $query->row();
        
        if($row->vse !== ''){
            $data = array(
                'visit_service_start' => $date.$row->vss,                
                'visit_service_end' => $date.$row->vse,
                'update_date' => date('Y-m-d H:i:s')
            );
        } else {
            
            $data = array(
                'visit_service_start' => $date.$row->vss,
                'update_date' => date('Y-m-d H:i:s')
            );
        }
        
        $this->db->where('id_visit_services=', $visit_service_id);
        $query=$this->db->update('visit_services', $data);
        
        return $this->db->affected_rows();
   
    }
    
    public function change_staff($staff, $visit_service_staff_id, $visit_id){
       // exit();
        $this->db->select("id_staff, staff_fullname", False);
        $this->db->where('id_staff=', $staff);
        $query=$this->db->get('staff');
        
        $row = $query->row();
        

        $this->db->set('staff_id', $row->id_staff);
        $this->db->set('staff_name', $row->staff_fullname);
        $this->db->where('id_visit_service_staffs=', $visit_service_staff_id);
        $this->db->update('visit_service_staffs');
        
        $updated=$this->db->affected_rows();
        

        $this->db->set('staff_id', $row->id_staff);
        $this->db->set('staff_name', $row->staff_fullname);
        $this->db->where('visit_staff_id', $visit_service_staff_id);
        $this->db->update('invoice_staff');

        if($updated > 0){
            ///update visit services
            $this->db->where('customer_visit_id', $visit_id);
            $this->db->update('visit_services', array('update_date' => date('Y-m-d H:i:s')));

        }        
        
        return $updated;   
    }
    
    public function assign_all_to_staff($staff, $visit_id){

        ///check if invoiced
       
        $this->db->select("id_staff, staff_fullname", False);
        $this->db->where('id_staff=', $staff);
        $query=$this->db->get('staff');
        
        $row = $query->row();
        

        $this->db->select("id_invoice", False);
        $this->db->where('visit_id=', $visit_id);
        $this->db->where('invoice_status=', 'valid');
        $invoicequery=$this->db->get('invoice');
        if($invoicequery->num_rows()>0){
            $invoice=$invoicequery->row();

            //update invoice
            $this->db->set('staff_id', $row->id_staff);
            $this->db->set('staff_name', $row->staff_fullname);
            $this->db->where('invoice_id = ', $invoice->id_invoice);
            $this->db->update('invoice_staff');
        }

        //update visit
        $this->db->set('staff_id', $row->id_staff);
        $this->db->set('staff_name', $row->staff_fullname);
        $this->db->where('customer_visit_id = ', $visit_id);
        $this->db->update('visit_service_staffs');

        

        
        $updated=$this->db->affected_rows();
        
        if($updated > 0){
            ///update visit services
            $this->db->where('customer_visit_id', $visit_id);
            $this->db->update('visit_services', array('update_date' => date('Y-m-d H:i:s')));

        }
        
        return $updated;
   
    }
    
    public function duplicate_service(){
        $variables = [$this->input->post('cd_visit_id'), $this->session->userdata('businessid')];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        $visitid= $this->input->post('cd_visit_id');
        $visitserviceid= $this->input->post('cd_visit_service_id');
        $dupqty=$this->input->post('dup_qty');
        
        
        $this->db->select('service_duration');
        
        
        $this->db->select("visit_services.business_id, visit_services.customer_visit_id, visit_services.service_id, visit_services.service_name, 
            Concat(date_format(visit_service_start,'%Y-%m-%d'),'T', ADDTIME(date_format(visit_service_start,'%H:%i:%s'),service_duration)) as visit_service_start, 
            Concat(date_format(visit_service_start,'%Y-%m-%d'),'T', ADDTIME(date_format(visit_service_end,'%H:%i:%s'),service_duration))as visit_service_end,
            update_date, service_flag,
            id_service_category, loyalty_service, promo, service_duration", false);
        $this->db->join('business_services', 'business_services.id_business_services = visit_services.service_id');
        $this->db->where('id_visit_services',$visitserviceid);
        $query=$this->db->get('visit_services');
        
      
        $service=$query->row();
        
        $visit_service_start = $service->visit_service_start;
        $visit_service_end = $service->visit_service_end;
       
        for($x=0; $x<$dupqty; $x++){
            //insert the visit service again
            $data=array(
                'business_id' => $service->business_id,
                'customer_visit_id' => $service->customer_visit_id,
                'service_id' => $service->service_id,
                'service_name' => $service->service_name,
                'visit_service_start' => $service->visit_service_start,
                'visit_service_end' => $service->visit_service_end,
                'update_date' => date('Y-m-d H:i:s'),
                'service_flag' => $service->service_flag,
                'id_service_category' => $service->id_service_category,
                'loyalty_service' => $service->loyalty_service,
                'promo' => $service->promo                
            );
            $this->db->insert('visit_services', $data);
            
            $newvisitserviceid=$this->db->insert_id();
            
            //get all the visit_service_staff
            $this->db->select('*');
            $this->db->where('visit_service_id', $visitserviceid);
            $query= $this->db->get('visit_service_staffs');
            
            //$staffindex=-1; 
            foreach ($query->result() as $row)
            {
//                if($staffindex < sizeof($staff)){
//                    $staffindex++;
//                } else {
//                    $staffindex = 0;
//                }
                
                $data=array(
                    'business_id' => $row->business_id,
                    'customer_visit_id' => $row->customer_visit_id,
                    'visit_service_id' => $newvisitserviceid,
                    'staff_id' => $row->staff_id,
                    'staff_name' => $row->staff_name,
                    'requested' => $row->requested,
                    'block_other' => $row->block_other,
                    'additional_staff' => $row->additional_staff
                    
                    );
                $this->db->insert('visit_service_staffs', $data);
            }
            
            //get all the visit_service_products
            $this->db->select('*');
            $this->db->where('visit_service_id', $visitserviceid);
            $query= $this->db->get('visit_service_products');
            
            foreach ($query->result() as $row1)
            {
                $data=array(
                    'business_id' => $row1->business_id,
                    'customer_visit_id' => $row1->customer_visit_id,
                    'visit_service_id' => $newvisitserviceid,
                    'product_id' => $row1->product_id,
                    'product_name' => $row1->product_name,
                    'product_qty' => $row1->product_qty,
                    'product_unit' => $row1->product_unit
                    );
                $this->db->insert('visit_service_products', $data);
            }
           
             //get the new start and end times
            $this->db->select("Concat(date_format(visit_service_start,'%Y-%m-%d'),'T', ADDTIME(date_format(visit_service_start,'%H:%i:%s'),'".$service->service_duration."')) as visit_service_start, 
            Concat(date_format(visit_service_start,'%Y-%m-%d'),'T', ADDTIME(date_format(visit_service_end,'%H:%i:%s'),'".$service->service_duration."'))as visit_service_end", false);
            $this->db->where('id_visit_services',$newvisitserviceid);
            $query=$this->db->get('visit_services');
            $newservice= $query->row();
            $visit_service_start = $newservice->visit_service_start;
            $visit_service_end = $newservice->visit_service_end;
        }
        
        
        return 'success';
        
        
    }
    
    function checkvariables($variables){
        $result=true;
        foreach($variables as $var){
            if(null == $var && $var == ''){
                $result=false;
            }
        }
        return $result;
    }
}
