<?php

class Imsfiscal_model extends CI_Model {

    function __construct() {

        // Call the Model constructor
        parent::__construct();
    }
    
    
    function get_imsfiscal_details($type){
        
        $this->db->select('*');
        $this->db->where('business_id', $this->session->userdata('businessid'));
        $this->db->where('ims_type', $type);
        
        $query = $this->db->get('imsfiscal');
        
        return $query->row();
    }
    
    
    function imsfiscal_invoice_service($posid, $invoiceid, $url, $token, $invoicetype, $taxmode) {        
        
        $sql = "select count(id_invoice)+1 as usin 
                from invoice where date(invoice_date) = '".date('Y-m-d')."'
                and invoice_type = 'service'    
                and invoice.business_id = ".$this->session->userdata('businessid')."     
                and invoice_status = 'valid';";
        
        $q = $this->db->query($sql); 
        $invoicenumber=$q->row();
        $usin = date('Y').'-'.date('m').'-s'.$invoicenumber->usin;
                
        $this->db->select('*, invoice.discount as invoice_discount, invoice_details.invoice_discount as invoice_discount_item, round(100*taxes/discounted_price ,2) as beforerate ', false);
        $this->db->join('customers','customers.id_customers=invoice.customer_id');
        $this->db->join('invoice_details','invoice_details.invoice_id = invoice.id_invoice');
        $this->db->where('id_invoice', $invoiceid);
        $query = $this->db->get('invoice');
        
        $invoice_data = $query->result_array();
        
//        $url = "http://localhost:8524/api/IMSFiscal/GetInvoiceNumberByModel";
//        $url = "https://ims.pral.com.pk/ims/sandbox/api/Live/PostData";
//        $token = "24d8fab3-f2e9-398f-ae17-b387125ec4a2";
        
        
        
        $invoice = new stdClass();
        $invoice->InvoiceNumber = "";
        $invoice->POSID = $posid;
        $invoice->USIN = $usin;// $invoice_data[0]['invoice_number'];
        $invoice->DateTime = date('Y-m-d h:m:s');
        $invoice->BuyerPNTN = isset($invoice_data[0]['ntn']) ? $invoice_data[0]['ntn'] : "1234567-8";
        $invoice->BuyerCNIC = isset($invoice_data[0]['cnic']) ? $invoice_data[0]['cnic'] : "12345-1234567-8";
        $invoice->BuyerName = $invoice_data[0]['customer_name'];
        $invoice->BuyerPhoneNumber = $invoice_data[0]['customer_cell'];
        $invoice->TotalBillAmount = $invoice_data[0]['total_payable'];
        $invoice->TotalQuantity = 1;
        if($taxmode=='after'){
            $invoice->TotalSaleValue = $invoice_data[0]['gross_amount'];
        }elseif($taxmode=='before'){
            $invoice->TotalSaleValue = $invoice_data[0]['sub_total'];
        }
        $invoice->TotalTaxCharged = $invoice_data[0]['tax_total'];
        if($taxmode=='after'){
            $invoice->Discount = 0.0;
        } elseif($taxmode=='before'){
            $invoice->Discount = $invoice_data[0]['invoice_discount'];
        }
        $invoice->FurtherTax = 0.0;
        $invoice->PaymentMode = 1;
        $invoice->RefUSIN = null;
        $invoice->InvoiceType = $invoicetype;

        $myItems = new stdClass();
        $x=1;
        foreach($invoice_data as $detail){
            $item = new stdClass();
            $item->ItemCode = $detail['service_id'];
            $item->ItemName = $detail['service_name'];
            $item->Quantity = 1.0;
            $item->PCTCode = "00000000";
            $item->TaxRate = 0.0;
            $item->SaleValue = $detail['final_price'];
            $item->TotalAmount = $detail['final_price']+$detail['taxes'];
            $item->TaxCharged = $detail['taxes'];
            if($taxmode=='after'){
                $item->Discount = 0.0;
            } elseif($taxmode=='before'){
                $item->Discount = $detail['invoice_discount_item'];                
            }
            $item->FurtherTax = 0.0;
            $item->InvoiceType = $invoicetype;
            $item->RefUSIN = null;
            $fieldname = 'item'.$x; 
            
            $invoice->Items[]= $item;
            
            $x++;
            
        }
        
       
        //$invoice->Items = [$item1, $item2, $item3];

        $myJSON = json_encode($invoice);

        
        //echo '<pre>';
        //print_r($myJSON);
        //echo '</pre>';
        //print_r($url);
        //print_r($token);
        //exit;
        //php api rest

        $curl = curl_init();
        //curl_setopt($curl, CURLOPT_POST, 1);

        curl_setopt($curl, CURLOPT_URL, $url);
        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 from cloud
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
           'Content-Type: application/json',
           'Authorization: Bearer ' . $token            
           ));
//        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        curl_setopt($curl, CURLOPT_USERAGENT, $agent);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 40); 
        curl_setopt($curl, CURLOPT_TIMEOUT, 400); //timeout in seconds
        
        
//        $result = curl_exec($curl);

//        curl_close($curl);
        if (curl_exec($curl) === FALSE) {
            curl_getinfo($curl);
           die("Curl Failed: " . curl_error($curl));
        } else {
           $result = curl_exec($curl);
            curl_close($curl);
            echo 'result is:';
           print_r($result);
           exit;
        }
//        {"InvoiceNumber":"800590BIFN30543742*test*","Code":"100","Response":"Invoice received successfully"}success|4163
        
        $decoded_result = json_decode($result);
        
        if(isset($decoded_result->InvoiceNumber)){
            $imsfiscal_number = $decoded_result->InvoiceNumber;
            $this->db->where('id_invoice', $invoiceid);
            $this->db->set('imsfiscal_invoice_number', $imsfiscal_number);
            $this->db->update('invoice');
            
            
            $this->db->insert('imsfiscal_log', $invoice);
            $logid=$this->db->insert_id();
            foreach($invoice->Items as $item){
                $item->imsfiscal_log_id = $logid;
                $this->db->insert('imsfiscal_log_detail', $item);
            }
            
        }
        
    }
    
    
    
    function imsfiscal_invoice_sale($posid, $invoiceid, $url, $token, $invoicetype, $taxmode) {
        
        $sql = "select count(id_invoice)+1 as usin from invoice where date(invoice_date) = '".date('Y-m-d')."'
            and invoice_type = 'sale' and invoice.business_id = ".$this->session->userdata('businessid')." 
            and invoice_status = 'valid';";

        
        $q = $this->db->query($sql); 
        $invoicenumber=$q->row();
         $usin = date('Y').'-'.date('m').'-r'.$invoicenumber->usin;
        
        
        $this->db->select('*, round(100*taxes/discounted_price ,2) as rate ', false);
        $this->db->join('customers','customers.id_customers=invoice.customer_id');
        $this->db->join('invoice_products','invoice_products.invoice_id = invoice.id_invoice');
        $this->db->where('id_invoice', $invoiceid);
        $query = $this->db->get('invoice');
        
        $invoice_data = $query->result_array();
        
//        $url = "http://localhost:8524/api/IMSFiscal/GetInvoiceNumberByModel";
//        $url = "https://ims.pral.com.pk/ims/sandbox/api/Live/PostData";
//        $token = "24d8fab3-f2e9-398f-ae17-b387125ec4a2";
        
        
        
        $invoice = new stdClass();
        $invoice->InvoiceNumber = "";
        $invoice->POSID = $posid;
        $invoice->USIN = $usin; //$invoice_data[0]['invoice_number'];
        $invoice->DateTime = date('Y-m-d h:m:s');
        $invoice->BuyerPNTN = isset($invoice_data[0]['ntn']) ? $invoice_data[0]['ntn'] : "1234567-8";
        $invoice->BuyerCNIC = isset($invoice_data[0]['cnic']) ? $invoice_data[0]['cnic'] : "12345-1234567-8";
        $invoice->BuyerName = $invoice_data[0]['customer_name'];
        $invoice->BuyerPhoneNumber = $invoice_data[0]['customer_cell'];
        $invoice->TotalBillAmount = $invoice_data[0]['total_payable'];
        $invoice->TotalQuantity = $invoice_data[0]['invoice_qty'];
        if($taxmode=='after'){
            $invoice->TotalSaleValue = $invoice_data[0]['gross_amount'];
        }elseif($taxmode=='before'){
            $invoice->TotalSaleValue = $invoice_data[0]['sub_total'];
        }
        $invoice->TotalTaxCharged = $invoice_data[0]['tax_total'];
        $invoice->Discount = 0.0;
        $invoice->FurtherTax = 0.0;
        $invoice->PaymentMode = 1;
        $invoice->RefUSIN = null;
        $invoice->InvoiceType = $invoicetype;

        $myItems = new stdClass();
        $x=1;
        foreach($invoice_data as $detail){
            $item = new stdClass();
            $item->ItemCode = $detail['product_id'];
            $item->ItemName = $detail['product_name'];
            $item->Quantity = $detail['invoice_qty'];
            $item->PCTCode = "00000000";
            $item->TaxRate = $detail['rate'];
            $item->SaleValue = $detail['final_price'];
            $item->TotalAmount = $detail['final_price']+($detail['taxes']*$detail['invoice_qty']);
            $item->TaxCharged = $detail['taxes']*$detail['invoice_qty'];
            $item->Discount = 0.0;
            $item->FurtherTax = 0.0;
            $item->InvoiceType = $invoicetype;
            $item->RefUSIN = null;
            $fieldname = 'item'.$x; 
            
            $invoice->Items[]= $item;
            
            $x++;
            
        }
        
       
        //$invoice->Items = [$item1, $item2, $item3];

        $myJSON = json_encode($invoice);
//        echo '<pre>';
//        print_r($myJSON);
//        echo '</pre>';
//        exit;
        //php api rest

        $curl = curl_init();
        //curl_setopt($curl, CURLOPT_POST, 1);

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $myJSON);
        //Set your auth headers from cloud
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
           'Content-Type: application/json',
           'Authorization: Bearer ' . $token
           ));
//        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $result = curl_exec($curl);

        curl_close($curl);

//        print_r($result);
//        exit;
        
        $decoded_result = json_decode($result);
        
        if(isset($decoded_result->InvoiceNumber)){
            $imsfiscal_number = $decoded_result->InvoiceNumber;
            $this->db->where('id_invoice', $invoiceid);
            $this->db->set('imsfiscal_invoice_number', $imsfiscal_number);
            $this->db->update('invoice');
            
            
            $this->db->insert('imsfiscal_log', $invoice);
            $logid=$this->db->insert_id();
            foreach($invoice->Items as $item){
                $item->imsfiscal_log_id = $logid;
                $this->db->insert('imsfiscal_log_detail', $item);
            }
            
        }
        
    }
    
    
    function imsfiscal_invoice_json($posid, $invoiceid, $url, $token, $invoicetype, $taxmode) {
        
        $sql = "select count(id_invoice)+1 as usin from invoice where date(invoice_date) = '".date('Y-m-d')."'
            and invoice_type = 'service' and invoice.business_id = ".$this->session->userdata('businessid')." 
            and invoice_status = 'valid';";

        
        $q = $this->db->query($sql); 
        $invoicenumber=$q->row();
         $usin = date('Y').'-'.date('m').'-s'.$invoicenumber->usin;
        
        
        
        
        $this->db->select('*, invoice.discount as invoice_discount, invoice_details.invoice_discount as invoice_discount_item, round(100*taxes/discounted_price ,2) as beforerate ', false);
        $this->db->join('customers','customers.id_customers=invoice.customer_id');
        $this->db->join('invoice_details','invoice_details.invoice_id = invoice.id_invoice');
        $this->db->where('id_invoice', $invoiceid);
        $query = $this->db->get('invoice');
        
        $invoice_data = $query->result_array();

        $invoice = new stdClass();
        $invoice->InvoiceNumber = "";
        $invoice->POSID = $posid;
        $invoice->USIN = $usin;
        $invoice->DateTime = $invoice_data[0]['invoice_date'];
        $invoice->BuyerPNTN = isset($invoice_data[0]['ntn']) ? $invoice_data[0]['ntn'] : "1234567-8";
        $invoice->BuyerCNIC = isset($invoice_data[0]['cnic']) ? $invoice_data[0]['cnic'] : "12345-1234567-8";
        $invoice->BuyerName = $invoice_data[0]['customer_name'];
        $invoice->BuyerPhoneNumber = $invoice_data[0]['customer_cell'];
        $invoice->TotalBillAmount = $invoice_data[0]['total_payable'];
        $invoice->TotalQuantity = 1;
        if($taxmode=='after'){
            $invoice->TotalSaleValue = $invoice_data[0]['gross_amount'];
        }elseif($taxmode=='before'){
            $invoice->TotalSaleValue = $invoice_data[0]['sub_total'];
        }
        $invoice->TotalTaxCharged = $invoice_data[0]['tax_total'];
        if($taxmode=='after'){
            $invoice->Discount = 0.0;
        } elseif($taxmode=='before'){
            $invoice->Discount = $invoice_data[0]['invoice_discount'];
        }
        $invoice->FurtherTax = 0.0;
        $invoice->PaymentMode = 1;
        $invoice->RefUSIN = null;
        $invoice->InvoiceType = $invoicetype;

        $myItems = new stdClass();
        $x=1;
        foreach($invoice_data as $detail){
            if($detail['final_price']>0){
                $item = new stdClass();
                $item->ItemCode = $detail['service_id'];
                $item->ItemName = trim($detail['service_name']);
                $item->Quantity = 1.0;
                $item->PCTCode = "00000000";
                $item->TaxRate = round($detail['taxes']*100/$detail['final_price'],2);
                $item->SaleValue = $detail['final_price'];
                $item->TotalAmount = $detail['final_price']+$detail['taxes'];
                $item->TaxCharged = $detail['taxes'];
                if($taxmode=='after'){
                    $item->Discount = 0.0;
                } elseif($taxmode=='before'){
                    $item->Discount = $detail['invoice_discount_item'];                
                }
                $item->FurtherTax = 0.0;
                $item->InvoiceType = $invoicetype;
                $item->RefUSIN = null;
                $fieldname = 'item'.$x; 

                $invoice->Items[]= $item;

                $x++;
            }
            
        }
        
       
        //$invoice->Items = [$item1, $item2, $item3];

        $myJSON = json_encode($invoice);
        
        return $myJSON;
    }
    
    
    function imsfiscal_invoice_r_json($posid, $invoiceid, $url, $token, $invoicetype, $taxmode){
        
        $sql = "select count(id_invoice)+1 as usin from invoice where date(invoice_date) = '".date('Y-m-d')."'
            and invoice_type = 'sale' and invoice.business_id = ".$this->session->userdata('businessid')." 
            and invoice_status = 'valid';";

        $q = $this->db->query($sql); 
        $invoicenumber=$q->row();
         $usin = date('Y').'-'.date('m').'-r'.$invoicenumber->usin;
        
        
        
        $this->db->select('*, invoice.discount as invoice_discount, invoice_products.discount as invoice_discount_item, round(100*taxes/discounted_price ,2) as beforerate ', false);
        $this->db->join('customers','customers.id_customers=invoice.customer_id');
        $this->db->join('invoice_products','invoice_products.invoice_id = invoice.id_invoice');
        $this->db->where('id_invoice', $invoiceid);
        $query = $this->db->get('invoice');
        
        $invoice_data = $query->result_array();

        $invoice = new stdClass();
        $invoice->InvoiceNumber = "";
        $invoice->POSID = $posid;
        $invoice->USIN = $usin;
        $invoice->DateTime = $invoice_data[0]['invoice_date'];
        $invoice->BuyerPNTN = isset($invoice_data[0]['ntn']) ? $invoice_data[0]['ntn'] : "1234567-8";
        $invoice->BuyerCNIC = isset($invoice_data[0]['cnic']) ? $invoice_data[0]['cnic'] : "12345-1234567-8";
        $invoice->BuyerName = $invoice_data[0]['customer_name'];
        $invoice->BuyerPhoneNumber = $invoice_data[0]['customer_cell'];
        $invoice->TotalBillAmount = $invoice_data[0]['total_payable'];
        $invoice->TotalQuantity = 1;
        if($taxmode=='after'){
            $invoice->TotalSaleValue = $invoice_data[0]['gross_amount'];
        }elseif($taxmode=='before'){
            $invoice->TotalSaleValue = $invoice_data[0]['sub_total'];
        }
        $invoice->TotalTaxCharged = $invoice_data[0]['tax_total'];
        if($taxmode=='after'){
            $invoice->Discount = 0.0;
        } elseif($taxmode=='before'){
            $invoice->Discount = $invoice_data[0]['invoice_discount'];
        }
        $invoice->FurtherTax = 0.0;
        $invoice->PaymentMode = 1;
        $invoice->RefUSIN = null;
        $invoice->InvoiceType = $invoicetype;

        $myItems = new stdClass();
        $x=1;
        foreach($invoice_data as $detail){
            if($detail['final_price']>0){
                $item = new stdClass();
                $item->ItemCode = $detail['product_id'];
                $item->ItemName = trim($detail['product_name']);
                $item->Quantity = 1.0;
                $item->PCTCode = "00000000";
                $item->TaxRate = round($detail['taxes']*100/$detail['final_price'],2);
                $item->SaleValue = $detail['final_price'];
                $item->TotalAmount = $detail['final_price']+$detail['taxes'];
                $item->TaxCharged = $detail['taxes'];
                if($taxmode=='after'){
                    $item->Discount = 0.0;
                } elseif($taxmode=='before'){
                    $item->Discount = $detail['invoice_discount_item'];                
                }
                $item->FurtherTax = 0.0;
                $item->InvoiceType = $invoicetype;
                $item->RefUSIN = null;
                $fieldname = 'item'.$x; 

                $invoice->Items[]= $item;
            }
            $x++;
            
        }
        
       
        //$invoice->Items = [$item1, $item2, $item3];

        $myJSON = json_encode($invoice);
        
        return $myJSON;
    }
    
    function imsfiscal_update_log(){
        

        $invoicedata = $this->input->post('data');
        $invoicenumber = $this->input->post('invoicenumber');
        $invoiceid = $this->input->post('invoiceid');
        
        $invoice = json_decode($invoicedata);
        
        if(null!==($invoicenumber) && $invoicenumber !== ''){
            $imsfiscal_number = $invoicenumber;
            $this->db->where('id_invoice', $invoiceid);
            $this->db->set('imsfiscal_invoice_number', $imsfiscal_number);
            $this->db->update('invoice');
            
            
            $this->db->insert('imsfiscal_log', $invoice);
            $logid=$this->db->insert_id();
            foreach($invoice->Items as $item){
                $item->imsfiscal_log_id = $logid;
                $this->db->insert('imsfiscal_log_detail', $item);
            }
            
            
            $this->db->where('id_imsfiscal_log', $logid);
            $this->db->set('InvoiceNumber', $invoicenumber);
            $this->db->set('USIN', $invoiceid);
            $this->db->update('imsfiscal_log');
            
            
            $this->update_receipt($invoiceid, $imsfiscal_number);
            
            return 'success|'.$logid;
            
        } else {
            return 'error|unknown';
        }
    }

    function update_receipt($invoice_id, $ims_number){
        
        $this->db->select('receipts_installed');
        $this->db->where('id_business', $this->session->userdata('businessid'));
        $query = $this->db->get('business');
        $business=$query->row();

        if($business->receipts_installed == "Yes"){            
            $sql="select sms_cred.*, tax_mode, CASE WHEN srb_fiscal_service = 'Yes' THEN 'SRB' ELSE 'PRA' END as tax_org
            from business 
            join sms_cred on sms_cred.business_id = business.id_business
            where sms_cred.channel like '%Receipt%' 
            and business.id_business = ". $this->session->userdata('businessid');

            $query=$this->db->query($sql);
            $sms_cred = $query->row();
            $taxmode =$sms_cred->tax_mode;
            $taxorg =$sms_cred->tax_org;

            $urltouse = $sms_cred->domain."update-receipt";

            $businessbranch = explode("|", $sms_cred->mask);

            if($taxorg=="SRB"){
                //$tax_org = "SRB";
                $tax_org_link = "https://pos.srb.gos.pk/InvoiceVerification/InvoiceStatus.jsp?invoiceVerification=".$ims_number;
            }else{
                //$tax_org ="PRA";
                $tax_org_link ="https://e.pra.punjab.gov.pk/IMSFiscalReport/SearchPOSInvoice_Report.aspx?PRAInvNo=".$ims_number;                
            }

            $sql="select invoice_number from invoice where id_invoice=".$invoice_id;
            $query=$this->db->query($sql);
            $invoice = $query->row();

            $invoice_number = $invoice->invoice_number;

            $data = array(
                "business_id" => $businessbranch[0],
                "branch_id" => $businessbranch[1],
                "invoice_number" => $invoice_number,
                "ims_code" => $ims_number,
                "tax_org_link" => $tax_org_link,
                "tax_org" => $taxorg
            );

            $urltouse = $sms_cred->domain;
            $authorization = "Authorization: Bearer ".$sms_cred->password;
            $curl = curl_init();

            curl_setopt_array($curl, array(
                CURLOPT_URL => $urltouse,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS =>$data,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json',
                    'secret-key: '.$sms_cred->password
                    )
                )
                    // CURLOPT_HTTPHEADER => array(
                    //     'Content-Type: application/json',
                    //     'Authorization: '.$authorization
                    //     ),
                    // )
                    
            );

               
            // Execute and get the response
            $response = curl_exec($curl);
            // Check for cURL errors
            if (curl_errno($curl)) {
                echo 'Error: ' . curl_error($curl);
            } else {
                //   echo $response;
            }
            // Close cURL session
            curl_close($curl);
        }
    }
    
    function srbfiscal_update_log(){

        $invoicedata = $this->input->post('data');
        $invoicenumber = $this->input->post('invoicenumber');
        $invoiceid = $this->input->post('invoiceid');
        
        $invoice = json_decode($invoicedata);
        $data = array(
            'InvoiceNumber' => $invoiceid,
            'POSID' => $invoice->posId,
            'USIN' => $invoice->invoiceID,
            'DateTime' => $invoice->invoiceDateTime,
            'BuyerPNTN' => $invoice->consumerNTN,            
            'BuyerName' => $invoice->consumerName,            
            'TotalBillAmount'=> $invoice->saleValue,
            'TotalSaleValue'=> $invoice->saleValue,
            'TotalTaxCharged'=> $invoice->taxAmount,
            'InvoiceType'=> $invoice->invoiceType
        );

        if(null!==($invoicenumber) && $invoicenumber !== ''){
            $imsfiscal_number = $invoicenumber;
            $this->db->where('id_invoice', $invoiceid);
            $this->db->set('imsfiscal_invoice_number', $imsfiscal_number);
            $this->db->update('invoice');
            
            
            $this->db->insert('imsfiscal_log', $data);
            $logid=$this->db->insert_id();
            // foreach($invoice->Items as $item){
            //     $item->imsfiscal_log_id = $logid;
            //     $this->db->insert('imsfiscal_log_detail', $item);
            // }
            
            
            $this->db->where('id_imsfiscal_log', $logid);
            $this->db->set('InvoiceNumber', $invoicenumber);
            $this->db->set('USIN', $invoiceid);
            $this->db->update('imsfiscal_log');
            

            $this->update_receipt($invoiceid, $imsfiscal_number);
            
            return 'success|'.$logid;
            
        } else {
            return 'error|unknown';
        }


    }
    
    function get_ims_unposted_invoices($startdate=null, $enddate=null, $invoice_type=null){
        
        if(null == $startdate){
            $startdate=$this->input->post('startdate');
        }
        if(null == $enddate){
            $enddate=$this->input->post('enddate');
        }
        
        $this->db->select('*');
        $this->db->where("date(invoice_date) >=", $startdate,true);
        $this->db->where("date(invoice_date) <=", $enddate,true);
        $this->db->where("ifnull(imsfiscal_invoice_number,'') = ", "" ,true);
        $this->db->where("invoice_status", "valid");
        $this->db->where("business_id", $this->session->userdata('businessid'),true);
        
        if(null != $invoice_type){
            $this->db->where("invoice.invoice_type", $invoice_type,true);
        }
        
        $query = $this->db->get('invoice');
        //echo $query;
        return $query->result_array();
        
        
    }

    function srb_invoice_json($posid, $pos_user, $pos_pass, $invoiceid, $url, $ntn, $invoicetype, $taxmode){

        $sql = "select count(id_invoice)+1 as usin from invoice where date(invoice_date) = '".date('Y-m-d')."'
        and invoice_type = 'service' and invoice.business_id = ".$this->session->userdata('businessid')." 
        and invoice_status = 'valid' and ifnull(imsfiscal_invoice_number,'')!='';";

    
        $q = $this->db->query($sql); 
        $invoicenumber=$q->row();
        $usin = date('Y').'-'.date('m').'-s'.$invoicenumber->usin;
                
        $this->db->select('*, invoice.discount as invoice_discount, invoice_details.invoice_discount as invoice_discount_item, round(100*taxes/discounted_price ,2) as beforerate ', false);
        $this->db->join('customers','customers.id_customers=invoice.customer_id');
        $this->db->join('invoice_details','invoice_details.invoice_id = invoice.id_invoice');
        $this->db->where('id_invoice', $invoiceid);
        $query = $this->db->get('invoice');
        
        $invoice_data = $query->result_array();

        $invoice = new stdClass();
        $invoice->posId = $posid;
        $invoice->name = $this->session->userdata('business');
        $invoice->ntn = $ntn;
        $invoice->invoiceDateTime =  $invoice_data[0]['invoice_date'];
        $invoice->invoiceType = 1;
        $invoice->invoiceID = $usin;
        

        if($taxmode=='after'){
            $invoice->saleValue = $invoice_data[0]['gross_wo_tax'];
            $invoice->rateValue = round($invoice_data[0]['tax_total']*100/$invoice_data[0]['gross_wo_tax'],2);     
        }elseif($taxmode=='before'){
            $invoice->saleValue = $invoice_data[0]['sub_total'];
            $invoice->rateValue = round($invoice_data[0]['tax_total']*100/$invoice_data[0]['sub_total'],2);     
        }        

        $invoice->taxAmount =  $invoice_data[0]['tax_total'];
        $invoice->consumerName = $invoice_data[0]['customer_name'];
        $invoice->consumerNTN = "N/A";
        $invoice->address = "N/A";
        $invoice->tariffCode = "N/A";
        $invoice->extraInf = "N/A";
        $invoice->pos_user = $pos_user;
        $invoice->pos_pass = $pos_pass;


        $myJSON = json_encode($invoice);
        
        return $myJSON;

    }
    
}