<?php

class Franchise_model extends CI_Model {

    function __construct() {

        // Call the Model constructor
        parent::__construct();
    }
    
    function get_all_franchises(){
        
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('franchise_status','Active');
        $query = $this->db->get('franchises');
        
        return $query->result_array();
        
    }
    
    function get_months(){
        $this->db->select('*');
        $query = $this->db->get('months');
        
        return $query->result_array();
    }
    
    function add_new_franchise(){
        $data = array(
            'business_id' => $this->session->userdata('businessid'),
            'franchise_name' => $this->input->post('franchise_name', TRUE),
            'franchise_email' => $this->input->post('franchise_email', TRUE),
            'franchise_contact' => $this->input->post('franchise_contact', TRUE),
            'franchise_ntn' => $this->input->post('franchise_ntn', TRUE),
            'franchise_address' => $this->input->post('franchise_address', TRUE),
            'franchise_owner' => $this->input->post('franchise_owner', TRUE),
            'franchise_office_phone' => $this->input->post('franchise_office_phone', TRUE),
            'created_by' => $this->session->userdata('username'),
            'franchise_discount' => $this->input->post('franchise_discount', TRUE),
            'franchise_limit' => $this->input->post('franchise_limit', TRUE)
        );

        $this->db->insert('franchises', $data);
        return $this->db->insert_id();
    }
    
    function get_franchise($franchise_id){
        
        $this->db->select('*');
        $this->db->where('id_franchises', $franchise_id);
        $this->db->where('franchise_status','Active');
        $query = $this->db->get('franchises');
        
        return $query->row();
        
    }
    
    function update_franchise($franchiseid){
        
        $data=array(
            'franchise_name'=>$this->input->post('franchise_name'),
            'franchise_ntn'=>$this->input->post('franchise_ntn'),
            'franchise_owner'=>$this->input->post('franchise_owner'),
            'franchise_office_phone'=>$this->input->post('franchise_office_phone'),
            'franchise_contact'=>$this->input->post('franchise_contact'),
            'franchise_email'=>$this->input->post('franchise_email'),
            'franchise_address'=>$this->input->post('franchise_address'),
            'franchise_discount' => $this->input->post('franchise_discount', TRUE),
            'franchise_limit' => $this->input->post('franchise_limit', TRUE)
        );
        $this->db->where('id_franchises', $franchiseid);
        $this->db->update('franchises', $data);

        return $franchiseid;
    }
    
    function searchnameforfranchise($match){
        $this->db->select('*, franchise_name as id');
        $this->db->like('franchise_name', $match);
        $query = $this->db->get("franchises");
        
        return $query->result_array();
    }
    
    
     function get_all_franchise_orders($franchiseid, $startdate, $enddate, $status, $dtype){
        $sql = '(select franchise_order_id, order_month, order_year from franchise_order_products where order_month is not null) as a';
        //echo $franchiseid; exit();
        $this->db->select('*, franchise_orders.created_by as created_by, date_format(order_date, "%d-%m-%Y %h:%i:%s") as order_date, date_format(franchise_orders.created_on, "%d-%m-%Y %h:%i:%s") as created_on, a.order_month, a.order_year');
        $this->db->join('franchises','franchises.id_franchises = franchise_orders.franchise_id');
        $this->db->join($sql, 'a.franchise_order_id = franchise_orders.id_franchise_orders', 'left');
        $this->db->where('franchise_orders.business_id', $this->session->userdata('businessid'));
        

        $d = new DateTime('tomorrow');
        $tommorrow = $d->format('Y-m-d H:i:s');
        
        if($startdate!==date('Y-m-d') && $enddate!==date('Y-m-d')){        
            if($dtype=='invoice'){
                $this->db->where('date(franchise_orders.invoice_date) >= ', $startdate);
                $this->db->where('date(franchise_orders.invoice_date) <= ', $enddate);
            }elseif($dtype=='order'){
                $this->db->where('date(franchise_orders.order_date) >= ', $startdate);
                $this->db->where('date(franchise_orders.order_date) <= ', $enddate);
            }else{
                $this->db->where('date(franchise_orders.created_on) >= ', $startdate);
                $this->db->where('date(franchise_orders.created_on) <= ', $enddate);
            }
        }
        
        if ($franchiseid!=='all'){
            $this->db->where('franchise_id', $franchiseid);
        }
        
        if($status!=='all'){
            if($status == 'Invoiced'){
                $this->db->where_in('order_status', array('Invoiced','Paid'));
            }else{
                $this->db->where('order_status', $status);
            }
        }else{
            $this->db->where_in('order_status', array('Open','Invoiced','Paid'));
        }
        $this->db->group_by('id_franchise_orders');
        $query = $this->db->get('franchise_orders');
        return $query->result_array();
    }
    
    
    function get_franchise_order($orderid){
        
        $this->db->select('*, date_format(invoice_date, "%d-%m-%Y") as formatted_invoice_date, date_format(date_add(invoice_date, , INTERVAL 7 DAY) , "%d-%m-%Y") as due_date');
        $this->db->join('franchise_order_products', 'franchise_order_id = id_franchise_orders' );
        $this->db->join('product_batch', 'id_batch= batch_id' );
        $this->db->join('business_products', 'business_products.id_business_products = franchise_order_products.product_id' );
        $this->db->join('business_brands', 'business_products.brand_id = id_business_brands' );
        $this->db->where('id_franchise_orders', $orderid);
        
        
        $query = $this->db->get('franchise_orders');
        return $query->result_array();
    }
    
    function get_customer_invoice_number($franchiseid){
        
        $this->db->select('max(invoice_number) + 1 as invoice_number',false);
        $this->db->where('franchise_id', $franchiseid);
        $query = $this->db->get('franchise_orders');
        return $query->row();
        
    }


    function add_new_order(){
        
       
       // Unescape the string values in the JSON array
        $tableData = stripcslashes($_POST['orderdata']);

        // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
        
        // now $tableData can be accessed like a PHP array
       // print_r($tableData); exit();
        
        //add new franchise_order
        $order = array(
            'business_id' => $this->session->userdata('businessid'),
            'franchise_id' => $this->input->post('franchiseid'),
            'franchise_name' => $this->input->post('franchisename'),
            'franchise_ntn' => $this->input->post('franchisentn'),
            'order_status' => $this->input->post('orderstatus'),
            'franchise_order_value' => $this->input->post('franchise_order_value'),
            'franchise_order_discount' => $this->input->post('franchise_order_discount'),
            'created_by' => $this->session->userdata('username'),
            'franchise_order_extra' => $this->input->post('order_extra')
        );
        $this->db->insert('franchise_orders', $order);
        $order_id = $this->db->insert_id();
        
        $data = [];
        
        foreach($tableData as $row){
           
            $data = array(
                'business_id' => $this->session->userdata('businessid'),
                'franchise_order_id' => $order_id,
                'product_id' => $row['productid'],
                'product_name' => $row['productname'],
                'product_detail' => $row['productdetail'],
                'category' => $row['category'],
                'staff_id' => $row['staffid'],
                'staff_name' => $row['staff'],
                'qty' => $row['qty'],
                'stockfrom' => $row['stockfrom'],
                'batch' => $row['batch'],
                'batch_id' => $row['batch_id'],
                'unit_price' => $row['unit_price'],
                'unit_discount' => $row['unit_discount'],
                'discounted_price' => $row['discounted_price'],
                'order_month' => isset($row['month']) ? $row['month'] : null,
                'order_year' => isset($row['year']) ? $row['year'] : null                
            );
           
            $this->db->insert('franchise_order_products', $data);
            
           
        }
        return $order_id;
    }
    
    function update_order($franchiseorderid){
        
      //exit();
       // Unescape the string values in the JSON array
        $tableData = stripcslashes($_POST['orderdata']);

        // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
       
        
        $stopproduct='';
        foreach($tableData as $row){
            $qty=0;
            $batches = $this->product_model->get_all_batches($row['productid'], $this->session->userdata('businessid'));
            foreach($batches as $batch){
                if($batch['id_batch']==$row['batch_id']){
                    $qty=$batch['total_stock'];
                    if($qty < $row['qty']){
                        $stopproduct=$row['productname'];
                        return('Error|Stock Qty is lower then the Ordered Qty for '.$stopproduct);
                    }
                }
            }
        }
        
        
        
        
        ///delete details///
        $this->db->where('franchise_order_id', $franchiseorderid);
        $this->db->delete('franchise_order_products');

        
        //update franchise_order
        $order = array(
            'franchise_order_value' => $this->input->post('franchise_order_value'),
            'franchise_order_discount' => $this->input->post('franchise_order_discount'),
            'franchise_order_extra' =>  $this->input->post('order_extra')
        );
        $this->db->where('id_franchise_orders', $franchiseorderid);
        $this->db->update('franchise_orders', $order);
        
        
        $data = [];
        
        ///insert again///
        foreach($tableData as $row){
           
            $data = array(
                'business_id' => $this->session->userdata('businessid'),
                'franchise_order_id' => $franchiseorderid,
                'product_id' => $row['productid'],
                'product_name' => $row['productname'],
                'product_detail' => $row['productdetail'],
                'category' => $row['category'],
                'staff_id' => $row['staffid'],
                'staff_name' => $row['staff'],
                'qty' => $row['qty'],
                'stockfrom' => $row['stockfrom'],
                'batch' => $row['batch'],
                'batch_id' => $row['batch_id'],
                'unit_price' => $row['unit_price'],
                'unit_discount' => $row['unit_discount'],
                'discounted_price' => $row['discounted_price'],
                'order_month' => isset($row['month']) ? $row['month'] : null,
                'order_year' => isset($row['year']) ? $row['year'] : null 

            );
           
            $this->db->insert('franchise_order_products', $data);
            
           
        }
        return "success|".$franchiseorderid;
    }
    
    function cancel_order($franchiseorderid){
        //update franchise_order
        
            
        $this->db->set('order_status', 'Cancelled');
        $this->db->where('id_franchise_orders', $franchiseorderid);
        $this->db->update('franchise_orders');
        
        //update account voucher
        $this->db->set('voucher_status', 'Cancelled');
        $this->db->set('cancelled_by', $this->session->userdata('username'));
        $this->db->set('cancelled_on', date('Y-m-d H:i:s'));
        $this->db->where('franchise_order_id', $franchiseorderid);
        $this->db->update('account_vouchers');
    }
    
    function update_invoice($franchiseorderid){
        //exit();
        $batch_amount=0;
        // Unescape the string values in the JSON array
        $tableData = stripcslashes($_POST['tabledata']);
        // Decode the JSON array
        $tableData = json_decode($tableData,TRUE);
        $stopproduct='';
        foreach($tableData as $row){
            $qty=0;
            $batches = $this->product_model->get_all_batches($row['productid'], $this->session->userdata('businessid'));
            foreach($batches as $batch){
                if($batch['id_batch']==$row['batch_id']){
                    $batch_amount=$batch_amount+($batch['batch_amount']*$row['qty']);
                    $qty=$batch['total_stock'];
                    if($qty < $row['qty']){
                        $stopproduct=$row['productname'];
                        return('Error|Stock Qty is lower then the Ordered Qty for '.$stopproduct);
                    }
                }
            }

            $this->db->set('product_tax', $row['product_tax']);
            $this->db->where('id_franchise_order_products', $row['id_franchise_order_products']);
            $this->db->update('franchise_order_products');
        }
        
        
        //update franchise_order
        $order = array(
            'invoice_discount' => $this->input->post('discount'),
            'product_discount' => $this->input->post('product_discount'),
            'invoice_discount_perc' => $this->input->post('discount_perc'),
            'invoice_other_charges' => $this->input->post('other_charges'),
            'invoice_gross_total' => $this->input->post('grosstotal'),
            'invoice_sales_tax' => $this->input->post('othertax'),            
            'invoice_sales_tax_perc' => round(($this->input->post('othertax') + $this->input->post('product_discount')) * 10/$this->input->post('grosstotal'),2)  ,
            'product_tax' => $this->input->post('salestax'),            
            'invoice_total_receivable' => $this->input->post('totalpayable'),
            'order_status' => 'Invoiced',
            'invoice_remarks' => $this->input->post('remarks'),
            'invoice_number' => $this->input->post('invoicenumber'),
            'invoice_date' => $this->input->post('invoicedate')
        );

        //print_r($order); exit();

        $this->db->where('id_franchise_orders', $franchiseorderid);
        $this->db->update('franchise_orders', $order);
       
        
        ///create account voucher for sale
        
            $this->db->where('franchise_order_id', $franchiseorderid);
            $this->db->set('voucher_status', 'cancelled');
            $this->db->set('cancelled_by', $this->session->userdata('username'));
            $this->db->set('cancelled_on', date('Y-m-d H:i:s'));
            $this->db->update('account_vouchers');

        
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(37);
            //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' => 'Franchise Sale Order Voucher on invoicing for Order #' . $franchiseorderid . ', Invoice # '.$this->input->post('invoicenumber').' on '. date('d-m-Y').', for '.$this->input->post('companyname').', customer ID : '. $this->input->post('customerid') .' with comments : '.$this->input->post('remarks'),
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $this->input->post('totalpayable'),
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Back Office',
                'business_partner'=> 4,
                'business_partner_id'=>$this->input->post('customerid'),
                'business_partner_name'=>$this->input->post('customername'),
                'voucher_type'=>3,
                'payment_mode'=>'Cash',
                'bank_name'=>$bank_name,
                'franchise_order_id'=>$franchiseorderid,
                'auto_voucher'=>'Yes',
                'sale_type'=>'franchise'
            );

            $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]=="total_receivable" && $this->input->post('totalpayable') > 0){$debitamount= $this->input->post('totalpayable');}
                if($debit[2]=="invoice_discount" && $this->input->post('discount')+$this->input->post('product_discount') > 0){$debitamount= $this->input->post('discount')+$this->input->post('product_discount');}
                
                
                $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]=="total_invoice_value"){$creditamount= $this->input->post('orgsubtotal') ;}
                if($credit[2]=="other_charges"){$creditamount= $this->input->post('other_charges') ;}
                if($credit[2]=="sales_tax"){$creditamount= $this->input->post('salestax') +  $this->input->post('othertax');}
              
                
                $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 inventory and cost of goods voucher/////////////////////////////////
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(23);
            //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' => 'Cost of Goods Solds Voucher against reference voucher ID '. $account_voucherid . ' Franchise invoice ' . $franchiseorderid . ' on '. date('d-m-Y').', for '.$this->input->post('customername').' customer ID : '. $this->input->post('customerid'),
                'voucher_date' => date('Y-m-d H:i:s'),
                'voucher_amount' => $batch_amount,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> '1',
                'cost_center_name'=> 'Front Desk',
                'business_partner'=> 1,
                'business_partner_id'=>$this->input->post('customerid'),
                'business_partner_name'=>$this->input->post('customername'),
                'voucher_type'=>3,
                'payment_mode'=>'Cash',
                'bank_name'=>$bank_name,
                'franchise_order_id'=>$franchiseorderid,
                'auto_voucher'=>'Yes'
                //'sale_type'=>'sale'
            );

            $this->db->insert('account_vouchers', $data);
            $cogs_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]=="cogs"){$debitamount= $batch_amount;}
                
                $data_detail=array(
                    'account_voucher_id' => $cogs_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]=="inventory"){$creditamount= $batch_amount;}
                
                $data_detail=array(
                    'account_voucher_id' => $cogs_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 "Success|".$franchiseorderid;
    } 
    
    
    function cancel_invoice($franchiseorderid){
        
        $this->db->set('order_status', 'Open');
        $this->db->set('invoice_discount', '0');
        $this->db->set('invoice_discount_perc', '0');
        $this->db->set('invoice_other_charges', '0');
        $this->db->set('invoice_gross_total', '0');
        $this->db->set('invoice_sales_tax', '0');
        $this->db->set('invoice_sales_tax_perc', '0');
        $this->db->set('invoice_total_receivable', '0');
        $this->db->set('invoice_remarks', '');
        $this->db->set('invoice_date', null);
        $this->db->set('invoice_number', null);
        $this->db->where('id_franchise_orders', $franchiseorderid);
        $this->db->update('franchise_orders');
        
        
        ///cancel the account voucher
        $this->db->set('voucher_status', 'cancelled');
        
        $this->db->set('cancelled_by', $this->session->userdata('username'));
        $this->db->set('cancelled_on', date('Y-m-d H:i:s'));
        $this->db->where('franchise_order_id', $franchiseorderid);
        $this->db->update('account_vouchers');
        
        return "Success";
        
    }
    
    function checkorderstatus($franchiseorderid){
        $this->db->select('order_status');
        $this->db->where('id_franchise_orders', $franchiseorderid);
        $query = $this->db->get('franchise_orders');
        
        $row = $query->row();
        
        return $row->order_status;
    }
    
    function update_receiving_note(){
        
       
        
        $franchiseorderid = $this->input->post('txtorderid');
        $receivable = $this->input->post('txtreceivable');
        $receiving = $this->input->post('txtreceivednow');
        $withholding = $this->input->post('txtwithholding');
        
        if($receivable <  ($receiving+$withholding)){
            return 'error| Cannot receive more then the total receivable';
            
        } else if($receivable == $receiving+$withholding) {
            //update franchise_order
            $order = array(
                'order_status' => 'Paid'
            );
            $this->db->where('id_franchise_orders', $franchiseorderid);
            $this->db->update('franchise_orders', $order);
        }
        
        
        ///create account voucher
            
            if($this->input->post('voucher_payment_mode')=="Cash"){
                $ac_head=$this->input->post('cash_accounts');
            } else if($this->input->post('voucher_payment_mode')=="Card") {
                $ac_head=$this->input->post('card_accounts');
            } else {
                $ac_head=$this->input->post('bank_accounts');
            }
            
            
            $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' => $this->input->post('description'),
                'voucher_date' => $this->input->post('account_voucher_date'),
                'voucher_amount' => $receiving,
                'voucher_status' => 'Active',
                'created_by' => $this->session->userdata('username'),
                'cost_center'=> $this->input->post('cost_center_type'),
                'cost_center_name'=> $this->input->post('cost_center'),
                'business_partner'=> 4,
                'business_partner_id'=>$this->input->post('txtfranchiseid'),
                'business_partner_name'=>$this->input->post('txtfranchisename'),
                'voucher_type'=>2,
                'payment_mode'=> $this->input->post('voucher_payment_mode'),
                'franchise_order_id'=>$franchiseorderid,
                'auto_voucher'=>'Yes',
                'sale_type'=>'franchise'
            );

            $this->db->insert('account_vouchers', $data);
            $account_voucherid =  $this->db->insert_id();
            
            
            $debit_accounts=[];
            $credit_accounts=[];
            
            $account_heads = $this->accounting_model->get_mapped_accounts(37);
            //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']);
                }
            }
            
            //Debit Fixed//
            $data = array(
                'account_voucher_id' => $account_voucherid,
                'account_head_id' => $ac_head,
                'debit' => $receiving,
                'credit' => 0,
                'cost_center_type'=> $this->input->post('cost_center_type'),
                'cost_center'=> $this->input->post('cost_center'),
                'instrument_number' => $this->input->post('instrument_number'),
                'payment_mode'=>$this->input->post('voucher_payment_mode')
            );
            $this->db->insert('account_voucher_detail', $data);
            
            //Debit other accounts//
            
            
            
            //enter debit entries
            foreach($debit_accounts as $debit_account){
                $debitamount=0;
                $debit = explode("|", $debit_account);
                //check entity
                if($debit[2]=="withholding" && $withholding > 0){$debitamount= $withholding;}
               
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $debit[0],
                    'debit' => round($debitamount,2),
                    'credit' => 0,
                    'instrument_number' => $this->input->post('instrument_number')
                );
                //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]=="received_amount"){$creditamount= $receiving+$withholding;}
                
                
                $data_detail=array(
                    'account_voucher_id' => $account_voucherid,
                    'account_head_id' => $credit[0],
                    'debit' => 0,
                    'credit' => round($creditamount,2),
                    'instrument_number' => $this->input->post('instrument_number')
                );
                //insert credit detail
                if($creditamount>0){
                    $this->db->insert('account_voucher_detail', $data_detail);
                }
            }
        
        return 'success|Payment received against order '.$franchiseorderid;
    }
 
    function franchise_aging_report(){
        
        $subsql="SELECT franchise_order_id, sum(debit)-sum(credit) as balance 
                from account_vouchers
                join account_voucher_detail 
                 on account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
                join account_event_mapping on account_event_mapping.account_head_id = account_voucher_detail.account_head_id
               
                 where  entity_name='total_receivable'
                and account_event_id=37
                and account_vouchers.voucher_status='Active'
                group by franchise_order_id";
        
        
        $sql = "SELECT franchise_name, franchise_id, id_franchise_orders, invoice_number, 
            date_format(invoice_date,'%d-%m-%Y') as invoice_date, 
            bal.balance as invoice_total_receivable, datediff(now(), invoice_date) as lapsed_days,
            a.product_name, franchise_order_extra
            FROM franchise_orders
            left join (select franchise_order_id, concat(franchise_order_products.product_name, ' ', months.month_name, ' ', order_year) as product_name  from 
            franchise_order_products
            join months on months.id_months = order_month
            group by franchise_order_id
            ) as a on a.franchise_order_id=franchise_orders.id_franchise_orders
            join (".$subsql.") as bal on bal.franchise_order_id= franchise_orders.id_franchise_orders
            where invoice_number is not null
            and order_status != 'Cancelled'
            and bal.balance>0
            order by franchise_id";
        
        //echo $sql ; exit();

        $query= $this->db->query($sql);
        
        return $query->result_array();
        
        
    }
    
    function get_paid_amount($orderid){
        $sql="SELECT franchise_order_id, ifnull(sum(debit)-sum(credit),0) as balance ,
            ifnull(sum(debit),0) as debit, ifnull(sum(credit),0) as credit 
                from account_vouchers
                join account_voucher_detail 
                on account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
                join account_event_mapping on account_event_mapping.account_head_id = account_voucher_detail.account_head_id
                where  entity_name='received_amount'                 
                and account_event_id=37
                and account_vouchers.voucher_status='Active'
                and account_vouchers.franchise_order_id = ".$orderid."
                group by franchise_order_id";
        
        $query= $this->db->query($sql);
        
        return $query->result_array();
        
        
    }
    
    function get_receivable_amount($franchiseid, $orderid=null){
        $sql="SELECT account_vouchers.business_partner_id, ifnull(sum(debit)-sum(credit),0) as balance ,
            ifnull(sum(debit),0) as debit, ifnull(sum(credit),0) as credit 
                from account_vouchers
                join account_voucher_detail 
                on account_voucher_detail.account_voucher_id = account_vouchers.id_account_vouchers
                join account_event_mapping on account_event_mapping.account_head_id = account_voucher_detail.account_head_id
                where  entity_name='received_amount'                 
                and account_event_id=37
                and account_vouchers.voucher_status='Active'
                and account_vouchers.business_partner_id = ".$franchiseid."
                and account_vouchers.business_partner = 4
                and franchise_order_id > 0
                and franchise_order_id != ".$orderid." 
                and account_event_mapping.entity_name in ('total_receivable', 'received_amount') 
                group by business_partner_id";
        
       
        $query= $this->db->query($sql);
        
        return $query->row();
        
        
    }
    
    function get_product_wise_invoiced($startdate, $enddate, $products){
        
        $sql = "select id_franchise_orders, franchise_name, franchise_order_products.category, franchise_order_products.product_name,  
            sum(discounted_price) as invoiced from franchise_orders
            join franchise_order_products on franchise_order_products.franchise_order_id=franchise_orders.id_franchise_orders
            where date(franchise_orders.order_date) >= '".$startdate."' 
            and date(franchise_orders.order_date) <= '".$enddate."'             
            and franchise_order_products.product_id in (".$products.")
            group by id_franchise_orders, franchise_name;";
        
        
        $query= $this->db->query($sql);
        
        return $query->row();
                
    }
    
}