<?php

class Pos_model extends CI_Model {

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

    function getProducts() {
        $this->db->select('*');
        $query = $this->db->get('business_products');
        return $query->result_array();
    }
    
    function getProductDetail($id) {
        
        $variables = [$id];
        $fine = $this->checkvariables($variables);
        if($fine == false){  return array('mes'=>'missing data'); exit();}
        
        
        $this->db->select('*');
        $this->db->where('id_business_products' , $id);
        $query = $this->db->get('business_products');
        return $query->row();
    }

    function add_visit($customer_id, $visit_id, $start, $advance_remarks) {
       
//        $variables = [$customer_id, $visit_id, $start, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return 0; exit();}
        
        if($customer_id ==0){return 0; exit();}
        
        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_visit_date' => date('Y-m-d H:i:s'),
                'customer_id' => $customer_id,
                'visit_color' => $color[0],
                'visit_color_type' => $color[1],
                'advance_comment' => $advance_remarks,
                'customer_visit_date'=>date('Y-m-d H:i:s'),
                'created_by'=>$this->session->userdata('username')
            );
            $this->db->insert('customer_visits', $visit);
            $visit_id = $this->db->insert_id();
            return $visit_id;
        } else {
            return $visit_id;
        }
        
    } 
    
    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 and visit_services.visit_service_status='Active'
            
            where date_format(visit_services.visit_service_start,'%Y-%m-%d') = '".$today[0]."'
            and visit_status != 'cancelled' 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_services($customer_visit_id, $customer_id, $customer_name, $services, $products, $staff, $start) {
//        print_r($products); exit();
//        $variables = [$customer_visit_id, $customer_id, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); 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")) ;
        
        $i = 0; $lastduration=0; $newtime='';
        
        foreach ($services as $service) {
            
            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['service_duration']=="00:00:00"){$lastduration="00:15:00";}
                else {$lastduration=$service['service_duration'];}
            } else {
                $newtime=$start;
                $lastduration=$service['service_duration'];
            }
            
            
            //create endtime
            $HoursInMin=0; $newendtime='';
            $durCal =  explode(':',$lastduration);
            if(intval($durCal[0]) > 0){$HoursInMin = intval($durCal[0])*60; }
            $newduration = $HoursInMin + $durCal[1];
            $newduration = date_interval_create_from_date_string($newduration.' minutes');
            $newendtime=date_create($newendtime);
            $newendtime = date_add(date_create($newtime), $newduration);
            $newendtime=date_format($newendtime,"c");
            $d=  explode('+', (string)$newendtime);
            $newendtime=$d[0];
            //
//            print_r($newtime);echo('<br>');
//            print_r($lastduration);echo('<br>');
//            print_r($business_end_time);echo('<br>');
            
            
            if($this->input->post('loyalty_service')){
                $data = array(
                    'business_id' => $this->session->userdata('businessid'),
                    'customer_visit_id' => $customer_visit_id,
                    'service_id' => $service['service_id'],
                    'service_name' => $service['service_name'],
                    'service_flag' => $service['service_flag'],
                    'id_service_category' => $service['id_service_category'],
                    'visit_service_start' => $newtime, //$start
                    'visit_service_end' => $newendtime, //$start
                    'update_date' => date('Y-m-d H:i:s'),
                    'loyalty_service' => $this->input->post('loyalty_service'),
                    //'crosssell'=>$crosssell,
                    's_rate'=>$service['service_rate'],
                    's_type'=>$service['service_type'],
                    's_category'=>$service['service_category'],
                    'id_service_type'=>$service['id_service_type']
                );
            } else {
                $data = array(
                    'business_id' => $this->session->userdata('businessid'),
                    'customer_visit_id' => $customer_visit_id,
                    'service_id' => $service['service_id'],
                    'service_name' => $service['service_name'],
                    'service_flag' => $service['service_flag'],
                    'id_service_category' => $service['id_service_category'],
                    'visit_service_start' => $newtime, //$start
                    'visit_service_end' => $newendtime, //$end
                    'update_date' => date('Y-m-d H:i:s'),
                    's_rate'=>$service['service_rate'],
                    's_type'=>$service['service_type'],
                    's_category'=>$service['service_category'],
                    'id_service_type'=>$service['id_service_type']
                );
            }
            
            $this->db->insert('visit_services', $data);
            $id_visit_services = $this->db->insert_id();
            $i=0;
            //Multiple Staff
            foreach($staff as $s){
                if($s['row_id']===$service['row_id']){
                    $block_other='No';
                    
                    $this->db->select('staff_shared');
                    $this->db->where('id_staff=',$s['staff_id']);
                    $query = $this->db->get('staff');
                    $blockstaff = $query->row();

                    if (isset($blockstaff))
                    { $block_other =  $blockstaff->staff_shared; }
                    
                    if($i==0){
                        //Main staff
                        $data = array(
                            'business_id' => $this->session->userdata('businessid'),
                            'customer_visit_id' => $customer_visit_id,
                            'visit_service_id' => $id_visit_services,
                            'staff_id' => $s['staff_id'],
                            'staff_name' => $s['staff_name'],
                            'requested' => $s['requested'],
                            'block_other' => $block_other
                        );
                    } else {
                        //Additional Staff
                         $data = array(
                            'business_id' => $this->session->userdata('businessid'),
                            'customer_visit_id' => $customer_visit_id,
                            'visit_service_id' => $id_visit_services,
                            'staff_id' => $s['staff_id'],
                            'staff_name' => $s['staff_name'],
                            'requested' => $s['requested'],
                            'block_other' => $block_other,
                            'additional_staff' => 'Yes' 
                        );
                    }
                //var_dump($data);
                $this->db->insert('visit_service_staffs', $data);
                $i++;
                }                
            }
            
            
            //Multiple Products
            if($products != null){
                foreach($products as $product){
                    if($product['row_id']===$service['row_id']){
                        $data = array(
                            'business_id' => $this->session->userdata('businessid'),
                            'customer_visit_id' => $customer_visit_id,
                            'visit_service_id' => $id_visit_services,
                            'product_id' => $product['product_id'],
                            'product_name' => $product['product_name'],
                            'product_qty' => $product['qty'],
                            'product_unit' => $product['unit']
                        );
                        $this->db->insert('visit_service_products', $data);
                    }
                }
            }
            $i++;
        }        
        return $customer_visit_id;
    }
 
    function move_advance($from_visit_id, $to_visit_id){
//       $variables = [$from_visit_id, $to_visit_id, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}

       $this->db->where('customer_visit_id', $from_visit_id);
       $this->db->update('visit_advance', array('customer_visit_id'=>$to_visit_id));
       
       return $this->db->affected_rows();
       
    }
    
    function removeVisit($visit_id){
//        $variables = [$visit_id, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}

        
        $canceledby=$this->session->userdata('username');
        $cancelreason='Visit Changed From POS View';
           
        $where = array(
            'business_id' => $this->session->userdata('businessid'),
            'id_customer_visits' => $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", $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')));
        }
                
       return true;
        
    }
    
    function insert_invoice($invoice_number, $invoice_date, $customer_id, $customername, $customercell, $customeraddress, $customeremail, $subtotal,$paid,$returnamount,$discount, $invoice_discount_type, $grosstotal,$balance,$taxtotal,$grandtotal,$visitid,$paymentmode,$instrumentnumber,$remarks,$discountremarks,$loyaltyused, $visittime, $advance_amount, $other_charges, $retained_used, $keepadv, $cctip,$loyaltyearned,$retained_amount_used,$cashpaid,$cardpaid,$voucherpaid,$checkpaid,$cc_charge,$totalpayable, $remaining_retained, $visitdate, $service_addition) {
//        $variables = [$visitid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
//echo $grandtotal; exit();
        $insertloyalty = true;
        if(defined('LOYALTY_VOUCHER')){                    
            if(LOYALTY_VOUCHER==TRUE){
                $insertloyalty=false;
            }
        }
       

        $data = array(
            'invoice_number'=>$invoice_number,
            'invoice_date'=>$invoice_date,
            'customer_id'=>$customer_id,
            'business_id'=>$this->session->userdata('businessid'),
            'customer_name'=>$customername,
            'customer_cell'=>$customercell,
            'customer_address'=> $customeraddress,
            'customer_email'=> $customeremail,
            'sub_total'=>$subtotal,
            'paid_amount' => $paid,
            'returnamount' => $keepadv==='true' ? 0 : $returnamount,
            'discount' => $discount,
            'discount_reason' => $invoice_discount_type,
            'service_addition' => $service_addition,
            'gross_amount' => $grosstotal + $taxtotal,
            'gross_wo_tax' => $grosstotal,
            'balance'=>$balance,
            'tax_total'=>$taxtotal,
            'net_amount' => $grandtotal,
            'visit_id' => $visitid,
            'invoice_status'=>'valid',
            'payment_mode'=>$paymentmode,
            'instrument_number'=>$instrumentnumber,
            'is_recovery' => $balance > 0 ? 'Yes' : 'No',
            'remarks'=>$remarks,
            'discount_remarks'=>$discountremarks,

            'loyalty_used'=> $insertloyalty == true ? $loyaltyused : 0,
            'loyalty_earned'=> $insertloyalty==true ? $loyaltyearned : 0,

            'visit_time'=> $visitdate.' '.$visittime,
            'advance_amount'=>$advance_amount,
            'other_charges'=>$other_charges,
            'retained_used'=>$retained_used,
            'retained_amount'=>$keepadv==='true' ? $returnamount : 0,
            'cctip'=>$cctip,            
            'retained_amount_used'=>$retained_amount_used,
            'paid_cash' => $cashpaid,
            'paid_card' => $cardpaid,
            'paid_voucher' => $voucherpaid,
            'paid_check' => $checkpaid,
            'cc_charge'=>$cc_charge,
            'total_payable'=>$totalpayable-($cctip+$cc_charge),
            'created_by' => $this->session->userdata('username')
        );
        
        $this->db->insert('invoice',$data);
        $invoiceid = $this->db->insert_id();
        
        
        return $invoiceid;
        
    }
    
    function insert_invoice_details($row_id, $invoiceid, $service_paid, $service_type, $service_category, $service_id, $service_name, $service_duration, $service_flag, $id_service_category, $discount, $discount_type, $unitcost, $originalservicerate, $visit_service_start, $priceafterdiscount, $discount_perc, $invoicediscount, $service_addition, $finalprice, $sPercPaidForService, $service_products,  $visitserviceids){
//        $variables = [$invoiceid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}
        $business = $this->business_model->getbusinessdetails('service');
        $taxperc= $this->business_model->get_tax_perc('service');
        $taxonoriginalprice= round((floatval($originalservicerate) * $taxperc->tax_percentage)/100,2);
        
        $taxonfinalprice = round((floatval($finalprice) * $taxperc->tax_percentage)/100,2);
        
        $servicesdetails= array(
                           
            'invoice_id' => $invoiceid,
            'business_id' => $this->session->userdata('businessid'),
            'service_id' => $service_id,
            'service_type' => $service_type,
            'service_category' => $service_category,
            'service_name' => $service_name,
            'staff' => '',
            'products' => $service_products,
            'price' => $originalservicerate,
            'discount' => $discount,
            'discount_type' => $discount_type,

            'discounted_price' => $priceafterdiscount,
            'invoice_discount' => $invoicediscount,
            'service_addition' => $service_addition,
            'final_price' => $finalprice,
            
            'taxes' => $business[0]['tax_mode']='after' ? $taxonfinalprice :  $taxonoriginalprice,

            'paid'=>$sPercPaidForService,

            'detail_visit_date'=>str_replace('T',' ',$visit_service_start),
            'service_flag'=>$service_flag,
            'visit_service_id'=> $visitserviceids
            
           // 'requested'=>$requested
                
        );
        $this->db->insert('invoice_details', $servicesdetails);
        
        return $this->db->insert_id();
        
    }
    
    function insert_invoice_staff($row_id, $invoiceid, $service_type, $service_category, $service_name, $price, $discount, $discounted_price, $requested, $staff_id, $staff_name, $staff_count, $staff_share, $invoice_detail_id, $additional_staff, $priceafterdiscount,$discount_perc,$invoicediscount, $service_addition, $finalprice, $sPercPaidForService, $commission, $visit_staff_id){
        //echo $requested; exit();
//        $variables = [$invoiceid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}

        $staff = array(
            
            'invoice_id' => $invoiceid,
            'invoice_detail_id' => $invoice_detail_id,
            'business_id' => $this->session->userdata('businessid'),
            'service_type' => $service_type,
            'service_category' => $service_category,
            'service_name' => $service_name,
            'staff_name' => $staff_name,
            'staff_id' => $staff_id,
            'price' => $price / $staff_count,
            'discount' => ($discount == '')? 0 : $discount / $staff_count,
            'discounted_price' => $priceafterdiscount/$staff_count,
            'service_addition' => $service_addition/$staff_count,
            'invoice_discount' => $invoicediscount/$staff_count,
            'final_price' => $finalprice/$staff_count,
            'paid' => $sPercPaidForService/$staff_count,
            'commission' => $commission/$staff_count,
            'requested'=>$requested,
            'additional_staff'=>$additional_staff,
            'visit_staff_id'=>$visit_staff_id
        );
        $this->db->insert('invoice_staff', $staff);
        
    }
    
     function insert_invoice_staff_services($row_id, $invoiceid, $invoice_detail_id, $visitid, $staff_id, $service_id, $staff_name, $service_type, $service_category, $service_name, $staff_price, $staff_discount, $staff_commission, $paid, $service_flag, $requested, $staff_count, $unitcost, $staff_share, $service_price){
        //update commissions
//        $variables = [$invoiceid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}

        if($service_price>0){
            $staff_paid = round(($staff_share*$paid)/$service_price);
        } else {$staff_paid=0;}
        
                $staffservice = array(
                    'invoice_id' => $invoiceid,
                    'invoice_detail_id' => $invoice_detail_id,
                    'business_id' => $this->session->userdata('businessid'),
                    'visit_id' => $visitid,
                    'staff_id' => $staff_id,
                    'service_id' => $service_id,
                    'staff_name' => $staff_name,
                    'service_type' => $service_type,
                    'service_category' => $service_category,
                    'service_name' => $service_name,
                    'price' => $unitcost/$staff_count,
                    'discount' => ($staff_discount == '')? 0 :  $staff_discount/$staff_count,
                    'discounted_price' => $staff_price,
                    'staff_commission' => $staff_commission,
                    'paid' => $staff_paid,
                    'service_flag'=>$service_flag,
                    'requested'=>$requested,
                    'staff_share'=>$staff_share
                );
                $this->db->insert('staff_services', $staffservice);
    }
    
    
    function insert_service_sale_voucher($invoiceid, $customer_id, $customername, $totalpayable, $paymentmode, $returnamount, $cashpaid, $cardpaid, $checkpaid, $voucherpaid, $cctip,$balance, $totalservicediscount, $discount, $retained_amount_used, $advance_amount, $org_subtotal, $other_charges, $cc_charge, $customer_advance, $taxtotal, $roundedadjustment, $loyaltyused, $loyaltyearned){
//        $variables = [$invoiceid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}

        ///create sale voucher
        if($this->session->userdata('auto_voucher')=='Yes'){
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(1);
            //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' => 'Service Sale Voucher against invoice ' . $invoiceid . ' on '. date('d-m-Y').', for '.$customername.' customer ID : '. $customer_id,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $totalpayable,
                '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'=>$customername,
                'voucher_type'=>2,
                'payment_mode'=>$paymentmode,
                'bank_name'=>$bank_name,
                'invoice_id'=>$invoiceid,
                'auto_voucher'=>'Yes',
                'sale_type'=>'service'
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            //enter debit entries
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                if($debit[2]=="paid_cash" && $cashpaid > 0){$debitamount= $customer_advance==='true' ?  $cashpaid+ $returnamount : $cashpaid ;}
                if($debit[2]=="paid_check" && $checkpaid > 0){$debitamount= $customer_advance==='true' ?  $checkpaid+ $returnamount : $checkpaid ;}
                if($debit[2]=="paid_voucher" && $voucherpaid > 0){$debitamount= $voucherpaid;}
                if($debit[2]=="paid_cash" && $cashpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount+$cashpaid : $cashpaid;}
                if($debit[2]=="paid_card" && $cardpaid > 0){$debitamount= $customer_advance==='true' ?  $cardpaid+ $returnamount : $cardpaid ;}
                if($debit[2]=="paid_check" && $checkpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount + $checkpaid : $checkpaid;}
                if($debit[2]=="paid_voucher" && $voucherpaid > 0){$debitamount= $customer_advance==='true' ? $returnamount + $voucherpaid : $voucherpaid;}
                if($debit[2]=="balance"){$debitamount= $balance;}
                if($debit[2]=="sale_discount_service"){$debitamount= $totalservicediscount + $discount;}
                if($debit[2]=="retained_amount_used"){$debitamount= $retained_amount_used;}
                if($debit[2]=="advance_adjusted"){
                    if($retained_amount_used==0 && $advance_amount > 0){
                        $debitamount= $advance_amount;
                    } elseif($retained_amount_used>0 && $advance_amount > 0) {
                        $debitamount= $advance_amount-$retained_amount_used;                        
                    } 
                }    
                if($debit[2]=="rounded_adjustment"){ 
                    if($roundedadjustment < 0){
                       
                        $debitamount=$roundedadjustment*-1;
                    }
                    
                }
                if(defined('LOYALTY_VOUCHER')){                    
                    if(LOYALTY_VOUCHER==TRUE){
                        if($debit[2]=="loyalty_amount"){
                            if($loyaltyused>0){ //if discount is actually loyalty points
                                $debitamount= 0;
                            
                                //see if we need to bring the loyalty points in from HO
                                $my_business = $this->check_if_ho();
                                //bring the points from ho
                                if($my_business != $this->session->userdata('businessid')){
                                    $this->bring_in_ho_points($my_business, $loyaltyused, $loyaltyearned, $customer_id, $customername, $invoiceid);
                                }   

                                $this->create_loyalty_used_voucher($this->session->userdata('businessid'),$loyaltyused, $loyaltyearned, $customer_id, $customername, $invoiceid);
                                $debitamount= 0; // make sure
                            }                 
                        }
                    }
                }
                
                $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]=="grosstotal_service"){$creditamount= $org_subtotal + $other_charges ;}
                
                if($credit[2]=="sales_tax"){$creditamount= $taxtotal;}
                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;}
                if($credit[2]=="rounded_adjustment"){ 
                    if($roundedadjustment > 0){
                        
                        $creditamount=$roundedadjustment; 
                    }
                    
                }
                $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);
                }
            }

            ///create loyalty voucher
            if(defined('LOYALTY_VOUCHER')){                    
                if(LOYALTY_VOUCHER==TRUE){
                    if($loyaltyearned > 0){
                        $my_business= $this->check_if_ho();            
                        $this->add_loyalty_points_ho($my_business, $loyaltyused, $loyaltyearned, $customer_id, $customername, $invoiceid);
                    }
                }
            }
        }
    }
    
    function get_visit_products($id_visit_services){
//        $variables = [$id_visit_services, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}

        
        
        //Get visit service products        
            $this->db->select('*');
           // $this->db->where('customer_visit_id', $visitid);
            $this->db->where('visit_service_id', $id_visit_services);
            $query = $this->db->get('visit_service_products');
            
            return $query->result_array();
    }
    
    function updateinvoicenumber($invoiceid,$paymentmode='Cash'){
//        $variables = [$invoiceid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}


        $business= $this->business_model->get_business_details();
        //make sure invoice number is correct
        $today=date('Y-m-d');
        
        $seq=1;        
        $sql = "select max(invoice_seq)+1 as 'seq'
            from invoice where day(invoice_date)= day('".$today."') 
            and month(invoice_date)= month('".$today."') and year(invoice_date)= year('".$today."')";
        $query = $this->db->query($sql);
        $invoice_seq =  $query->row();
        if(isset($invoice_seq) && null !== $invoice_seq->seq){$seq=$invoice_seq->seq;}
        if($paymentmode!=='Card' && $paymentmode!=='Mixed' && $business[0]['sh_hide']=='Yes'){
            $seq=0;
        }
            
        $update_invoice = array(
            'invoice_number' => date('Y-m').'-'.$invoiceid,
            'invoice_seq' => $seq
        );            
        $this->db->where(array(
            'business_id' => $this->session->userdata('businessid'),
            'id_invoice' => $invoiceid
        ));
        $this->db->update('invoice', $update_invoice);
        
        return $seq;
    }
    
    function insert_invoice_taxes($invoiceid,$taxname, $tax){
//        $variables = [$invoiceid, $this->session->userdata('businessid')];
//        $fine = $this->checkvariables($variables);
//        if($fine == false){  return array('mes'=>'missing data'); exit();}

        $data=array(
            'invoice_id'=>$invoiceid,
            'business_id'=>$this->session->userdata('businessid'),
            'invoice_tax_name'=>$taxname,
            'invoice_tax'=>$tax
        );
        $this->db->insert('invoice_taxes', $data);
        
    }
    
    function insert_invoice_products($invoiceid, $visitid, $serviceid, $servicename, $id_business_products, $product, $usage_qty, $measure_unit){
        
        $data = array(
            'business_id' => $this->session->userdata('businessid'),
            'invoice_id' => $invoiceid,
            'customer_visit_id' => $visitid,
            'service_id' => $serviceid,
            'service_name' => $servicename,
            'product_id' => $id_business_products,
            'product_name' => $product,
            'product_qty' => $usage_qty,
            'product_unit' => $measure_unit
        );
        $this->db->insert('invoice_visit_products', $data);
        
    }
    
    function update_visit_status($visitid, $seq=0){
        
        $this->db->set('visit_status', 'invoiced');
        $this->db->set('invoice_seq', $seq);
        $this->db->where('id_customer_visits', $visitid);
        $this->db->update('customer_visits');
        
    }
    
    function updatecustomeradvance($customerid, $keepadv, $remaining_retained, $returnamount){
        if ($keepadv==='true'){
            $newval=$returnamount + $remaining_retained;
        } else {
            $newval=$remaining_retained;
        }
        $this->db->set('customer_advance', $newval);
        $this->db->where('id_customers',$customerid);
        $this->db->update('customers');
        
        return $this->db->affected_rows();
    }
 
   

    function cancelVisit($customer_visit_id, $cancelled_by, $cancelreason='', $event_id=0){
        
        
        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);
        
        if($event_id==0){
            $query = $this->db->update('customer_visits', array('visit_status' => 'canceled', 'cancelreason' => $cancelreason, 'canceled_by' => $this->session->userdata('username')));
            
        } else {
            $query = $this->db->update('customer_visits', array('visit_status' => 'AdvKeptcanceled', 'cancelreason' => $cancelreason, 'canceled_by' => $this->session->userdata('username')));
            
        }
        
        //create auto account voucher       
        if($this->session->userdata('auto_voucher')=='Yes' && $event_id > 0){
            
            $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;
            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;
            } 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;
            }
            
            $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'=>3,
                '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 true;
    }
    
    function checkvariables($variables){
        $result=true;
        foreach($variables as $var){
            if(null == $var && $var == ''){
                $result=false;
            }
        }
        return $result;
    }
    
    function get_untracked_products(){

        $this->db->select('*, id_business_products as id, product as text');
        $this->db->join('business_brands','business_brands.id_business_brands = business_products.brand_id');
        if($this->session->userdata('common_products')=='No'){
            $this->db->where('business_brands.business_id', $this->session->userdata('businessid', TRUE));
        }
        
        $this->db->where('track_inventory', 'No');
        $this->db->order_by('business_brand_name, product', 'Asc');
        $query = $this->db->get('business_products');
        
        return $query->result_array();
    }
    
    
    function search_untracked_products(){

        $phrase=  strtoupper( $this->input->get('productname'));
        $match = explode(' ',$phrase);
        
        $phrase =  str_replace(' ','%',$phrase);
        
        $sql = " select *, id_business_products as id, product from business_products 
        join business_brands on business_brands.id_business_brands = business_products.brand_id
        ";
        if($this->session->userdata('common_products')=='No'){
            $sql .= " where business_brands.business_id = " . $this->session->userdata('businessid', TRUE);
        }        
        $sql .= " and business_products.track_inventory = 'No' ";
        $sql .= " and (upper(concat(business_brand_name,' ', product,' ', IFNULL(business_products.category, '') )) LIKE '%".$phrase."%' 
                OR  upper(concat(product,' ', business_brand_name,' ', IFNULL(business_products.category, '') )) LIKE '%".$phrase."%' 
                OR  upper(concat(product,' ', IFNULL(business_products.category, '') ,' ', business_brand_name)) LIKE '%".$phrase."%' 
                OR  upper(concat(IFNULL(business_products.category, '') , ' ', product, ' ', business_brand_name)) LIKE '%".$phrase."%' 
                OR  upper(concat(business_brand_name, ' ', IFNULL(business_products.category, '') , ' ', product)) LIKE '%".$phrase."%' 
                OR  IFNULL(business_products.barcode_products, '') like '%".$phrase."%'
                OR  IFNULL(business_products.sku, '') like '%".$phrase."%'    
                OR  upper(id_business_products) LIKE '%".$phrase."%' )";
        
        
        $sql .= " order by  business_brand_name, product, 'Asc'";
        $query = $this->db->query($sql);
//       / echo $sql;
        return $query->result_array();
    }

    function check_if_ho(){
        $my_business= $this->session->userdata('businessid');
        if($this->session->userdata('common_products')=='Yes'){
            $sqlb="select id_business from business where business.ho='Yes'";
            $b=$this->db->query($sqlb);
            $ho=$b->row();
            if($ho){
                $my_business= $ho->id_business;
            }
        }
       
        return $my_business;
    }

    function bring_in_ho_points($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid){
        ///create voucher in ho
        $data = array( 
            'business_id' => $my_business,
            'description' => 'Loyalty Points Moved to Branch '.$this->session->userdata('businessid').' against invoice ' . $invoiceid . ' on '. date('d-m-Y').', For '.$customername.' customer ID : '. $customerid,
            'voucher_date' => date('Y-m-d H:i:s'),
            'voucher_amount' => $loyaltyused,
            'voucher_status' => 'Active',
            'created_by' => $this->session->userdata('username'),
            'cost_center'=> '1',
            'cost_center_name'=> 'Front Desk',
            'business_partner'=> 1,
            'business_partner_id'=>$customerid,
            'business_partner_name'=>$customername,
            'voucher_type'=>3,
            'payment_mode'=>'Cash',
            'bank_name'=>'',
            'invoice_id'=>$invoiceid,
            'auto_voucher'=>'Yes'                            
        );            
        $this->db->insert('account_vouchers', $data);
        $account_voucherid =  $this->db->insert_id();        

        $account_heads = $this->accounting_model->get_mapped_accounts(4,$my_business);     
        $debit_accounts  =[];
        $credit_accounts  =[];
        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='';
        //enter detail entries
        foreach($debit_accounts as $debit_account){
            $debitamount=0;
            $debit = explode("|", $debit_account);
            //check entity
            if($debit[2]=="loyalty_expense"){$debitamount= $loyaltyused;}
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $debit[0],                
                'credit' => round($debitamount,2), //reverse entry
                'debit' => 0
            );
            //insert debit detail
            if($debitamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }
        }
        foreach($credit_accounts as $credit_account){
            $creditamount=0;
            $credit = explode("|", $credit_account);
            //check entity                
            if($credit[2]=="loyalty_amount"){$creditamount= $loyaltyused;}
            $data_detail=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $credit[0],                
                'credit' => 0,
                'debit' => round($creditamount,2) //reverse entry
            );
            //insert credit detail
            if($creditamount>0){
                $this->db->insert('account_voucher_detail', $data_detail);
            }
        }


        ///////create voucher in your own branch
        $data = array( 
            'business_id' => $this->session->userdata('businessid'),
            'description' => 'Loyalty Points Moved From HO to Branch '.$this->session->userdata('businessid').' against invoice ' . $invoiceid . ' on '. date('d-m-Y').', For '.$customername.' customer ID : '. $customerid,
            'voucher_date' => date('Y-m-d H:i:s'),
            'voucher_amount' => $loyaltyused,
            'voucher_status' => 'Active',
            'created_by' => $this->session->userdata('username'),
            'cost_center'=> '1',
            'cost_center_name'=> 'Front Desk',
            'business_partner'=> 1,
            'business_partner_id'=>$customerid,
            'business_partner_name'=>$customername,
            'voucher_type'=>3,
            'payment_mode'=>'Cash',
            'bank_name'=>'',
            'invoice_id'=>$invoiceid,
            'auto_voucher'=>'Yes'                            
        );            
        $this->db->insert('account_vouchers', $data);
        $account_voucherid =  $this->db->insert_id();        

        $account_heads = $this->accounting_model->get_mapped_accounts(4,$this->session->userdata('businessid'));     
        $debit_accounts  =[];
        $credit_accounts  =[];
        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='';
        //enter detail entries
        foreach($debit_accounts as $debit_account){
            $debitamount=0;
            $debit = explode("|", $debit_account);
            //check entity
            if($debit[2]=="loyalty_expense"){$debitamount= $loyaltyused;}
            $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);
            }
        }
        foreach($credit_accounts as $credit_account){
            $creditamount=0;
            $credit = explode("|", $credit_account);
            //check entity                
            if($credit[2]=="loyalty_amount"){$creditamount= $loyaltyused;}
            $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);
            }
        }
    }
    
    function create_loyalty_used_voucher($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid){

        $sql1="SELECT account_head_id, entity_name FROM account_event_mapping
        where account_event_id = 1 and entity_name = 'loyalty_amount' 
        and business_id=".$this->session->userdata('businessid')." ;";
        $query=$this->db->query($sql1);
        $result1 = $query->row();
        $loyalty_ah = $result1->account_head_id;

        $sql2="SELECT account_head_id, entity_name FROM account_event_mapping
        where account_event_id = 4 and entity_name = 'loyalty_expense' 
        and business_id=".$this->session->userdata('businessid')." ;";
        $query=$this->db->query($sql2);
        $result2= $query->row();
        $expense_ah = $result2->account_head_id;

        ////create loyalty used voucher
        if($loyaltyused>0){
            $data = array( 
                'business_id' => $my_business,
                'description' => 'Loyalty Points Used for discount on invoice ' . $invoiceid . ' on '. date('Y-m-d') .', For '.$customername.' customer ID : '. $customerid,
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $loyaltyused,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$customerid,
                'business_partner_name'=>$customername, 
                'voucher_type'=>3,
                'payment_mode'=>'Cash',
                'bank_name'=>'',
                'invoice_id'=>$invoiceid,
                'auto_voucher'=>'Yes'                        
            );            
            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();        
    
            $data_debit=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $expense_ah,
                'credit' => round($loyaltyused,2), //reverse
                'debit' => 0
            );
            $this->db->insert('account_voucher_detail', $data_debit);

            
            $data_credit=array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $loyalty_ah,
                'credit' => 0,
                'debit' => round($loyaltyused,2) //reverse
            );
            $this->db->insert('account_voucher_detail', $data_credit);


        }
    }

    function add_loyalty_points_ho($my_business, $loyaltyused, $loyaltyearned, $customerid, $customername, $invoiceid){
        ///create voucher in ho
        $account_heads = $this->accounting_model->get_mapped_accounts(4, $my_business);    
        $debit_accounts  =[];
        $credit_accounts  =[];        
        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='';

        $data = array( 
            'business_id' => $my_business,
            'description' => 'Loyalty Points Earned against invoice ' . $invoiceid . ' on '. date('d-m-Y').', By '.$customername.' customer ID : '. $customerid,
            'voucher_date' => date('Y-m-d H:i:s'),
            'voucher_amount' => $loyaltyearned,
            'voucher_status' => 'Active',
            'created_by' => $this->session->userdata('username'),
            'cost_center'=> '1',
            'cost_center_name'=> 'Front Desk',
            'business_partner'=> 1,
            'business_partner_id'=>$customerid,
            'business_partner_name'=>$customername,
            'voucher_type'=>3,
            'payment_mode'=>'Cash',
            'bank_name'=>$bank_name,
            'invoice_id'=>$invoiceid,
            'auto_voucher'=>'Yes',
            'sale_type'=>'loyalty'
        );

        $this->db->insert('account_vouchers', $data);
        $account_voucherid =  $this->db->insert_id();
        
        //enter detail entries
        foreach($debit_accounts as $debit_account){
            $debitamount=0;
            $debit = explode("|", $debit_account);
            //check entity
            if($debit[2]=="loyalty_expense"){$debitamount= $loyaltyearned;}
            $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);
            }
        }
        foreach($credit_accounts as $credit_account){
            $creditamount=0;
            $credit = explode("|", $credit_account);
            //check entity                
            if($credit[2]=="loyalty_amount"){$creditamount= $loyaltyearned;}     
            $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);
            }
        }
    }

    
}