<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Purchaseinvoice extends MY_Controller {
    function __construct() {
        parent::__construct();
        if($this->session->user == "") {
            redirect('login');
        }
        $this->load->library('form_validation');
        $this->load->model('inventory/purchaseinvoice_model');
        $this->load->model('settings/taxes_model');
        $this->load->model('inventory/stock_model');
        $this->load->model('inventory/goodsreceipts_model');
        $this->load->model('inventory/products_model');
        $this->load->model('settings/companyinfo_model');
        $this->load->model('finance/TransactionModel');
        $this->load->library('Formatslist');
        $this->load->library('session');
        $this->session->unset_userdata('PRPIID');
    }
    function index() {
        $this->session->unset_userdata('PIID');
        $data['template'] = 'inventory/pi_view';
        $this->load->view('template',$data);
    }
    function purchaseinvoiceupdate() {
        //$id = $this->input->get('id');
        $id = $this->input->get('id');
        if($this->input->get('SUPPLIERID'))
            $data["SUPPLIERID"] = $this->input->get('SUPPLIERID');
        if($this->input->get('DELIVERYDATE'))
            $data["DELIVERYDATE"] = date('Y-m-d',strtotime($this->input->get('DELIVERYDATE')));
        if($this->input->get('REFERENCE'))
            $data["REFERENCE"] = $this->input->get('REFERENCE');
        if($this->input->get('COMMENTS'))
            $data["COMMENTS"] = $this->input->get('COMMENTS');
        if($this->input->get('DISCOUNT')!='')
            $data["DISCOUNT"] = $this->input->get('DISCOUNT');
        if($this->input->get('FREIGHTAMOUNT')!='')
            $data["FREIGHTAMOUNT"] = $this->input->get('FREIGHTAMOUNT');
        if($this->input->get('ADJUSTMENT')!='')
            $data["ADJUSTMENT"] = $this->input->get('ADJUSTMENT');
//        if($this->input->get('TOTALAMOUNT')!='')
//            $data["TOTALAMOUNT"] = $this->input->get('TOTALAMOUNT');
        $where  =   array('ID' => $id);
        $res =   $this->common->update('PURCHASEINVOICE',$where,$data);
        if($res){
            $result["status"]   =   'success';
        }else{
            $result["status"]   =   'fail';
        }
        echo json_encode($result);
    }
    function create($id='',$status=''){
        $where = array('ID!=' => -1);
        $data['categories'] = $this->common->getWhere('CATEGORIES',$where);
        $data['tax_categories'] = $this->common->getWhere('TAXCATEGORIES',$where);
        $where_resources = array('NAME' => 'Product.Properties');
        $data['resources'] =  $this->common->getWhere('RESOURCES',$where_resources);        
        $data['attributeset'] = $this->common->getAll('ATTRIBUTESET');
        $currencyFormat = $this->formatslist->formatCurrency(0);
        $data['currencyDecimel'] = strlen(substr(strrchr($currencyFormat, "."), 1));        
        $data['alltaxes'] = $this->taxes_model->gettax();
        $this->load->model('settings/companyinfo_model');
        $data['company'] = $this->companyinfo_model->getcompanyinfo('0');
        $this->load->model('inventory/Products_model');
        $this->load->model('settings/companyinfo_model');
        $data['locale'] = $this->companyinfo_model->getlocaleinfo();
        //$id =   $this->session->userdata('PIID');
        if(!$id) {
            redirect('inventory/purchaseinvoice/createnew/');exit;
        }
        if($id){
            $data['invoiceId']    =   $id;
            $this->session->unset_userdata('PIID');
            $editdata = $this->purchaseinvoice_model->getpibyid($id);
            $supname =   $editdata->name;
            if($editdata->TAXID)
                $supname =   $supname." - ".$editdata->TAXID;
            $editdata->name =    $supname;
            $data['taxRecData'] = $this->purchaseinvoice_model->getPurchaseInvoiceTaxes($id);
        }
        if($editdata->DELIVERYDATE)
            $editdata->DELIVERYDATE    =   $this->formatslist->dateFormat($editdata->DELIVERYDATE);
        else
            $editdata->DELIVERYDATE    =   $this->formatslist->dateFormat(date('d-m-Y'));
        if(!$editdata->DISCOUNT)
            $editdata->DISCOUNT    =   $this->formatslist->formatCurrency(0);
        else
            $editdata->DISCOUNT    =   $this->formatslist->formatCurrency($editdata->DISCOUNT);
        if(!$editdata->FREIGHTAMOUNT)
            $editdata->FREIGHTAMOUNT    =   $this->formatslist->formatCurrency(0);
        else
            $editdata->FREIGHTAMOUNT    =   $this->formatslist->formatCurrency($editdata->FREIGHTAMOUNT);
        if(!$editdata->ADJUSTMENT)
            $editdata->ADJUSTMENT    =   $this->formatslist->formatCurrency(0);
        else
            $editdata->ADJUSTMENT    =   $this->formatslist->formatCurrency($editdata->ADJUSTMENT);
        $data['taxtotal']    =   $this->formatslist->formatCurrency(0);
        $data['editRec']    =   $editdata;
        $editinvlinesdata           =   $this->purchaseinvoice_model->getpilinesbyid($id);
        $data['editinvlinesRec']    =   $editinvlinesdata;
        $data['cnt']    =   count($editinvlinesdata);
        $data['nettotal']    =   0;
        $data['subtotal']   =   0;
        $this->load->model('partner/Suppliers_model');
        $supplierRec    =   $this->Suppliers_model->getSupplierById($editdata->SUPPLIERID);
        $supplierdetails    =   array();
        if($supplierRec){
            foreach ($supplierRec as $supplier){
                array_push($supplierdetails, array(
                    'ADDRESS' => $supplier->ADDRESS,
                    'CITY' => $supplier->CITY,
                    'REGION' => $supplier->REGION,
                    'COUNTRY' => $supplier->COUNTRY,
                    'POSTAL' => $supplier->POSTAL,
                    'PHONE' => $supplier->PHONE,
                    'EMAIL' => $supplier->EMAIL,
                ));
            }
            $data['supplierdata']    =   $supplierdetails[0];
        }else{
            $data['supplierdata']    =   $supplierdetails;
        }
        $data['template'] = 'inventory/pi_add';
        $this->load->view('template',$data);
    }
    
    function purchasereturn(){
        $user = $this->session->userdata('user');
        $get_where  = array('NAME' => $user, );
        $user_detail = $this->common->getWhere('PEOPLE',$get_where);
        foreach($user_detail as $userdetail){
           $user_id = $userdetail->ID;
        }
        $pid    =   $this->input->get('invoiceId');
        $editdata = $this->purchaseinvoice_model->getpibyid($pid);
        $datainsert['ID'] = uniqid();
        $id         = $datainsert['ID'];
        $datainsert['DELIVERYDATE'] =  date('Y-m-d',strtotime($editdata->DELIVERYDATE));
        $datainsert['SUPPLIERID'] =  $editdata->SUPPLIERID;
        $datainsert['REFERENCE'] =  $editdata->REFERENCE;
        $datainsert['ADJUSTMENT'] =  0;
        $datainsert['FREIGHTAMOUNT'] =  0;
        $datainsert['DISCOUNT'] =  0;
        $datainsert['ADJUSTMENT'] =  0;
        $datainsert['CREATEDBY'] = $user_id;
        $datainsert['STATUS'] = -1;
        $this->common->insert('PURCHASEINVOICE',$datainsert);
        $this->session->set_userdata(array('PRPIID'  => $id));
        echo $id;
    }
    
    function copyinvoice(){
        $user = $this->session->userdata('user');
        $get_where  = array('NAME' => $user, );
        $user_detail = $this->common->getWhere('PEOPLE',$get_where);
        foreach($user_detail as $userdetail){
           $user_id = $userdetail->ID;
        }
        $pid    =   $this->input->get('invoiceId');
        $editdata = $this->purchaseinvoice_model->getpibyid($pid);
        $datainsert['ID'] = uniqid();
        $id         = $datainsert['ID'];
        $datainsert['DELIVERYDATE'] =  date('Y-m-d');
        $datainsert['SUPPLIERID'] =  $editdata->SUPPLIERID;
//        $datainsert['REFERENCE'] =  $editdata->REFERENCE;
//        $datainsert['ADJUSTMENT'] =  0;
//        $datainsert['FREIGHTAMOUNT'] =  0;
//        $datainsert['DISCOUNT'] =  0;
        $datainsert['CREATEDBY'] = $user_id;
        if($editdata->STATUS>0)
            $datainsert['STATUS'] = 1;
        else if($editdata->STATUS<0)
            $datainsert['STATUS'] = -1;
        $this->common->insert('PURCHASEINVOICE',$datainsert);
        $editinvlinesdata           =   $this->purchaseinvoice_model->getpilinesbyid($pid);
        if($editinvlinesdata) {
            foreach($editinvlinesdata as $editinvlines) {
                $data = array(
                    'ID' => uniqid(),
                    'PIID' => $id,
                    'PRODUCT' => $editinvlines->PRODUCT,
                    'DESCRIPTION' => $editinvlines->DESCRIPTION,
                    'QUANTITY' => $editinvlines->QUANTITY,
//                    'UOM' => $editinvlines->UOM,
                    'UNITPRICE' => $editinvlines->UNITPRICE,
                    'TAXID' => $editinvlines->TAXID,
//                    'DISCOUNT' => $editinvlines->DISCOUNT
                );
                $this->common->insert('PURCHASEINVOICELINES',$data);
            }
        }
        $purchaseinvTaxList    =   $this->purchaseinvoice_model->getPurchaseInvoiceListGroupPInv($pid);
        if($purchaseinvTaxList){
            foreach($purchaseinvTaxList as $purchaseinvTaxRec){
                $taxRec   =   array(
                    'ID' => uniqid(),
                    'PIID' => $id,
                    'TAXID' => $purchaseinvTaxRec->TAXID,
                    'BASEAMOUNT' => $purchaseinvTaxRec->BASEAMOUNT,
                    'TAXAMOUNT' => $purchaseinvTaxRec->TAXAMOUNT,
                );
                $this->purchaseinvoice_model->insertTaxData($taxRec);
            }
        }
        
        echo "true";
    }
    
    
    function createnew($status=''){
        $user = $this->session->userdata('user');
        $get_where  = array('NAME' => $user, );
        $user_detail = $this->common->getWhere('PEOPLE',$get_where);
        foreach($user_detail as $userdetail) {
           $user_id = $userdetail->ID;
        }
        $datainsert['ID'] = uniqid();
        $id         = $datainsert['ID'];
        $this->session->set_userdata(array('PIID'  => $id));
        $datainsert['ADJUSTMENT'] =  0;
        $datainsert['CREATEDDATE'] = date("Y-m-d H:i:s");
        $datainsert['CREATEDBY'] = $user_id;
        $datainsert['DELIVERYDATE'] = date("Y-m-d");
        if($status==-1)
            $datainsert['STATUS'] = -1;
        else
            $datainsert['STATUS'] = 1;
        
        $this->common->insert('PURCHASEINVOICE',$datainsert);
        redirect('inventory/purchaseinvoice/create/'.$id);
    }

    function newpi() {
        $data['template'] = 'inventory/pi_new_view';
        $this->load->view('template',$data);
    }
    
    public function getpurchaseinvoice() {
        $data['data'] =  $this->purchaseinvoice_model->getpis();
        echo json_encode($data);
    }
    
    public function addpurchaseinvoice() {
        $id = $this->input->post('id');
        $user = $this->session->userdata('user');
        $get_where  = array('NAME' => $user, );
        $user_detail = $this->common->getWhere('PEOPLE',$get_where);
        foreach($user_detail as $userdetail) {
           $user_id = $userdetail->ID;
        }
        $data = array(
            'SUPPLIERID' => $this->input->post('SUPPLIER'),
            'REFERENCE' => $this->input->post('REFERENCE'),
            'DELIVERYDATE' => $this->input->post('DELIVERYDATE'),
            'TERMS' => $this->input->post('TERMS'),
            'FREIGHTAMOUNT' => $this->input->post('FREIGHTAMOUNT'),
            'DISCOUNT' => $this->input->post('DISCOUNT'),
            'ADJUSTMENT' => $this->input->post('ADJUSTMENT'),
            'STATUS' => $this->input->post('STATUS'),
        );
        if($id == '') {
            $data['REVISION'] = 0;
            $data['CREATEDBY'] = $user_id;
            $data['UPDATEDDATE'] = null;
            $this->common->insert('PURCHASEINVOICE',$data);
            $this->session->set_flashdata('success_msg', 'The record is added successfuly.');
        } else { 
            $data['UPDATEDBY'] = $user_id;
            $data['UPDATEDDATE'] = date('Y-m-d h:i:s', time());
            $where = array('ID' => $id);
            $this->session->set_flashdata('success_msg', 'The record has been updated successfuly.');
            $this->common->update('PURCHASEINVOICE',$where,$data);
        }
        redirect('inventory/purchaseinvoice');
    }
    
    public function addpurchaseinvoicelines() {
        $id = $this->input->post('id');
        $data = array(
            'PIID' => $this->input->post('addproductid'),
            'PRODUCT' => $this->input->post('PRODUCTID'),
            'DESCRIPTION' => $this->input->post('DESCRIPTION'),
            'QUANTITY' => ($this->input->post('QUANTITY') == '' ? 0.0 : $this->input->post('QUANTITY')),
            'UOM' => $this->input->post('UOM'),
            'UNITPRICE' => ($this->input->post('UNITPRICE') == '' ? 0.0 : $this->input->post('UNITPRICE')),
            'TAXAMOUNT' => ($this->input->post('TAXAMOUNT') == '' ? 0.0 : $this->input->post('TAXAMOUNT')),
            'DISCOUNT' => ($this->input->post('DISCOUNT') == '' ? 0.0 : $this->input->post('DISCOUNT'))
        );
        if($id == '') {
            $this->common->insert('PURCHASEINVOICELINES',$data);
            $this->session->set_flashdata('success_msg', 'The record is added successfuly.');
        } else {
            $where = array('ID' => $id);
            $this->session->set_flashdata('success_msg', 'The record has been updated successfuly.');
            $this->common->update('PURCHASEINVOICELINES',$where,$data);
        }
        redirect('inventory/purchaseinvoice');
    }
    public function editpurchaseinvoice($id) {
        $where = array('ID' => $id,);
        $data = $this->common->getWhere('PURCHASEINVOICE',$where);
        echo json_encode($data);
    }
    public function deletepurchaseinvoice($id) {
        $where = array('ID' => $id);  
        $this->common->delete('PURCHASEINVOICE',$where);
        $this->session->set_flashdata('success_msg', 'The record has been deleted successfuly.');
        redirect('inventory/purchaseinvoice');
    }
    function getpis() {
        echo $this->purchaseinvoice_model->getpis();
    }
    function getpilines($id) {
        $poid = $id;
        $data['data'] =  $this->purchaseinvoice_model->getpilines($poid);
        echo json_encode($data);
    }
    
    function getproductsautocomplete() {
        $term = $this->input->get('term', TRUE);
        $this->load->model('inventory/purchaseinvoice_model');
        $rows = $this->purchaseinvoice_model->getproductsautocomplete($term);
        $keywords = array();
//        foreach ($rows as $row)
//            array_push($keywords, $row->NAME);
        
        foreach ($rows as $row)
        {
            array_push($keywords, array(
                'CODE' => $row->CODE,
                'NAME' => $row->NAME,
                'ID' => $row->ID,
                'PRICEBUY' => $row->PRICEBUY,
                'PRICESELL' => $row->PRICESELL,
                'TAXCAT' => $row->TAXCAT,
                'value' => $row->NAME,
                'label' => $row->NAME
            ));
        }
        echo json_encode($keywords);
    }
    
    function getitemautocomplete() {
        $term = $this->input->post('term', TRUE);
        $this->load->model('inventory/materials_model');
        $rows = $this->materials_model->getitemautocomplete($term);
        $keywords = array();
        foreach ($rows as $row) {
            array_push($keywords, array(
                'code' => $row->CODE,
                'label' => $row->NAME,
                'value' => $row->ID,
                'price' => $row->PRICEBUY,
                'pricesell' => $row->PRICESELL
            ));
        }
        echo json_encode($keywords);
    }
    
    function getitembybarcode() {
        $term = $this->input->post('term', TRUE);
        $this->load->model('inventory/materials_model');
        $rows = $this->materials_model->getitembybarcode($term);
        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, array(
                'code' => $row->CODE,
                'label' => $row->NAME,
                'value' => $row->ID,
                'price' => $row->PRICEBUY,
                'pricesell' => $row->PRICESELL
            ));
        echo json_encode($keywords);
    }
    
    function record() {
        $oper = $this->input->post('oper');
        if ($oper == 'del') {
            $id = $this->input->post('id');
            if ($id) {
                $this->purchaseinvoice_model->delete($id);
                $fdata = array('msgt' => 'S', 'msg' => 'Purchase invoice deleted successfully.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'inventory/purchaseinvoice');
            } else {
                $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete purchase invoice.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'app/purchaseinvoice');
            }
        } else {
            $form_data = array(
                'SUPPLIERID' => ($this->input->post('SUPPLIERID') == '' ? null : $this->input->post('SUPPLIERID')),
                'REFERENCE' => $this->input->post('REFERENCE'),
                'DELIVERYDATE' => ($this->input->post('DELIVERYDATE') == '' ? null : $this->input->post('DELIVERYDATE')),
                'TERMS' => $this->input->post('TERMS'),
                'FREIGHTAMOUNT' => ($this->input->post('FREIGHTAMOUNT') == '' ? 0.0 : $this->input->post('FREIGHTAMOUNT')),
                'TAXAMOUNT' => ($this->input->post('TAXAMOUNT') == '' ? 0.0 : $this->input->post('TAXAMOUNT')),
                'DISCOUNT' => ($this->input->post('DISCOUNT') == '' ? 0.0 : $this->input->post('DISCOUNT')),
                'ADJUSTMENT' => ($this->input->post('ADJUSTMENT') == '' ? 0.0 : $this->input->post('ADJUSTMENT')),
                'STATUS' => $this->input->post('STATUS')
            );
            if ($oper == 'add') {
                $form_data['REVISION'] = 0;
                $form_data['CREATEDBY'] = $this->session->userdata('empid');
                $form_data['UPDATEDDATE'] = null;
                if ($this->purchaseinvoice_model->add($form_data) == TRUE) {
                    $fdata = array('msgt' => 'S', 'msg' => 'Purchase invoice created successfully.');
                    $this->session->set_flashdata($fdata);
                    return true;
                }
            } elseif ($oper == 'edit') {
                $form_data['UPDATEDBY'] = $this->session->userdata('empid');
                $form_data['UPDATEDDATE'] = date('Y-m-d h:i:s', time());
                $id = $this->input->post('id');
                if ($id) {
                    $this->purchaseinvoice_model->update($id, $form_data);
                }
            }
        }
    }
    
    function recordline() {
        $oper = $this->input->post('oper');
        if ($oper == 'del') {
            $id = $this->input->post('id');
            if ($id) {
                $this->purchaseinvoice_model->deleteline($id);
                $fdata = array('msgt' => 'S', 'msg' => 'Purchase invoice line deleted successfully.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'inventory/purchaseinvoice');
            } else {
                $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete purchase invoice line.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'inventory/purchaseinvoice');
            }
        } else {
            $form_data = array(
                'PIID' => $this->uri->segment(4),
                'PRODUCT' => $this->input->post('PRODUCTID'),
                'DESCRIPTION' => $this->input->post('DESCRIPTION'),
                'QUANTITY' => ($this->input->post('QUANTITY') == '' ? 0.0 : $this->input->post('QUANTITY')),
                'UOM' => $this->input->post('UOM'),
                'UNITPRICE' => ($this->input->post('UNITPRICE') == '' ? 0.0 : $this->input->post('UNITPRICE')),
                'TAXAMOUNT' => ($this->input->post('TAXAMOUNT') == '' ? 0.0 : $this->input->post('TAXAMOUNT')),
                'DISCOUNT' => ($this->input->post('DISCOUNT') == '' ? 0.0 : $this->input->post('DISCOUNT'))
            );
            if ($oper == 'add') {
                if ($this->purchaseinvoice_model->addline($form_data) == TRUE) {
                    $fdata = array('msgt' => 'S', 'msg' => 'Purchase invoice line added successfully.');
                    $this->session->set_flashdata($fdata);
                    return true;
                }
            } elseif ($oper == 'edit') {
                $id = $this->input->post('id');
                if ($id) {
                    $this->purchaseinvoice_model->updateline($id, $form_data);
                    $fdata = array('msgt' => 'S', 'msg' => 'Purchase invoice line edited successfully.');
                    $this->session->set_flashdata($fdata);
                    return true;
                }
            }
        }
    }
    
    function submitpi() {
        $piid = $this->uri->segment(4);
        $pi = $this->purchaseinvoice_model->getpibyid($piid);
        $pros = $this->purchaseinvoice_model->getpilinesbyid($piid);
        
        $locale = $this->companyinfo_model->getlocaleinfo();
        if($locale->LOCATION)
            $warehousesel   =   $locale->LOCATION;
        else
            $warehousesel   =   0;
        if (($pi->STATUS==1 || $pi->STATUS==-1) && $pi->DELIVERYDATE!=null && $pi->REFERENCE!=null &&  sizeof($pros) > 0  && $pi->SUPPLIERID!=null) {
            for ($i = 0; $i < count($pros); $i++) {
                $mats = $this->stock_model->getMaterialsProd($pros[$i]->PRODUCT);
                if (sizeof($mats) > 0) {
                    
                    
                    for ($j = 0; $j < count($mats); $j++) {
                        $mat_data = array(
                            'ID' => uniqid(),
                            'DATENEW' => $pi->DELIVERYDATE,
                            'REASON' => 1,
                            'LOCATION' => $warehousesel,
                            'SUPPLIER' => $pi->SUPPLIERID,
                            'PRODUCT' => $mats[$j]->MATERIAL,
                            'UNITS' => $pros[$i]->QUANTITY * $mats[$j]->UNITS,
                            'PRICE' => ($pros[$i]->UNITPRICE/count($mats))/$mats[$j]->UNITS
                        );
                        if ($this->stock_model->add($mat_data) == TRUE) {
                            //UPDATE CURRENTSTOCK
                            $pidinstock = $this->goodsreceipts_model->productInStockCurrent($mats[$j]->MATERIAL, $warehousesel);
                            if ($pidinstock) {
                                $currentstock=$pidinstock[0]->UNITS;
                                $this->goodsreceipts_model->updateStockcurrent($warehousesel, $mats[$j]->MATERIAL, $pros[$i]->QUANTITY * $mats[$j]->UNITS);
                            } else {
                                $currentstock=0;
                                $this->goodsreceipts_model->insertStockcurrent($warehousesel, $mats[$j]->MATERIAL, $pros[$i]->QUANTITY * $mats[$j]->UNITS);
                            }
                            
                            $this->products_model->productpricecalculation(($pros[$i]->UNITPRICE/count($mats))/$mats[$j]->UNITS,$mats[$j]->MATERIAL, $currentstock, $pros[$i]->QUANTITY);
                            // $this->goodsreceipts_model->updateProductCost($mats[$j]->MATERIAL, $pros[$i]->UNITPRICE/$mats[$j]->UNITS);
                            
                        }
                    }
                } else {
                    $pro_data = array(
                        'ID' => uniqid(),
                        'DATENEW' => $pi->DELIVERYDATE,
                        'REASON' => 1,
                        'LOCATION' => $warehousesel,
                        'SUPPLIER' => $pi->SUPPLIERID,
                        'PRODUCT' => $pros[$i]->PRODUCT,
                        'UNITS' => $pros[$i]->QUANTITY,
                        'PRICE' => $pros[$i]->UNITPRICE,
                    );
                    
                    if ($this->stock_model->add($pro_data) == TRUE) {
                        //UPDATE CURRENTSTOCK
                        $pidinstock = $this->goodsreceipts_model->productInStockCurrent($pros[$i]->PRODUCT, $warehousesel);
                        if ($pidinstock) {
                            $currentstock=$pidinstock[0]->UNITS;
                            $this->goodsreceipts_model->updateStockcurrent($warehousesel, $pros[$i]->PRODUCT, $pros[$i]->QUANTITY);
                        } else {
                            $currentstock=0;
                            $this->goodsreceipts_model->insertStockcurrent($warehousesel, $pros[$i]->PRODUCT, $pros[$i]->QUANTITY);
                        }
                        
                        $this->products_model->productpricecalculation($pros[$i]->UNITPRICE,$pros[$i]->PRODUCT, $currentstock, $pros[$i]->QUANTITY);
                        $mprodctlist = $this->products_model->productmaterialidwise($pros[$i]->PRODUCT);
                        
                        if($mprodctlist) {
                            foreach($mprodctlist as $mprodctrec) {
                                $productrec = $this->products_model->productmaterialmaterialwise($mprodctrec->PRODUCT);
                                $this->goodsreceipts_model->updateProductCost($productrec->PRODUCT, $productrec->TOTALAMOUNT);
//                                $this->products_model->productpricecalculation($productrec->TOTALAMOUNT,$productrec->PRODUCT);
                            }
                        }
                    }
                }
            }
            if($pi->STATUS==1)
            {
                $this->purchaseinvoice_model->updatepistatus($piid,2);
            }
            else if($pi->STATUS==-1)
            {
                $this->purchaseinvoice_model->updatepistatus($piid,-2);
            }
            $user = $this->session->userdata('user');
            $get_where  = array('NAME' => $user, );
            $user_detail = $this->common->getWhere('PEOPLE',$get_where);
            foreach($user_detail as $userdetail) {
               $user_id = $userdetail->ID;
            }
            $this->purchaseinvoice_model->updatePICreatedValues($piid,$user_id);
            $this->purchaseinvoice_model->updatepisuppliercredit($pi->SUPPLIERID,$pi->TOTALAMOUNT,$pi->DELIVERYDATE);
            $fdata = array('msgt' => 'S', 'msg' => 'Purchase invoice submitted successfully.');
            $this->session->set_flashdata($fdata);
            redirect(site_url() . 'inventory/purchaseinvoice');
        } else {
            $msg    =   "Sorry You Can't Submit the Invoice !!! Invoice must have Atleast Following Data: <br/>";
            $msg    =   $msg."1) Invoice Date<br/>";
            $msg    =   $msg."2) Invoice Number<br/>";
            $msg    =   $msg."3) Supplier<br/>";
            $msg    =   $msg."4) Atleast One Item in the List<br/>";
            $fdata = array('msgt' => 'E', 'msg' => $msg);
            $this->session->set_flashdata($fdata);
            redirect(site_url() . 'inventory/purchaseinvoice/create/'.$piid);
        }
    }
    function companyinfo(){
        $this->load->model('settings/companyinfo_model');
        var_dump($this->companyinfo_model->getcompanyinfo('0'));
    }
    function printpi() {
        $this->load->library('session');
        $this->load->helper('dompdf');
        $this->load->helper('file');
        $this->load->model('settings/companyinfo_model');
        $this->load->model('reports/inventory_model');
        $data['companyinfo'] = $this->companyinfo_model->getcompanyinfo('0');
        $data['po'] = $this->purchaseinvoice_model->getpibyid($this->uri->segment(4));
        $data['polines'] = $this->purchaseinvoice_model->getpilinesbyid($this->uri->segment(4));
        $this->load->model('reports/report_model');
        $data['columns'] = $this->report_model->getcolumns('INVENTORY');
        $data['reportlabel'] = '';
        if($data['po']->STATUS==-1 || $data['po']->STATUS==-2) {
            $data['reporttitle'] = 'Purchase Return';
            $data['reportlabel'] = ' Purchase Return# ';
        } else if($data['po']->STATUS==1 || $data['po']->STATUS==2) {
            $data['reporttitle'] = 'Purchase Invoice';
            $data['reportlabel'] = 'Purchase Invoice# ';
        }
        
        $taxRecData = $this->purchaseinvoice_model->getPurchaseInvoiceTaxes($this->uri->segment(4));
        $resultData='';
        if($taxRecData){
            foreach($taxRecData as $taxRec){
                $resultData.=   '<div style="font-size: 11px;">'.$taxRec->NAME." : ".$this->formatslist->formatCurrencywithHash($taxRec->TAXAMOUNT).'</div>';
            }
        }
        $data["taxresultdata"] =   $resultData;
        $html = $this->load->view('inventory/purchaseinvoice_print', $data, true);
        $this->load->library('Pdf');
        $pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
        $pdf->SetMargins(10, 10, 10, true);
        $pdf->SetCreator('Saleculator');
        $pdf->SetAuthor('Shameer C K');
        if($data['po']->STATUS==-1 || $data['po']->STATUS==-2) {
            $pdf->SetTitle('Purchase Return');
            $pdf->SetSubject('Purchase Return');
        } else if($data['po']->STATUS==1 || $data['po']->STATUS==2) {
            $pdf->SetTitle('Purchase Invoice');
            $pdf->SetSubject('Purchase Invoice');
        }
        if($data['po']->STATUS==-1 || $data['po']->STATUS==-2)
            $pdf->SetHeaderData(K_BLANK_IMAGE, PDF_HEADER_LOGO_WIDTH, $data['companyinfo']->COMPANYNAME."#Purchase Return", $data['companyinfo']->ADDRESS1."\nPhone: ".$data['companyinfo']->PHONE1."\n".$data['companyinfo']->EMAIL.', '.$data['companyinfo']->WEBSITE."\nTRN: ".$data['companyinfo']->TAXID);
        else if($data['po']->STATUS==1 || $data['po']->STATUS==2)
            $pdf->SetHeaderData(K_BLANK_IMAGE, PDF_HEADER_LOGO_WIDTH, $data['companyinfo']->COMPANYNAME."#Purchase Invoice", $data['companyinfo']->ADDRESS1."\nPhone: ".$data['companyinfo']->PHONE1."\n".$data['companyinfo']->EMAIL.', '.$data['companyinfo']->WEBSITE."\nTax Id: ".$data['companyinfo']->TAXID);
        
        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
        //set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        //set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        // ---------------------------------------------------------
        // set font
        $pdf->SetFont('helvetica', '', 11);
        // add a page
        //$pdf->AddPage();
        $pdf->AddPage();
        $pdf->writeHTML($html, true, false, true, false, '');
        //var_dump($html);exit;
        //echo $html;exit;
        // Print some HTML Cells
        // reset pointer to the last page
        $pdf->lastPage();
        // ---------------------------------------------------------
        //Close and output PDF document
        $pdf->Output('PI'.$data['po']->PLID.'.pdf', 'I');
    }

    function printpo() {
        $this->load->library('session');
        $this->load->helper('dompdf');
        $this->load->helper('file');
        $this->load->model('settings/companyinfo_model');
        $this->load->model('reports/inventory_model');
        $data['companyinfo'] = $this->companyinfo_model->getcompanyinfo('0');
        $data['po'] = $this->purchaseinvoice_model->getpibyid($this->uri->segment(4));
        $data['polines'] = $this->purchaseinvoice_model->getpilinesbyid($this->uri->segment(4));
        $this->load->model('reports/report_model');
        $data['columns'] = $this->report_model->getcolumns('INVENTORY');
        $data['reporttitle'] = 'Purchase Invoice';
        $html = $this->load->view('inventory/purchaseinvoice_print', $data, true);
        $this->load->library('Pdf');
$pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetMargins(10, 10, 10, true);
$pdf->SetCreator('Saleculator');
$pdf->SetAuthor('Shameer C K');
$pdf->SetTitle('Purchase Order');
$pdf->SetSubject('Purchase Order');
//$pdf->SetKeywords('Posics, PDF, example, test, guide');

$pdf->SetHeaderData(K_BLANK_IMAGE, PDF_HEADER_LOGO_WIDTH, $data['companyinfo']->COMPANYNAME."#Purchase Order", $data['companyinfo']->ADDRESS1."\nPhone: ".$data['companyinfo']->PHONE1."\n".$data['companyinfo']->EMAIL.', '.$data['companyinfo']->WEBSITE);    
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
//set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
//set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// ---------------------------------------------------------
// set font
$pdf->SetFont('helvetica', '', 11);
// add a page
//$pdf->AddPage();
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, '');
// Print some HTML Cells
// reset pointer to the last page
$pdf->lastPage();
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('PO'.$data['po']->PIID.'.pdf', 'I');
    }

    function getsupplierautocomplete() {
        $term = $this->input->post('term', TRUE);
        $this->load->model('partner/suppliers_model');
        $rows = $this->suppliers_model->getsupplierautocomplete($term);
        $keywords = array();
        foreach ($rows as $row)
            array_push($keywords, array(
                'label' => $row->NAME,
                'value' => $row->ID
            ));
        echo json_encode($keywords);
    }
    /**************************** Added BY John *******************************/
    // PURCHASE INVOICE LIST
    public function listpurchaseinvoice() {
        $columns = array(
            0 =>'sl', 
            1=> 'REFERENCE',
            2 =>'name',
            3=> 'DELIVERYDATE',
            4=> 'TOTALAMOUNT',
            5=> 'PAIDAMOUNT',
            6=> 'BALANCE',
            7=> 'STATUS',
            8=> 'ID'
        );
        $limit = $this->input->post('length'); 
        $start = $this->input->post('start');
        if($this->input->post('order')[0]['column']) {
            $order = $columns[$this->input->post('order')[0]['column']];
            $dir = $this->input->post('order')[0]['dir'];
        } else {
            $order= 'CREATEDDATE';
            $dir = 'DESC';
        }
            
        $search_array = array();
        if(!empty($_POST['purchaseinvoicetype'])){
            $search_array['purchaseinvoicetype'] = $_POST['purchaseinvoicetype'];
        }
        if(!empty($_POST['searchtext'])){
            $search_array['searchtext'] = $_POST['searchtext'];
        }
        if(!empty($_POST['fromdate'])){
            $search_array['fromdate'] = date("Y-m-d",strtotime($_POST['fromdate']));
        }
        if(!empty($_POST['todate'])){
            $search_array['todate'] = date("Y-m-d",strtotime($_POST['todate']));
        }
        
        if(count($search_array)==0) {
            $totalData = $this->purchaseinvoice_model->all_purchaseinvoice_count();
            $totalFiltered = $totalData;
            $purchaseinvoicelist = $this->purchaseinvoice_model->all_purchaseinvoice_list($limit,$start,$dir,$order);
            $totcount   =   $totalData;
        } else {
            $purchaseinvoicelist =  $this->purchaseinvoice_model->purchaseinvoice_search($limit,$start,$search_array,$dir,$order);
            $totalData = $this->purchaseinvoice_model->purchaseinvoice_searchcount($search_array);
            $totalFiltered = $totalData;
            if($totalFiltered>0) {
                $totcount   =   $totalFiltered;
            } else {
                $totcount   =   0;
            }
        }
        $data = array();
        if(!empty($purchaseinvoicelist)) {
            $account_id = 0;
            $j = $start+1;
            foreach ($purchaseinvoicelist as $aRow){
//                $nestedData['sl'] = $j;
                $row['sl'] = $j;
                $row['DELIVERYDATE'] = $this->formatslist->dateFormat($aRow->DELIVERYDATE);
                $row['REFERENCE'] = $aRow->REFERENCE;
                $row['name'] = $aRow->name;
                $row['TOTALAMOUNT'] = $this->formatslist->formatCurrencywithHash($aRow->TOTALAMOUNT);
                $row['PAIDAMOUNT'] = $this->formatslist->formatCurrencywithHash($aRow->PAIDAMOUNT);
                $tmpamnt    =   abs($aRow->BALANCE);
                if($tmpamnt==0)
                    $amountbal  =   $this->formatslist->formatCurrencywithHash(0);
                else
                    $amountbal  =   $this->formatslist->formatCurrencywithHash($aRow->BALANCE);
                $row['BALANCE'] = $amountbal;
                
                if($aRow->STATUS=='1')
                    $row['STATUS'] =  '<div class="buttons-preview"><span class="label label-primary shiny">'.$this->lang->line("CREATED").'</span></div>';
                else if($aRow->STATUS=='2')
                    $row['STATUS'] =  '<div class="buttons-preview"><span class="label label-success shiny">'.$this->lang->line("SUBMITTED").'</a></div>';
                else if($aRow->STATUS=='-1')
                    $row['STATUS'] =  '<div class="buttons-preview"><span class="label label-danger shiny">'.$this->lang->line("RETURNED").'</a></div>';
                else if($aRow->STATUS=='-2')
                    $row['STATUS'] =  '<div class="buttons-preview"><span class="label label-maroon shiny">'.$this->lang->line("RETURNSUBMITTED").'</a></div>';
                
                if($aRow->STATUS=='1' ||$aRow->STATUS=='-1')
                    $row['ID'] =  '<div class="buttons-preview"><a class="btn btn-info shiny btn-xs"'
                    . ' href="'.base_url().'inventory/purchaseinvoice/create/'.$aRow->ID.'"><i class="fa fa-pencil-square-o"></i></a></div>';
                else
                    $row['ID'] =  '<div class="buttons-preview"><a class="btn btn-warning shiny btn-xs"'
                    . ' href="'.base_url().'inventory/purchaseinvoice/create/'.$aRow->ID.'" title="View"><i class="fa fa-eye"></i></a></div>';
                $data[] = $row;
                $j++;
            }
        }
        $json_data = array(
            "draw"            => intval($this->input->post('draw')),  
            "recordsTotal"    => intval($totcount),  
            "recordsFiltered" => intval($totalFiltered), 
            "data"            => $data   
        );
        echo json_encode($json_data);
        
    }

    // Delete Purchase Invoice
    public function deletepurchaseinvoicecontroller($id = NULL) {
        $this->load->model('inventory/Purchaseinvoice_model');
        $this->Purchaseinvoice_model->deleteinvoicerecmodel($id);
        $this->session->set_flashdata('success_msg', 'The record has been deleted successfuly.');
        redirect('inventory/purchaseinvoice');
    }
    // Get supplier By Name
    function getsuppliersbyname() {
        $term = $this->input->get('term', TRUE);
        $this->load->model('partner/suppliers_model');
        $rows = $this->suppliers_model->getsupplierautocomplete($term);
        $keywords = array();
        foreach ($rows as $row){
            array_push($keywords, array(
                'value' => $row->NAME." - ".$row->TAXID,
                'address' => $row->ADDRESS,
                'postal' => $row->POSTAL,
                'city' => $row->CITY,
                'region' => $row->REGION,
                'country' => $row->COUNTRY,
                'phone' => $row->PHONE,
                'email' => $row->EMAIL,
                'id' => $row->ID
            ));
        }
        echo json_encode($keywords);
    }
    
    // Create Purchase Invoice Items.
    public function managepurchaseinvlines() {
        $id = $this->input->get('id');
        $data = array(
            'PIID' => $this->input->get('PIID'),
            'PRODUCT' => $this->input->get('PRODUCTID'),
            'DESCRIPTION' => $this->input->get('DESCRIPTION'),
            'QUANTITY' => ($this->input->get('QUANTITY') == '' ? 0.0 : $this->input->get('QUANTITY')),
            //'UOM' => $this->input->get('UOM'),
            'UNITPRICE' => ($this->input->get('UNITPRICE') == '' ? 0.0 : $this->input->get('UNITPRICE')),
            'TAXID' => ($this->input->get('TAXID') == '' ? 0.0 : $this->input->get('TAXID')),
            'DISCOUNT' => ($this->input->get('DISCOUNT') == '' ? 0.0 : -1*abs($this->input->get('DISCOUNT')))
        );
        if($id == ''){
            $data["ID"] = uniqid();
            $this->common->insert('PURCHASEINVOICELINES',$data);
            $retData["id"]          =    $data["ID"];
            $retData["txtindex"]    =    $this->input->get('txtindex');
            if($this->purchaseinvoice_model->deleteTaxByPinvId($this->input->get('PIID'))){
                $purchaseinvTaxList    =   $this->purchaseinvoice_model->getPurchaseInvoiceListGroupPInv($this->input->get('PIID'));
                if($purchaseinvTaxList){
                    foreach($purchaseinvTaxList as $purchaseinvTaxRec){
                        $taxRec   =   array(
                            'ID' => uniqid(),
                            'PIID' => $this->input->get('PIID'),
                            'TAXID' => $purchaseinvTaxRec->TAXID,
                            'BASEAMOUNT' => $purchaseinvTaxRec->BASEAMOUNT,
                            'TAXAMOUNT' => $purchaseinvTaxRec->TAXAMOUNT,
                        );
                        $this->purchaseinvoice_model->insertTaxData($taxRec);
                    }
                }
            }
            echo json_encode($retData);
        } else {
            $where = array('ID' => $id);
            $this->common->update('PURCHASEINVOICELINES',$where,$data);
            $retData["id"]          =   $id;
            $retData["txtindex"]    =    $this->input->get('txtindex');
            if($this->purchaseinvoice_model->deleteTaxByPinvId($this->input->get('PIID'))){
                $purchaseinvTaxList    =   $this->purchaseinvoice_model->getPurchaseInvoiceListGroupPInv($this->input->get('PIID'));
                if($purchaseinvTaxList){
                    foreach($purchaseinvTaxList as $purchaseinvTaxRec){
                        $taxRec   =   array(
                            'ID' => uniqid(),
                            'PIID' => $this->input->get('PIID'),
                            'TAXID' => $purchaseinvTaxRec->TAXID,
                            'BASEAMOUNT' => $purchaseinvTaxRec->BASEAMOUNT,
                            'TAXAMOUNT' => $purchaseinvTaxRec->TAXAMOUNT,
                        );
                        $this->purchaseinvoice_model->insertTaxData($taxRec);
                    }
                }
            }
            echo json_encode($retData);
        }
    }

    public function deletepurchaseinvoicelinesrec() {
        $id = $this->input->get('id');
        $where = array('ID' => $id);  
        $retvalue   =   $this->common->delete('PURCHASEINVOICELINES',$where);
        if($this->purchaseinvoice_model->deleteTaxByPinvId($this->input->get('PIID'))){
            $purchaseinvTaxList    =   $this->purchaseinvoice_model->getPurchaseInvoiceListGroupPInv($this->input->get('PIID'));
            if($purchaseinvTaxList){
                foreach($purchaseinvTaxList as $purchaseinvTaxRec){
                    $taxRec   =   array(
                        'ID' => uniqid(),
                        'PIID' => $this->input->get('PIID'),
                        'TAXID' => $purchaseinvTaxRec->TAXID,
                        'BASEAMOUNT' => $purchaseinvTaxRec->BASEAMOUNT,
                        'TAXAMOUNT' => $purchaseinvTaxRec->TAXAMOUNT,
                    );
                    $this->purchaseinvoice_model->insertTaxData($taxRec);
                }
            }
        }
        if($retvalue)
            $respdata["status"] =   'success';
        else
            $respdata["status"] =   'fail';
        echo json_encode($respdata);
    }
    // get submitted purchace invoice list
    public function PurchaseInvoiceListByStatus(){
        $status = $this->input->get('status');
        $this->load->model('inventory/Purchaseinvoice_model');
        $rows = $this->Purchaseinvoice_model->getpurchaseinvoicelist($status);
        echo json_encode($rows);
    }
    // list purchase invoice tax details
    public function purchaseInvoiceTax($id=''){
        $id = $this->input->get('PIID');
        $taxRecData = $this->purchaseinvoice_model->getPurchaseInvoiceTaxes($id);
        $resultData='';
        if($taxRecData){
            foreach($taxRecData as $taxRec){
                $resultData.=   '<div style="font-size: 11px;"><div style="float:left;">'.$taxRec->NAME." : </div>".$this->formatslist->formatCurrencywithHash($taxRec->TAXAMOUNT).'</div>';
            }
            echo $resultData;
        }
    }
    public function productlistall(){
        $this->load->model('inventory/Products_model');
        // coulmn declaration
        $aColumns = array( 'C.NAME','P.REFERENCE','P.CODE','P.NAME','P.PRICEBUY','P.PRICESELL');
        // set limit
        $sLimit = "";
        if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' ){
          $sLimit = "LIMIT ".$_GET['iDisplayStart'].", ".$_GET['iDisplayLength'];
        }
        //Ordering
        if ( isset( $_GET['iSortCol_0'] ) ) {
            $sOrder = " ORDER BY  ";
            for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {
                if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" ) {
                    if($aColumns[ intval( $_GET['iSortCol_'.$i] ) ]!='sl') {
                        $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                        ".$_GET['sSortDir_'.$i].", ";
                    }
                }
            }
            $sOrder = substr_replace( $sOrder, "", -2 );
            if ( $sOrder == " ORDER BY" ) {
              $sOrder = "";
            }
        }
        $sWhere = "";
        if ( $_GET['sSearch'] != "" ) {
            $sWhere = "WHERE (";
            for ( $i=0 ; $i<4 ; $i++ ) {
                $sWhere .= $aColumns[$i]." LIKE '%".$_GET['sSearch']."%' OR ";
            }
            $sWhere = substr_replace( $sWhere, "", -3 );
            $sWhere .= ')';
        }
        // get data
        $order = str_replace(" ORDER BY", '', $sOrder);  
        // echo $sLimit;
        $limit = ' '.$sLimit;
        if($sWhere!='') {
            //$where = ' AND ';
            $where = str_replace(" WHERE", '',$sWhere); 
        } else {
            $where = '';
        }
        $barcodesearchchar    =   $_GET["sSearch_0"];
        if($sWhere){
            if($barcodesearchchar){
                $where .= " AND P.CODE='".$barcodesearchchar."'";
            }
        }else{
            if($barcodesearchchar){
                $where .= " WHERE P.CODE='".$barcodesearchchar."'";
            }
        }
        // echo $where;exit;
        $sql = "SELECT P.*,C.NAME AS CATEGORYNAME from PRODUCTS P LEFT JOIN CATEGORIES C ON P.CATEGORY=C.ID ".$where.$sOrder.$limit;
        //echo $sql;  exit;
        $arr = $this->common->customquery($sql);
        $totalCount_sql   =  "SELECT count(*)AS total FROM PRODUCTS P LEFT JOIN CATEGORIES C ON P.CATEGORY=C.ID ".$where;
        $totalCount = $this->common->customquery($totalCount_sql);
        // echo"<pre>";print_r($totalCount);
        $iTotal  = $totalCount[0]->total;
        /*
         * Output
         */
        $output = array(
          "sEcho" => intval($_GET['sEcho']),
          "iTotalRecords" => $iTotal,
          "iTotalDisplayRecords" => $iTotal,
          "aaData" => array()
        );
        $j=1;
        unset($aColumns[1]);
        $aColumns[1] = 'categoryname';
        unset($aColumns[8]);
        $aColumns[7] = 'taxcategory';
        $currencyFormat = $this->formatslist->formatCurrency(0);
        $currencyDecimel = strlen(substr(strrchr($currencyFormat, "."), 1));
        // echo "<pre>";print_r($arr);
        // echo sizeof($arr);
        if($arr!='') {
            foreach ($arr as $key => $aRow) {
                $row = array();
                $row[0] = '<a href="javascript:void(0)" onclick="selectItemgrid(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;,&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->TAXCAT.'&quot;)">'.$aRow->CATEGORYNAME.'</a>';
                $row[1] = '<a href="javascript:void(0)" onclick="selectItemgrid(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;,&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->TAXCAT.'&quot;)">'.$aRow->REFERENCE.'</a>';
                $row[2] = '<a href="javascript:void(0)" onclick="selectItemgrid(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;,&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->TAXCAT.'&quot;)">'.$aRow->CODE.'</a>';
                $row[3] = '<a href="javascript:void(0)" onclick="selectItemgrid(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;,&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->TAXCAT.'&quot;)">'.$aRow->NAME.'</a>';
                $row[4] = '<a href="javascript:void(0)" onclick="selectItemgrid(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;,&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->TAXCAT.'&quot;)">'.$this->formatslist->formatCurrencywithHash($aRow->PRICEBUY).'</a>';
                $row[5] = '<a href="javascript:void(0)" onclick="selectItemgrid(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;,&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->TAXCAT.'&quot;)">'.$this->formatslist->formatCurrencywithHash($aRow->PRICESELL).'</a>';
                $compinfdet    =   $this->companyinfo_model->getlocaleinfo();
                $stockdet    =   $this->stock_model->getproductstock($aRow->ID,$compinfdet->LOCATION);
                $row[6] = '<a href="javascript:void(0)" onclick="selectItemgrid(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->CODE.'&quot;,&quot;'.$aRow->NAME.'&quot;,&quot;'.$aRow->PRICEBUY.'&quot;,&quot;'.$aRow->TAXCAT.'&quot;)">'.$stockdet[0]["UNITS"].'</a>';
                $row[7] = '<a class="btn btn-info btn-xs" onclick="myFunction(&quot;'.$aRow->ID.'&quot;)"><i class="fa fa-edit"></i>
     </a>&nbsp;&nbsp;';
                $output['aaData'][] = $row;
                $j++;
            }
        } else {

        }
        // print_r($output);
       echo json_encode( $output );
    }
    
    function leadsupplierlistall () {
        error_reporting(0);
        $this->load->model('inventory/Products_model');
        $aColumns = array('NAME','SEARCHKEY','TAXID','EMAIL','PHONE','CURDEBT');
        $sLimit = "";
        if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' ) {
            $sLimit = "LIMIT ".$_GET['iDisplayStart'].", ".$_GET['iDisplayLength'];
        }
        if (isset($_GET['iSortCol_0'])) {
            $sOrder = " ORDER BY  ";
            for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ ) {
                if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" ) {
                    if($aColumns[ intval( $_GET['iSortCol_'.$i] ) ]!='sl') {
                        $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                        ".$_GET['sSortDir_'.$i].", ";
                    }
                }
            }
            $sOrder = substr_replace( $sOrder, "", -2 );
            if ( $sOrder == " ORDER BY" ) {
              $sOrder = "";
            }
        }
        /* 
        * Filtering
        */
        $sWhere = "";
        if ( $_GET['sSearch'] != "" ) {
            $sWhere = " AND (";
            for ( $i=0 ; $i<6 ; $i++ ) {
                $sWhere .= $aColumns[$i]." LIKE '%".$_GET['sSearch']."%' OR ";
            }
            $sWhere = substr_replace( $sWhere, "", -3 );
            $sWhere .= ')';
        }
        // get data
        $order = str_replace(" ORDER BY", '', $sOrder);  
        // echo $sLimit;
        $limit = ' '.$sLimit;
        if($sWhere!='') {
            //$where = ' AND ';
            $where = str_replace(" AND ", ' AND ',$sWhere); 
        } else {
            $where = '';
        }

        $barcodesearchchar    =   $_GET["sSearch_0"];
        if($sWhere){
            if($barcodesearchchar){
                $where .= " AND P.CODE='".$barcodesearchchar."'";
            }
        }else{
            if($barcodesearchchar){
                $where .= " AND P.CODE='".$barcodesearchchar."'";
            }
        }
        $sql = "SELECT * from SUPPLIERS WHERE 1 ".$where.$sOrder.$limit;
        $arr = $this->common->customquery($sql);
        $totalCount_sql   =  "SELECT count(*) AS total from SUPPLIERS WHERE 1 ".$where;
        $totalCount = $this->common->customquery($totalCount_sql);
        $iTotal  = $totalCount[0]->total;
        /*
        * Output
        */
        $output = array(
            "sEcho" => intval($_GET['sEcho']),
            "iTotalRecords" => $iTotal,
            "iTotalDisplayRecords" => $iTotal,
            "aaData" => array()
        );
        $j=1;
        if($arr!='') {
            foreach ($arr as $key => $aRow) {
                $row = array();
                $row[0] = '<a href="javascript:void(0)" onclick="setsupplierdetails(&quot;'.$aRow->NAME.'&quot;,&quot;'.trim(preg_replace('/\s\s+/', ' ', $aRow->ADDRESS)).'&quot;,&quot;'.$aRow->CITY.'&quot;,&quot;'.$aRow->REGION.'&quot;,&quot;'.$aRow->COUNTRY.'&quot;,&quot;'.$aRow->POSTAL.'&quot;,&quot;'.$aRow->PHONE.'&quot;,&quot;'.$aRow->EMAIL.'&quot;,&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->TAXID.'&quot;)">'.$aRow->NAME.'</a>';
                $row[1] = '<a href="javascript:void(0)" onclick="setsupplierdetails(&quot;'.$aRow->NAME.'&quot;,&quot;'.trim(preg_replace('/\s\s+/', ' ', $aRow->ADDRESS)).'&quot;,&quot;'.$aRow->CITY.'&quot;,&quot;'.$aRow->REGION.'&quot;,&quot;'.$aRow->COUNTRY.'&quot;,&quot;'.$aRow->POSTAL.'&quot;,&quot;'.$aRow->PHONE.'&quot;,&quot;'.$aRow->EMAIL.'&quot;,&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->TAXID.'&quot;)">'.$aRow->SEARCHKEY.'</a>';
                $row[2] = '<a href="javascript:void(0)" onclick="setsupplierdetails(&quot;'.$aRow->NAME.'&quot;,&quot;'.trim(preg_replace('/\s\s+/', ' ', $aRow->ADDRESS)).'&quot;,&quot;'.$aRow->CITY.'&quot;,&quot;'.$aRow->REGION.'&quot;,&quot;'.$aRow->COUNTRY.'&quot;,&quot;'.$aRow->POSTAL.'&quot;,&quot;'.$aRow->PHONE.'&quot;,&quot;'.$aRow->EMAIL.'&quot;,&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->TAXID.'&quot;)">'.$aRow->TAXID.'</a>';
                $row[3] = '<a href="javascript:void(0)" onclick="setsupplierdetails(&quot;'.$aRow->NAME.'&quot;,&quot;'.trim(preg_replace('/\s\s+/', ' ', $aRow->ADDRESS)).'&quot;,&quot;'.$aRow->CITY.'&quot;,&quot;'.$aRow->REGION.'&quot;,&quot;'.$aRow->COUNTRY.'&quot;,&quot;'.$aRow->POSTAL.'&quot;,&quot;'.$aRow->PHONE.'&quot;,&quot;'.$aRow->EMAIL.'&quot;,&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->TAXID.'&quot;)">'.$aRow->EMAIL.'</a>';
                $row[4] = '<a href="javascript:void(0)" onclick="setsupplierdetails(&quot;'.$aRow->NAME.'&quot;,&quot;'.trim(preg_replace('/\s\s+/', ' ', $aRow->ADDRESS)).'&quot;,&quot;'.$aRow->CITY.'&quot;,&quot;'.$aRow->REGION.'&quot;,&quot;'.$aRow->COUNTRY.'&quot;,&quot;'.$aRow->POSTAL.'&quot;,&quot;'.$aRow->PHONE.'&quot;,&quot;'.$aRow->EMAIL.'&quot;,&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->TAXID.'&quot;)">'.$aRow->PHONE.'</a>';
                $row[5] = '<a href="javascript:void(0)" onclick="setsupplierdetails(&quot;'.$aRow->NAME.'&quot;,&quot;'.trim(preg_replace('/\s\s+/', ' ', $aRow->ADDRESS)).'&quot;,&quot;'.$aRow->CITY.'&quot;,&quot;'.$aRow->REGION.'&quot;,&quot;'.$aRow->COUNTRY.'&quot;,&quot;'.$aRow->POSTAL.'&quot;,&quot;'.$aRow->PHONE.'&quot;,&quot;'.$aRow->EMAIL.'&quot;,&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->TAXID.'&quot;)">'.$this->formatslist->formatCurrency(round($aRow->CURDEBT,5)).'</a>';
                $output['aaData'][] = $row;
                $j++;
           }
        } else {
            //
        }   
        echo json_encode( $output );
    }
}