<?php

class Tools extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // Your own constructor code
        $this->load->model('business_model');
        $this->load->model('tools_model');
        $this->load->model('sms_model');
    }

    public function get_scheduled_tasks() {

        $business_id = 1;
        $st = $this->tools_model->get_scheduled_tasks();
        //echo 'do it bro';
        foreach ($st as $task) {
            //echo $task['task_name'];


            if (isset($task['channel'])) {
                echo $task['channel'];
                if ($task['channel'] == 'email') { //email
                    if (strtolower(substr($task['s_query'], 0, 6)) === "select") {
                        $data = $this->tools_model->run_query($task['s_query']);
                        $fields = $data['fields'];
                        $resultset = $data['resultset'];

                        $emails = [];
                        foreach ($resultset as $row) {
                            echo '<pre>';
                            print_r($row);
                            echo '</pre>';
                            exit();
                        }
                    }
                } elseif($task['channel']  == "sms") { //sms
                    if (strtolower(substr($task['s_query'], 0, 6)) === "select") {
                        $data = $this->tools_model->run_query($task['s_query']);
                        $fields = $data['fields'];
                        $resultset = $data['resultset'];

                        $customer_cell = '';
                        foreach ($resultset as $row) {
                            if ($row['customer_cell'] !== $customer_cell) {
                               // echo 'sending  to ' . $row['customer_name'];
                                $msg = str_replace('$name$', $row['customer_name'], $task['msg']);
                                $business_id = 1;
                                if (isset($row['visit_date']) && null !== $row['visit_date']) {

                                    $date = date_create($row['visit_date']);
                                    $visit_day = $date->format('dS');
                                    $visit_month = $date->format('M');

                                    if ($date->format('g:i A') !== '12:00 AM') {
                                        $visit_time = $date->format('g:i A');
                                        $final_date = $visit_day . ' of ' . $visit_month . ' at ' . strtolower($visit_time);
                                    } else {
                                        $final_date = $visit_day . ' of ' . $visit_month;
                                    }

                                    $msg = str_replace('$date$', $final_date, $msg);
                                } else {
                                    $msg = str_replace('$date$', date('d-m-Y'), $msg);
                                }


                                if (isset($row['service_name']) && null !== $row['service_name']) {
                                    $msg = str_replace('$service$', $row['service_name'], $msg);
                                } else {
                                    $msg = str_replace('$service$', ' ', $msg);
                                }


                                if (isset($row['business']) && null !== $row['business']) {
                                    $msg = str_replace('$business$', $row['business'], $msg);
                                } else {
                                    $msg = str_replace('$business$', ' ', $msg);
                                }

                                if (isset($row['id_business']) && null !== $row['id_business']) {
                                    $business_id = $row['id_business'];
                                } else {
                                    $business_id = 1;
                                }

                                if (isset($row['contact']) && null !== $row['contact']) {
                                    $msg = str_replace('$contact$', $row['contact'], $msg);
                                } else {
                                    $msg = str_replace('$contact$', ' ', $msg);
                                }
                                $this->sms_model->send_sms($msg, $row['customer_cell'], false, 'ScheduledTask', false, $business_id);                                

                                $customer_cell = $row['customer_cell'];

                                if (isset($row['update_status']) && null !== $row['update_status']) {
                                    if (isset($row['visit_id']) && null !== $row['visit_id'])
                                        $this->sms_model->update_status($row['visit_id']);
                                }                       
                              
                            }
                        }
                    }
                
                } else if ($task['channel'] == 'whatsapp'){ 
                    echo 'Chanel=whatsapp inside';
                    $data = $this->tools_model->run_query($task['s_query']);
                        $fields = $data['fields'];
                        $resultset = $data['resultset'];
                        echo '<pre>';
                        print_r($resultset);
                        $customer_cell = '';
                        foreach ($resultset as $row) {
                            $msg = str_replace('$name$', $row['customer_name'], $task['msg']);
                            $business_id = 1;
                            if (isset($row['visit_date']) && null !== $row['visit_date']) {
                                $date = date_create($row['visit_date']);
                                $visit_day = $date->format('dS');
                                $visit_month = $date->format('M');
                                if ($date->format('g:i A') !== '12:00 AM') {
                                    $visit_time = $date->format('g:i A');
                                    $final_date = $visit_day . ' of ' . $visit_month . ' at ' . strtolower($visit_time);
                                } else {
                                    $final_date = $visit_day . ' of ' . $visit_month;
                                }
                                $msg = str_replace('$date$', $final_date, $msg);
                            } else {
                                $msg = str_replace('$date$', date('d-m-Y'), $msg);
                            }
                            if (isset($row['service_name']) && null !== $row['service_name']) {
                                $msg = str_replace('$service$', $row['service_name'], $msg);
                            } else {
                                $msg = str_replace('$service$', ' ', $msg);
                            }
                            if (isset($row['business']) && null !== $row['business']) {
                                $msg = str_replace('$business$', $row['business'], $msg);
                            } else {
                                $msg = str_replace('$business$', ' ', $msg);
                            }
                            if (isset($row['id_business']) && null !== $row['id_business']) {
                                $business_id = $row['id_business'];
                            } else {
                                $business_id = 1;
                            }
                            if (isset($row['contact']) && null !== $row['contact']) {
                                $msg = str_replace('$contact$', $row['contact'], $msg);
                            } else {
                                $msg = str_replace('$contact$', ' ', $msg);
                            }
                        
                            $wa_phone = $row['customer_cell'];
                            if (preg_match('/^0(\d{10})$/', $row['customer_cell'], $matches)) {
                                $wa_phone = '+92' . $matches[1]; // Replace '0' with '+92'
                            }

                            $data = array(                                      
                                'text_msg'=> '😀 '.$msg,
                                'business_id'=>$business_id,
                                'receiver'=> $wa_phone,
                                'msg_type'=> 'ScheduledTask'
                            );
                            $this->db->insert('wa_msg_list', $data);
                        }
                
                }
            } else { //channel field not available
                if (strtolower(substr($task['s_query'], 0, 6)) === "select") {
                    $data = $this->tools_model->run_query($task['s_query']);
                    $fields = $data['fields'];
                    $resultset = $data['resultset'];

                    $customer_cell = '';
                    foreach ($resultset as $row) {
                        if ($row['customer_cell'] !== $customer_cell) {
                            //echo 'sending  to ' . $row['customer_name'];
                            $msg = str_replace('$name$', $row['customer_name'], $task['msg']);
                            $business_id = 1;
                            if (isset($row['visit_date']) && null !== $row['visit_date']) {

                                $date = date_create($row['visit_date']);
                                $visit_day = $date->format('dS');
                                $visit_month = $date->format('M');

                                if ($date->format('g:i A') !== '12:00 AM') {
                                    $visit_time = $date->format('g:i A');
                                    $final_date = $visit_day . ' of ' . $visit_month . ' at ' . strtolower($visit_time);
                                } else {
                                    $final_date = $visit_day . ' of ' . $visit_month;
                                }

                                $msg = str_replace('$date$', $final_date, $msg);
                            } else {
                                $msg = str_replace('$date$', date('d-m-Y'), $msg);
                            }


                            if (isset($row['service_name']) && null !== $row['service_name']) {
                                $msg = str_replace('$service$', $row['service_name'], $msg);
                            } else {
                                $msg = str_replace('$service$', ' ', $msg);
                            }


                            if (isset($row['business']) && null !== $row['business']) {
                                $msg = str_replace('$business$', $row['business'], $msg);
                            } else {
                                $msg = str_replace('$business$', ' ', $msg);
                            }

                            if (isset($row['id_business']) && null !== $row['id_business']) {
                                $business_id = $row['id_business'];
                            } else {
                                $business_id = 1;
                            }

                            if (isset($row['contact']) && null !== $row['contact']) {
                                $msg = str_replace('$contact$', $row['contact'], $msg);
                            } else {
                                $msg = str_replace('$contact$', ' ', $msg);
                            }

                            $this->sms_model->send_sms($msg, $row['customer_cell'], false, 'ScheduledTask', false, $business_id);
                            //echo ($msg." , ". $row['customer_cell']); exit();

                            $customer_cell = $row['customer_cell'];

                            if (isset($row['update_status']) && null !== $row['update_status']) {
                                if (isset($row['visit_id']) && null !== $row['visit_id'])
                                    $this->sms_model->update_status($row['visit_id']);
                            }
                        }
                    }
                }
            }
        }
    }
    
    
     
    public function sync_inventory(){
        
        
        
        
        $brands = json_decode($this->get_remote_data('brands',''));
        //print_r(json_decode($brands)); exit();
        $brandx=0;$brandy=0;
        if(!empty($brands)){
            foreach($brands as $brand){
            
            $this->db->select("id_business_brands");
            $this->db->where("id_business_brands", $brand->id_business_brands);
            $query = $this->db->get('business_brands');
            
            $my_brand = $query->row();
            
            if($my_brand != ''){
                if($my_brand->id_business_brands == $brand->id_business_brands){
                    //echo 'update';
                    $this->db->where('id_business_brands', $brand->id_business_brands);
                    $this->db->set('business_brand_name', $brand->business_brand_name);
                    $this->db->set('business_brand_short', $brand->business_brand_short);
                    $this->db->set('business_brand_website', $brand->business_brand_website);
                    $this->db->set('business_brand_active', $brand->business_brand_active);
                    
                    $this->db->update('business_brands');
                    $brandy++;
                }else{
                    //echo 'insert';
                    $data = array(
                        'id_business_brands'=>$brand->id_business_brands,
                        'business_brand_name'=>$brand->business_brand_name,
                        'business_brand_short'=>$brand->business_brand_short,
                        'business_brand_website'=>$brand->business_brand_website,
                        'business_brand_active'=>$brand->business_brand_active,
                        'business_id'=>1
                    );
                    $this->db->insert('business_brands', $data);
                    $brandx++;
                }
            }else{
                $data = array(
                    'id_business_brands'=>$brand->id_business_brands,
                    'business_brand_name'=>$brand->business_brand_name,
                    'business_brand_short'=>$brand->business_brand_short,
                    'business_brand_website'=>$brand->business_brand_website,
                    'business_brand_active'=>$brand->business_brand_active,
                    'business_id'=>1
                );
                $this->db->insert('business_brands', $data);
                $brandx++;
            }
        }
        }
        echo 'Brands Updated : '.$brandy.'<br>';
        echo 'Brands inserted :'.$brandx.'<br>';
        
        
        $products = json_decode($this->get_remote_data('products',''));
        //print_r($products);
        $productx=0;$producty=0;
        if(!empty($products)){
            foreach($products as $product){
            
            $this->db->select("id_business_products");
            $this->db->where("id_business_products", $product->id_business_products);
            $query = $this->db->get('business_products');
            
            $my_products = $query->row();
            
            if($my_products != ''){
                if($my_products->id_business_products == $product->id_business_products){
                    $this->db->where('id_business_products', $product->id_business_products);
                    $this->db->set('brand_id', $product->brand_id);
                    $this->db->set('product', $product->product);
                    $this->db->set('sku', $product->sku);
                    $this->db->set('price', $product->price);
                    $this->db->set('purchase_price', $product->purchase_price);
                    $this->db->set('in_stock', $product->in_stock);
                    $this->db->set('inhouse_stock', $product->inhouse_stock);
                    $this->db->set('unit_type', $product->unit_type);
                    $this->db->set('measure_unit', $product->measure_unit);
                    $this->db->set('qty_per_unit', $product->qty_per_unit);
                    $this->db->set('business_product_active', $product->business_product_active);
                    $this->db->set('category', $product->category);
                    $this->db->set('professional', $product->professional);
                    $this->db->set('opening_inhouse', $product->opening_inhouse);
                    $this->db->set('opening_date', $product->opening_date);
                    $this->db->set('product_threshold', $product->product_threshold);
                    $this->db->set('barcode_products', $product->barcode_products);
                    $this->db->set('commission', $product->commission);
                    $this->db->set('product_type', $product->product_type);
                    
                    $this->db->update('business_products');
                    $producty++;
                    
                }else{
                    
                    $data=array(
                       'id_business_products'=>$product->id_business_products , 
                        'business_id'=>1, 
                        'brand_id'=>$product->brand_id , 
                        'product'=>$product->product , 
                        'sku'=>$product->sku , 
                        'price'=> $product->price , 
                        'purchase_price'=> $product->purchase_price, 
                        'in_stock'=>$product->in_stock , 
                        'inhouse_stock'=> $product->inhouse_stock, 
                        'unit_type'=> $product->unit_type, 
                        'measure_unit'=> $product->measure_unit, 
                        'qty_per_unit'=>$product->qty_per_unit , 
                        'business_product_active'=> $product->business_product_active, 
                        'category'=> $product->category, 
                        'professional'=> $product->professional, 
                        'opening_inhouse'=> $product->opening_inhouse,                         
                        'opening_date'=> $product->opening_date, 
                        'product_threshold'=>$product->product_threshold , 
                        'barcode_products'=>$product->barcode_products , 
                        'commission'=> $product->commission, 
                        'product_type'=> $product->product_type
                        
                    );
                    
                    
                    $this->db->insert('business_products', $data);
                    $productx++;
                }
            }else {
                $data=array(
                       'id_business_products'=>$product->id_business_products , 
                        'business_id'=>1 , 
                        'brand_id'=>$product->brand_id , 
                        'product'=>$product->product , 
                        'sku'=>$product->sku , 
                        'price'=> $product->price , 
                        'purchase_price'=> $product->purchase_price, 
                        'in_stock'=>$product->in_stock , 
                        'inhouse_stock'=> $product->inhouse_stock, 
                        'unit_type'=> $product->unit_type, 
                        'measure_unit'=> $product->measure_unit, 
                        'qty_per_unit'=>$product->qty_per_unit , 
                        'business_product_active'=> $product->business_product_active, 
                        'category'=> $product->category, 
                        'professional'=> $product->professional, 
                        'opening_inhouse'=> $product->opening_inhouse,                         
                        'opening_date'=> $product->opening_date, 
                        'product_threshold'=>$product->product_threshold , 
                        'barcode_products'=>$product->barcode_products , 
                        'commission'=> $product->commission, 
                        'product_type'=> $product->product_type
                        
                    );
                $this->db->insert('business_products', $data);
                $productx++;
            }
        }
        }
        echo 'Products Updated : '.$producty.'<br>';
        echo 'Products inserted :'.$productx.'<br>';
        
        $this->db->select('*');
        $query = $this->db->get('business_stores');
        $stores = $query->result();
        //print_r($stores);
        foreach($stores as $store){
            $batches = json_decode($this->get_remote_data('batches','storeid='.$store->linked_store_id));
            // if($store->linked_store_id == 14){
            //     print_r($batches);
            //     exit();
            // }
            // $uu=false;
            // if($uu==true){
                $batchx=0; $batchy=0;
                if(!empty($batches)){
                    
                    foreach($batches as $batch){
                       
                
                        $this->db->select("id_batch");
                        $this->db->where("id_batch", $batch->id_batch);
                        $query = $this->db->get('product_batch');
    
                        $my_batch = $query->row();
    
                        if($my_batch != ''){
                            if($my_batch->id_batch == $batch->id_batch){
                                $this->db->where('id_batch', $batch->id_batch);
                                $this->db->set('product_id', $batch->product_id);
                                $this->db->set('batch_number', $batch->batch_number);
                                $this->db->set('batch_date', $batch->batch_date);
                                $this->db->set('expiry_date', $batch->expiry_date);
                                $this->db->set('batch_qty', $batch->batch_qty);
                                $this->db->set('store_id', $store->id_business_stores);
                                $this->db->set('batch_amount', $batch->batch_amount);
    
                                $this->db->update('product_batch');
                                $batchy++;
    
                            }else{
                                $data=array(
                                    'id_batch'=>$batch->id_batch,
                                    'product_id'=>$batch->product_id,
                                    'batch_number'=>$batch->batch_number,
                                    'batch_date'=>$batch->batch_date,
                                    'expiry_date'=>$batch->expiry_date,
                                    'batch_qty'=>$batch->batch_qty,
                                    'store_id'=>$store->id_business_stores,
                                    'batch_amount'=>$batch->batch_amount
                                );
                                $this->db->insert('product_batch', $data);
                                $batchx++;
                            }
                        }else {
                            $data=array(
                                'id_batch'=>$batch->id_batch,
                                'product_id'=>$batch->product_id,
                                'batch_number'=>$batch->batch_number,
                                'batch_date'=>$batch->batch_date,
                                'expiry_date'=>$batch->expiry_date,
                                'batch_qty'=>$batch->batch_qty,
                                'store_id'=>$store->id_business_stores,
                                'batch_amount'=>$batch->batch_amount
                            );
                            $this->db->insert('product_batch', $data);
                            $batchx++;
                        }
                    }
                }
            //}
            
            echo 'Batches Updated in '.$store->id_business_stores.' '.$store->business_store.': '.$batchy.'<br>';
            echo 'Batches Inserted in '.$store->id_business_stores.' '.$store->business_store.':'.$batchx.'<br>';
        }
        
        $last_update_date = '';
        
        foreach($stores as $store){
            $transfernotes = json_decode($this->get_remote_data('transfernotes','storeid='.$store->linked_store_id));
            //print_r($store->linked_store_id);
            
           
            $transferx=0; $transfery=0;
            
            if(!empty($transfernotes)){
                // echo '<pre>';
                //  print_r($transfernotes); exit();
                foreach($transfernotes as $transfernote){
                    $this->db->select("id_transfer_notes");
                    $this->db->where("remote_transfer_id", $transfernote->id_transfer_notes);
                    $query = $this->db->get('transfer_notes');

                    $last_update_date = $transfernote->last_updated;

                    $my_transfernote = $query->row();

                    if($my_transfernote!=''){
                       $this->db->where('remote_transfer_id', $transfernote->id_transfer_notes);
                       $data=array(
                            'remote_transfer_id'=>$transfernote->id_transfer_notes,
                            
                            'product_id'=>$transfernote->product_id,
                            'tranfer_in_qty'=>$transfernote->tranfer_in_qty,
                            'transfer_date'=>$transfernote->transfer_date,
                            'created_by'=>$transfernote->created_by,
                            'status'=>$transfernote->status,
                            'batch'=>$transfernote->batch,
                            'batch_id'=>$transfernote->batch_id
                        );
                        $this->db->update('transfer_notes',$data);
                       $transferx++;
                           
                    }else{
                        $data1 = array(
                            //'id_gtn'=> $transfernote->id_gtn,
                            'gtn_number'=> $transfernote->gtn_number,
                            'gtn_date'=> $transfernote->gtn_date,
                            'created_by'=> $transfernote->created_by,
                            'created_on'=> $transfernote->created_on,
                            'business_id'=> $transfernote->business_id,
                            'comments'=> $transfernote->comments,
                            'to_store'=> $transfernote->to_store
                        );
                         $this->db->insert('gtn',$data1);
                         $gtn_id = $this->db->insert_id();

                        $data=array(
                                'remote_transfer_id'=>$transfernote->id_transfer_notes,
                                'business_id'=>1,
                                'gtn_id'=>$gtn_id,
                                'product_id'=>$transfernote->product_id,
                                'tranfer_in_qty'=>$transfernote->tranfer_in_qty,
                                'transfer_date'=>$transfernote->transfer_date,
                                'created_by'=>$transfernote->created_by,
                                'status'=>$transfernote->status,
                                'batch'=>$transfernote->batch,
                                'batch_id'=>$transfernote->batch_id
                            );
                            $this->db->insert('transfer_notes',$data);
                            
                            $transferx++;
                    }
                }      
                echo 'Transfer Notes Updated in store '.$store->id_business_stores.' '.$store->business_store.': '.$transfery.'<br>';
                echo 'Transfer Notes Inserted in store '.$store->id_business_stores.' '.$store->business_store.': '.$transferx.'<br>';
                // if($last_update_date!=''){
                //     $data=array('last_updated'=>$last_update_date);
                //     //$this->db->where('id', 1);
                //     $this->db->update('rest_keys', $data);
                // }
            }            
        }
        
        if($last_update_date!=''){
            $data=array('last_updated'=>$last_update_date);
            //$this->db->where('id', 1);
            $this->db->update('rest_keys', $data);
        }
        
    }
    
   
    
    
    public function get_remote_data($function, $param){
        
        $this->db->select('last_updated, inventory_server');
        $query = $this->db->get('rest_keys');
        $dt_data = $query->row();
        
        $lastupdated = $dt_data->last_updated;
        $inventory_server = $dt_data->inventory_server;
        
       // echo $lastupdated;
        
        $url = $inventory_server.$function.'?';
        if($param != ''){
            $url = $url.$param.'&';
        }
        if($lastupdated!=''){
            $url = $url.'lastupdated='. urlencode($lastupdated);
        }
        
        $curl = curl_init();   
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_FAILONERROR, 0);
        curl_setopt($curl, CURLOPT_POST, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1); // Skip SSL Verification
        
        //curl_setopt($curl, CURLOPT_POSTFIELDS, $myJSON);
        
        $agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36';
        //Set your auth headers 
        
        $authorization = 'SKED-API-KEY: $kedw!$e-8547-65265-7444-12';
        
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: */*', 'Connection: keep-alive', 'User-Agent: '.$agent, $authorization));
        //curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
       // curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
        curl_setopt($curl, CURLINFO_HEADER_OUT, true);
       // curl_setopt($curl, CURLOPT_USERAGENT, $agent);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 40); 
        curl_setopt($curl, CURLOPT_TIMEOUT, 40); //timeout in seconds
        
        //$result = curl_exec($curl);
        if (curl_exec($curl) === FALSE) {
           $info = curl_getinfo($curl);
           print_r($info['request_header']);
           die("Curl Failed: " . curl_error($curl));
        } else {
           $result = curl_exec($curl);
           $info = curl_getinfo($curl);
           //print_r($info['request_header']);
           curl_close($curl);
           
          // echo 'result is:'.$result;
           return $result;
           exit;
        }
        
    }


    public function create_loyalty_vouchers(){
        $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;

        $sqlinvoice="SELECT id_invoice, customer_id, customer_name, 
            date(invoice_date) as invoice_date, payment_mode, invoice.invoice_type, invoice_status, created_by,
            invoice_status, loyalty_earned, loyalty_used, 
            loyalty_earned-loyalty_used as loyalty
            FROM invoice 
            WHERE  loyalty_used>0 Or loyalty_earned>0";
        $query=$this->db->query($sqlinvoice);
        $invoices = $query->result_array();
       
        $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;
            }
        }

        foreach($invoices as $invoice){
            if($invoice['loyalty_earned']>0){
                /// loyalty earned
                $data = array( 
                    'business_id' => $my_business,
                    'description' => 'Loyalty Points Earned against invoice ' . $invoice['id_invoice'] . ' on '.$invoice['invoice_date'].', for '.$invoice['customer_name'].' customer ID : '. $invoice['customer_id'],
                    'voucher_date' => $invoice['invoice_date'],
                    'voucher_amount' => $invoice['loyalty'],
                    'voucher_status' => 'Active',
                    'created_by' => $invoice['created_by'],
                    'cost_center'=> '1',
                    'cost_center_name'=> 'Front Desk',
                    'business_partner'=> 1,
                    'business_partner_id'=>$invoice['customer_id'],
                    'business_partner_name'=>$invoice['customer_name'],
                    'voucher_type'=>2,
                    'payment_mode'=>$invoice['payment_mode'],
                    'bank_name'=>'',
                    'invoice_id'=>$invoice['id_invoice'],
                    'auto_voucher'=>'Yes',
                    'sale_type'=>$invoice['invoice_type'],
                    'voucher_status'=> $invoice['invoice_status']=='valid' ? 'Active' : 'Cancelled'
                );

                $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,
                    'debit' => round($invoice['loyalty_earned'],2),
                    'credit' => 0
                );
                $this->db->insert('account_voucher_detail', $data_debit);

                
                $data_credit=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $loyalty_ah,
                    'debit' => 0,
                    'credit' => round($invoice['loyalty_earned'],2)
                );
                $this->db->insert('account_voucher_detail', $data_credit);
            }

            ////create loyalty used voucher
            if($invoice['loyalty_used']>0){
                $data = array( 
                    'business_id' => $my_business,
                    'description' => 'Loyalty Points Used for discount on invoice ' . $invoice['id_invoice'] . ' on '. $invoice['invoice_date'] .', For '.$invoice['customer_name'].' customer ID : '. $invoice['customer_id'],
                    'voucher_date' => date('Y-m-d H:i:s'),
                    'voucher_amount' => $invoice['loyalty_used'],
                    'voucher_status' => 'Active',
                    'created_by' => $invoice['created_by'],
                    'cost_center'=> '1',
                    'cost_center_name'=> 'Front Desk',
                    'business_partner'=> 1,
                    'business_partner_id'=>$invoice['customer_id'],
                    'business_partner_name'=>$invoice['customer_name'],
                    'voucher_type'=>3,
                    'payment_mode'=>'Cash',
                    'bank_name'=>'',
                    'invoice_id'=>$invoice['id_invoice'],
                    'auto_voucher'=>'Yes',
                    'voucher_status'=> $invoice['invoice_status']=='valid' ? 'Active' : 'Cancelled'                            
                );            
                $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($invoice['loyalty_earned'],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($invoice['loyalty_earned'],2) //reverse
                );
                $this->db->insert('account_voucher_detail', $data_credit);

            }

        }

    }


    public function duplicate_packages(){


        $copy_from_business_id = $this->input->post('from_business');
        $copy_to_business_id = $this->input->post('to_business');

        $sql_type = "select * from package_type where business_id = 1;";
        $query_type = $this->db->query($sql_type);
        $type_data = $query_type->result_array();


        for($x=3; $x<=3; $x++){
            foreach($type_data as $type){
                //insert copy package_type record to business 2
                $data_type=array(
                    'business_id'=>$x,
                    'order_id'=>$type['order_id'],
                    'service_type'=>$type['service_type'],
                    'service_type_image'=>$type['service_type_image'],
                    'service_type_active'=>$type['service_type_active'],
                    'expiry_date'=>$type['expiry_date']
                );

                $this->db->insert('package_type', $data_type);
                $package_type_id = $this->db->insert_id();

                $sql_category = "select * from package_category where business_id=1 and package_type_id=".$type['id_package_type'];
                $query_category=$this->db->query($sql_category);
                $category_data = $query_category->result_array();

                foreach($category_data as $category){

                    $data_category=array(
                        'business_id'=>$x,
                        'package_type_id'=>$package_type_id,
                        'order_id'=>$category['order_id'],
                        'service_category'=>$category['service_category'],                        
                        'service_category_active'=>$category['service_category_active'],
                        'service_category_image'=>$category['service_category_image']
                    );
                    $this->db->insert('package_category', $data_category);
                    $package_category_id = $this->db->insert_id();

                    $sql_package_service = "select * from package_services where business_id=1 and package_category_id=".$category['id_package_category'].";";
                    $query_service =$this->db->query($sql_package_service);
                    $service_data = $query_service->result_array();

                    foreach($service_data as $service){

                        $data_service=array(
                            
                        );

                    }


                }



            }
        }


    }


    public function duplicate_services(){

        $copy_from_business_id = $this->input->post('from_business');
        $copy_to_business_id = $this->input->post('to_business');

        $sql_type = "select * from service_type where business_id = ".$copy_from_business_id;
        $query_type = $this->db->query($sql_type);
        $type_data = $query_type->result_array();


        //for($x=3; $x<=3; $x++){
            foreach($type_data as $type){
                //insert copy service_type record to business 2
                $data_type=array(
                    'business_id'=>$copy_to_business_id,
                    'order_id'=>$type['order_id'],
                    'service_type'=>$type['service_type'],
                    'service_type_image'=>$type['service_type_image'],
                    'service_type_active'=>$type['service_type_active']
                );

                $this->db->insert('service_type', $data_type);
                $package_type_id = $this->db->insert_id();

                $sql_category = "select * from service_category where business_id=".$copy_from_business_id." and service_type_id=".$type['id_service_types'];
                $query_category=$this->db->query($sql_category);
                $category_data = $query_category->result_array();

                foreach($category_data as $category){

                    $data_category=array(
                        'business_id'=>$copy_to_business_id,
                        'service_type_id'=>$package_type_id,
                        'order_id'=>$category['order_id'],
                        'service_category'=>$category['service_category'],                        
                        'service_category_active'=>$category['service_category_active'],
                        'service_category_image'=>$category['service_category_image']
                    );
                    $this->db->insert('service_category', $data_category);
                    $service_category_id = $this->db->insert_id();

                    $sql_service = "select * from business_services where business_id=".$copy_from_business_id." and service_category_id=".$category['id_service_category'].";";
                    $query_service =$this->db->query($sql_service);
                    $service_data = $query_service->result_array();

                    foreach($service_data as $service){

                        $data_service=array(
                            'service_category_id'=> $service_category_id,
                            'business_id'=> $copy_to_business_id,
                            'order_id'=> $service['order_id'],
                            'service_name'=> $service['service_name'],
                            'service_desc'=> $service['service_desc'],
                            'created_date'=> $service['created_date'],
                            'service_rate'=> $service['service_rate'],
                            'service_active'=> $service['service_active'],
                            'commission_perc'=> $service['commission_perc'],
                            'helper_perc'=> $service['helper_perc'],
                            'service_color'=> $service['service_color'],
                            'service_duration'=> $service['service_duration'],
                            'max_per_day'=> $service['max_per_day'],
                            'service_mode'=> $service['service_mode'],
                            'service_department'=> $service['service_department']
                        );
                        $this->db->insert('business_services', $data_service);
                        $service_id = $this->db->insert_id();

                        $sql_services_products = "select * from services_products where business_service_id=".$service_id;
                        $query_service_products = $this->db->query($sql_services_products);
                        $service_product_data = $query_service_products->result_array();

                        foreach($service_product_data as $service_product){
                            $data_service_products = array(
                                'business_service_id'=>$service_id,
                                'business_product_id'=>$service_product['business_product_id'],
                                'usage_qty'=>$service_product['usage_qty'],
                                'status'=>$service_product['status']
                            );
                            $this->db->insert('service_products', $data_service_products);
                            $service_product_id = $this->db->insert_id();
                        }
                    }
                }
            }
        //}
    }
    


    function year_closing_balance_voucher(){


        $businesssql = "select * from business";
        $qbusiness= $this->db->query($businesssql);
        $businesses = $qbusiness->result_array();

        foreach($businesses as $business){

            $sql = "select closing_balances_2023.*, account_heads.business_id 
            from closing_balances_2023 join account_heads on id_account_heads = account_head_id
            where account_heads.business_id = ".$business['id_business'].";";

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

            $data = array(
                'business_id'=> $business['id_business'],
                'voucher_date'=> '2023-12-31',
                'voucher_amount'=> 0,
                'voucher_status'=>'Active',
                'created_by'=>1,
                'cost_center'=>2,
                'cost_center_name'=>'Back Office',
                'voucher_type'=>3,
                'payment_mode'=>'Cash',
                'bank_name'=>'',
                'auto_voucher'=>'No',                
                'voucher_status'=>'Active'
            );

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

            $voucher_id = $this->db->insert_id();


            foreach($balances as $balance){
                
                $data_debit = array(
                    'account_voucher_id'=> $voucher_id,
                    'account_head_id'=> $balance['account_head_id'],
                    'debit'=> $balance['debit'],
                    'credit'=> 0
                );

                $this->db->insert('account_voucher_detail', $data_debit);


                $data_credit = array(
                    'account_voucher_id'=> $voucher_id,
                    'account_head_id'=> $balance['account_head_id'],
                    'debit'=> 0,
                    'credit'=> $balance['credit']
                );

                $this->db->insert('account_voucher_detail', $data_credit);

            }
        }

    }


}