<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Payments extends MY_Controller {
    function __construct(){
        parent::__construct();
        if($this->session->user == ""){
            redirect('login');
        }
        $this->load->model('finance/AccountModel');
        $this->load->model('finance/TransactionModel');
        $this->load->model('finance/PaymentHeadModel');
        $this->load->model('inventory/purchaseinvoice_model');
        $this->load->library('Formatslist');
        $this->load->library('session');
        $this->load->model('settings/taxes_model');
        $this->load->model('partner/suppliers_model');
    }
    public function index(){
        $this->session->unset_userdata('PaymentId');
        $this->load->view('common/head');
        $this->load->view('common/header');
        $this->load->view('finance/view_payments');
        $this->load->view('common/footer');
    }

    public function view_payments(){
        $aColumns = array(
            'sl',
            'TRANSACTION_DATE',
            'account',
            'PAYMENTHEAD',
            'AMOUNT',
            'created_by',
            'status',
            'ID');
        // 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 = "";
            }
        }
        /*
         * Filtering
         */
        $sWhere = "";
        if ($_GET['sSearch'] != "") {
            $sWhere = "WHERE (";
            for ($i = 1; $i < 7; $i++) {
                if ($aColumns[$i] == 'account') {
                    $aColumns[$i] = 'account';
                    //$tablename = 'b';
                } else if ($aColumns[$i] == 'PAYMENTHEAD') {
                    $aColumns[$i] = 'PAYMENTHEAD';
                   // $tablename = 'd';
                } else if ($aColumns[$i] == 'AMOUNT') {
                    $aColumns[$i] = 'AMOUNT';
                    //$tablename = 'a';
                } else if ($aColumns[$i] == 'created_by') {
                    $aColumns[$i] = 'created_by';
                    //$tablename = 'c';
                } else if ($aColumns[$i] == 'TRANSACTION_DATE') {
                    $aColumns[$i] = 'TRANSACTION_DATE';
                    //$tablename = 'a';
                } else if ($aColumns[$i] == 'status') {
                    $aColumns[$i] = 'statustext';
                    //$tablename = '';
                }
                $sWhere .= $aColumns[$i] . " LIKE '%" . $_GET['sSearch'] . "%' OR ";
            }
            $sWhere = substr_replace($sWhere, "", -3);
            $sWhere .= ')';
        }
    
        // get data
        $order = str_replace("ORDER BY",
                '',
                $sOrder);
        $limit = ' ' . $sLimit;
        if ($sWhere != '') {
            $where = ' AND ';
            $where .= str_replace("WHERE",
                    '',
                    $sWhere);
        } else {
            $where = '';
        }
        
        if($_GET["filter_begin"]) {
            $where  =   $where." AND a.TRANSACTION_DATE>='".date("Y-m-d",strtotime($_GET["filter_begin"]))."'";
        }
        if($_GET["filter_end"]) {
            $where  =   $where." AND a.TRANSACTION_DATE<='".date("Y-m-d",strtotime($_GET["filter_end"]))."'";
        }
        
        if($sOrder=='')
            $sOrder= ' ORDER BY created DESC';
        
        $sql = "Select a.ID, b.ACCOUNT_NAME as account,b.ID as accountid, a.AMOUNT, c.NAME as created_by, a.CREATED as created,a.STATUS,a.TRANSACTION_DATE,CASE a.status 
            WHEN 0 THEN 'Created' 
            WHEN 1 THEN 'Approved'  
            WHEN 2 THEN 'Rejected'
            WHEN 3 THEN 'On Hold'
            WHEN 4 THEN 'Updated'
            ELSE 'Created' 
            END as statustext,".
            " CASE WHEN a.TRANSACTION_TYPE_ID=0 THEN 'Deposit' ELSE 'Payment' END as Transactiontype,d.PAYMENTHEAD".
            " from TRANSACTIONS as a".
            " left join ACCOUNTS as b on a.ACCOUNT_ID=b.ID".
            " left join PEOPLE as c on a.CREATED_BY=c.ID".
            " left join PAYMENTHEADS as d on a.PAYMENTHEAD_ID=d.ID";
       $sql.= " WHERE TRANSACTION_TYPE_ID='1' HAVING 1 " . $where . $sOrder . $limit;
       
//       echo $sql;exit;
       
        $arr = $this->common->customquery($sql);
        $totalCount_sql = " Select count(*) AS total".
            " from TRANSACTIONS as a".
            " left join ACCOUNTS as b on a.ACCOUNT_ID=b.ID".
            " left join PEOPLE as c on a.CREATED_BY=c.ID".
            " left join PAYMENTHEADS as d on a.PAYMENTHEAD_ID=d.ID";
        $totalCount_sql .= " WHERE TRANSACTION_TYPE_ID='1' ";
        $totalCount = $this->common->customquery($totalCount_sql);
        $iTotal = $totalCount[0]->total;
        /*
         * Output
         */
        $output = array(
            "sEcho" => intval($_GET['sEcho']),
            "iTotalRecords" => $iTotal,
            "iTotalDisplayRecords" => $iTotal,
            "aaData" => array()
        );
        $j = $_GET['iDisplayStart']+1;
        if ($arr != '') {
            foreach ($arr as $key => $aRow) {
                $row = array();
                $row[0] = $j;
                $row[1] = $this->formatslist->dateFormat($aRow->TRANSACTION_DATE);
                $row[2] = $aRow->account;
                $row[3] = $aRow->PAYMENTHEAD;
                $row[4] = $this->formatslist->formatCurrencywithHash($aRow->AMOUNT);
                $row[5] = $aRow->created_by;
                $row[6] = $aRow->STATUS;
                $row[7] = $aRow->ID;
                $output['aaData'][] = $row;
                $j++;
            }
        } else {
            //
        }
        echo json_encode($output); 
    }
    public function editrecord($id=''){
        $this->session->set_userdata(array('PaymentId'  => $id));
        redirect('finance/payments/add_payment/');
    }
    public function add_payment(){
        $data['alltaxes'] = $this->taxes_model->gettax();
        $id = $this->session->userdata('PaymentId');
        if(!empty($_POST)) {
            if($_POST["paymentheads"]=='PURCHASE' || $_POST["paymentheads"]=='PURCHASERETURN') {
                if($this->input->post('PayId')) {
                    $paymentdetRec  =   $this->TransactionModel->get_transactiondetails($this->input->post('PayId'));
                    $dataTrans["TRANSACTION_DATE"]      =   date("Y-m-d",strtotime($this->input->post('TRANSACTION_DATE')));
                    $dataTrans["TRANSACTION_TYPE_ID"]   =   '1'; // 1 for Payment
                    $dataTrans["ACCOUNT_ID"]            =   $this->input->post('account');
//                    $editdata = $this->purchaseinvoice_model->getpibyid($this->input->post('invoicelist'));
                    $editdata = $this->purchaseinvoice_model->getPurchaseInvoiceDetailsByid($this->input->post('invoicelist'));
                    if($editdata->STATUS==-2)
                        $dataTrans["AMOUNT"]            =   abs($this->input->post('amount'));
                    else if($editdata->STATUS==2)
                        $dataTrans["AMOUNT"]            =   -1*abs($this->input->post('amount'));
                    $dataTrans["COMMENTS"]              =   $this->input->post('comments');
                    if($paymentdetRec[0]->STATUS==5 || $paymentdetRec[0]->STATUS==6 || $paymentdetRec[0]->STATUS==7)
                        $dataTrans["STATUS"]            =   6;
                    else
                        $dataTrans["STATUS"]            =   4;
                    $dataTrans["PAYMENTHEAD_ID"]        =   $_POST["paymentheads"];
                    $dataTrans["CREATED"]               =   date('Y-m-d H:i:s');
                    $dataTrans["CREATED_BY"]            =   $this->session->userid;
                    $dataTrans["APPROVED_BY"]           =   $this->session->userid;
                    $id                                 =   $this->input->post('PayId');
//                    $dataTrans["STATUS"]                =   4;
                    if($this->TransactionModel->update_transaction($dataTrans,$id)){
                        if($dataTrans["PAYMENTHEAD_ID"]=='PURCHASE' || $dataTrans["PAYMENTHEAD_ID"]=='PURCHASERETURN'){
                            $datapurpaymnt["ID"]                    =   uniqid();
                            $datapurpaymnt["PURCHASEINVOICE_ID"]    =   $this->input->post('invoicelist');
                            $datapurpaymnt["TRANSACTION_ID"]        =   $id;
                            if($this->TransactionModel->deletePurchasePayment($id)){
                                $this->TransactionModel->addPurchasePayment($datapurpaymnt);
                            }
                        }
                    }
                } else {
                    if(isset($_POST["invamount"]) && $_POST["invamount"])
                        $invamountArr       =  $_POST["invamount"];
                    if(isset($_POST["chkinvsettlemnt"]) && $_POST["chkinvsettlemnt"])
                        $invsettlemntArr    =  $_POST["chkinvsettlemnt"];
                    if(isset($_POST["invtype"]) && $_POST["invtype"])
                        $invtypeArr         =  $_POST["invtype"];
                    if(isset($_POST["chkinvcancel"]) && $_POST["chkinvcancel"])
                        $invcancelArr    =  $_POST["chkinvcancel"];

                    if($invtypeArr) {
                        foreach($invtypeArr as $key => $invtype) {
                            if($invamountArr[$key]!=''){
                                $dataTrans["TRANSACTION_DATE"]      =   date("Y-m-d",strtotime($this->input->post('TRANSACTION_DATE')));
                                $dataTrans["TRANSACTION_TYPE_ID"]   =   '1'; // 1 for Payment
                                $dataTrans["ACCOUNT_ID"]    =   $this->input->post('account');
//                                $editdata = $this->purchaseinvoice_model->getpibyid($key);
                                $editdata = $this->purchaseinvoice_model->getPurchaseInvoiceDetailsByid($key);
                                
                                if($invamountArr[$key]==$this->formatslist->formatCurrency($editdata->BALANCE))
                                     $invamountArr[$key]    =   $editdata->BALANCE;

                                if($editdata->STATUS==-2){
                                    $dataTrans["AMOUNT"]    =   abs($invamountArr[$key]);
                                } else if($editdata->STATUS==2) {
                                    $dataTrans["AMOUNT"]    =   -1*abs($invamountArr[$key]);
                                }
                                
                                $dataTrans["COMMENTS"]      =   $_POST["comments"];
                                
                                if(isset($invsettlemntArr) && $invsettlemntArr){
                                    if($invsettlemntArr[$key]==1)
                                        $dataTrans["STATUS"]        =   5;
                                    else
                                        $dataTrans["STATUS"]        =   0;
                                } else {
                                    $dataTrans["STATUS"]        =   0;
                                }
                                // Cancel bill
                                if(isset($invcancelArr) && $invcancelArr){
                                    if($invcancelArr[$key]==1) {
                                        $dataTrans["STATUS"]        =   9;
                                        if($_POST["paymentheads"]=='PURCHASE') {
                                            if($invamountArr[$key]>0)
                                                $dataTrans["AMOUNT"]    =   -1*abs($invamountArr[$key]);
                                            else
                                                $dataTrans["AMOUNT"]    =   abs($invamountArr[$key]);
                                        } else if($_POST["paymentheads"]=='PURCHASERETURN') {
                                            if($invamountArr[$key]>0)
                                                $dataTrans["AMOUNT"]    =   -1*abs($invamountArr[$key]);
                                            else 
                                                $dataTrans["AMOUNT"]    =   abs($invamountArr[$key]);
                                        }
                                    }
                                }
                                $dataTrans["PAYMENTHEAD_ID"]    =   $_POST["paymentheads"];
                                $dataTrans["CREATED"]       =   date('Y-m-d H:i:s');
                                $dataTrans["CREATED_BY"]    =   $this->session->userid;
                                $dataTrans["APPROVED_BY"]   =   $this->session->userid;
                                $dataTrans["ID"]    = uniqid();
                                
//                                echo "<pre>";
//                                print_r($dataTrans);exit;
                                
                                if($this->TransactionModel->add_transaction($dataTrans)) {
                                    $transId                                =   $dataTrans["ID"];
                                    $datapurpaymnt["ID"]                    =   uniqid();
                                    $datapurpaymnt["PURCHASEINVOICE_ID"]    =   $key;
                                    $datapurpaymnt["TRANSACTION_ID"]        =   $transId;
                                    $this->TransactionModel->addPurchasePayment($datapurpaymnt);
                                }
                            }
                        }
                    }
                }
                redirect('finance/payments');
            } else {
                $amount =   -1*abs($this->input->post('finalamount'));
                $dataTrans["TRANSACTION_DATE"]      =   date("Y-m-d",strtotime($this->input->post('TRANSACTION_DATE')));
                $dataTrans["TRANSACTION_TYPE_ID"]    =   '1'; // 1 for Payment
                $dataTrans["ACCOUNT_ID"]    =   $this->input->post('account');
                if($this->input->post('paymentheads')){
                    $dataTrans["PAYMENTHEAD_ID"]    =   $this->input->post('paymentheads');
                }
                $dataTrans["AMOUNT"]        =   $amount;
                $dataTrans["COMMENTS"]      =   $this->input->post('comments');
                $dataTrans["STATUS"]        =   0;
                $dataTrans["CREATED"]       =   date('Y-m-d H:i:s');
                $dataTrans["CREATED_BY"]    =   $this->session->userid;
                $dataTrans["APPROVED_BY"]   =   $this->session->userid;
                if($this->input->post('PayId')){
                    $id    =   $this->input->post('PayId');
                    $dataTrans["STATUS"]        =   4;
                    if($this->TransactionModel->update_transaction($dataTrans,$id)){
                        redirect('finance/payments');
                    }else{
                        return false;
                    }
                }else{
                    $dataTrans["ID"]    = uniqid();
                    if($this->TransactionModel->add_transaction($dataTrans)){
                        redirect('finance/payments');
                    }else{
                        return false;
                    }
                }
            }
        }else{
            if($id){
                $data['paymentdetails'] = $this->TransactionModel->get_transactiondetails($id);
                $data['paymentdetails'] = $data['paymentdetails'][0];
                $data['purchasepaymentdet'] = $this->TransactionModel->getPurchasePayment($id);
                if(isset($data['purchasepaymentdet'][0]->PURCHASEINVOICE_ID))
                    $data["purchaseinvdet"] = $this->purchaseinvoice_model->getPurchaseInvoiceDetailsByid($data['purchasepaymentdet'][0]->PURCHASEINVOICE_ID);
                if($data['paymentdetails']->PAYMENTHEAD_ID) {
                    $paymentheaddet = $this->PaymentHeadModel->get_paymenthead($data['paymentdetails']->PAYMENTHEAD_ID);
                    if($paymentheaddet[0]->TAXCAT) {
                        $taxdets    =   $this->taxes_model->getTaxByCatId($paymentheaddet[0]->TAXCAT);
                        $amountwithouttax   =   $data['paymentdetails']->AMOUNT/($taxdets+1);
                        $data['amtwithouttax']  =   $amountwithouttax;
                        $data['taxrateamount']  =   $taxdets*100;
                    } else {
                        $data['amtwithouttax']  =   $data['paymentdetails']->AMOUNT;
                    }
                    
                } else {
                    $data['amtwithouttax']  =   $data['paymentdetails']->AMOUNT;
                }
            }
            $data['accounts']               = $this->AccountModel->dropdown_acounts();
            $data['paymentheads']           = $this->PaymentHeadModel->all_paymentheads();
//            $data['invoicepaymentdetails']  = $this->TransactionModel->purchaseInvoicePaymentList();
            $data['template']               = 'finance/add_payment';
            $this->load->view('template',$data);
        }
    }

    public function get_account(){
        if(!empty($_POST)){
            $id = $this->input->post('account');
            $account = $this->AccountModel->get_account($id);
            $data['available_balance'] = $account[0]->available_balance;
            header('Content-Type: application/json');
            echo json_encode( $data );
        }
    }
    
    public function delete_transaction($id=''){
        if(!empty($id)){
            $getTransRec    =   $this->TransactionModel->get_transactiondetails($id);
            if($getTransRec[0]->PAYMENTHEAD_ID=='PURCHASE' || $getTransRec[0]->PAYMENTHEAD_ID=='PURCHASERETURN'){
                $this->TransactionModel->deletePurchasePayment($id);
            }
            $where  =   array('ID'=>$id);
            if($this->common->delete('TRANSACTIONS',$where)){
                $this->session->set_flashdata('success_msg', 'The record has been deleted successfuly.');
                redirect('finance/payments');
            }else{
                $this->session->set_flashdata('success_msg', 'Cannot Delete');
                redirect('finance/payments');
            }
        }
    }
    
    function viewPurchaseInvoicePayment(){
        $supplierId = $this->input->post('supplierId');
        $flpurchase = $this->input->post('flpurchase');
        $invoicepaymentdetails    = $this->purchaseinvoice_model->getapprovedinvoicebalance('NOTPAID',$supplierId,$flpurchase);
        $dataret    =   '<div class="table-toolbar col-xs-12 col-md-12">
            <input class="form-control" id="myInput" type="text" placeholder="Search...">
            </div>
            <div id="tablecontent" class="table-scrollable">
            <table class="table table-striped table-hover table-bordered editable">
		<thead>
                    <tr role="row">
                        <th width="80">'.$this->lang->line("INVOICENO").'
                        </th>
                        <th width="80">'.$this->lang->line("INVOICEDATE").'
                        </th>
                        <th width="80">'.$this->lang->line("SUPPLIER").'
                        </th>
                        <th class="text-align-right" width="100">'.$this->lang->line("TOTAL").'
                        </th>
                        <th class="text-align-right" width="100">'.$this->lang->line("PAID").'
                        </th>
                        <th class="text-align-right" width="100">'.$this->lang->line("BALANCE").'
                        </th>
                        <th class="text-align-right" width="50">'.$this->lang->line("STATUS").'
                        </th>
                        <th class="text-align-right" width="50">'.$this->lang->line("TRANSFER").'
                        </th>
                        <th class="text-align-right" width="60">'.$this->lang->line("AMOUNTTOPAY").'
                        </th>
                        <th class="text-align-right" width="10">'.$this->lang->line("SETTLE").'
                        </th>
                    </tr>
		</thead>
            <tbody id="myTable">';
            if ($invoicepaymentdetails) {
                foreach ($invoicepaymentdetails as $invpaymntdet) {
                    $dataret=$dataret.'<tr><td>'.$invpaymntdet->REFERENCE.'</td><td>'.$this->formatslist->dateFormat($invpaymntdet->DELIVERYDATE).'</td>   <td>'.$invpaymntdet->name.'</td>   <td>'.$this->formatslist->formatCurrencywithHash($invpaymntdet->TOTALAMOUNT).'</td><td>'.$this->formatslist->formatCurrencywithHash($invpaymntdet->PAIDAMOUNT).'</td><td>'.$this->formatslist->formatCurrencywithHash($invpaymntdet->BALANCE).'</td><td>';
                    if ($invpaymntdet->STATUS == '2') 
                        $dataret=$dataret.'<div class="buttons-preview"><span class="label label-success shiny">Purchase</a></div>';
                    else if ($invpaymntdet->STATUS == '-2') 
                        $dataret=$dataret.'<div class="buttons-preview"><span class="label label-maroon shiny">Purchase Return</a></div>';
                    if ($invpaymntdet->STATUS == '-2') $dtid = 'data-id="txtprreturn"'; else $dtid = '';
                    
                    $balanceamt =   $this->formatslist->formatCurrency($invpaymntdet->BALANCE);
                    $paymnId    =   $invpaymntdet->ID;
                    
                    $dataret=$dataret."</td><td><a href=\"#\" onclick=\"amounttransfer('$paymnId', '$balanceamt')\" ".$dtid." style='width:120px;padding-left:1px;padding-right:1px;text-align:right;'><i class='fa fa-arrow-circle-right' style='font-size: 32px;'></i></a></td><td><input type='text' name=invamount[".$invpaymntdet->ID."] id='invamount_".$invpaymntdet->ID."' ".$dtid." class='invamount'  />";
                    $dataret=$dataret."<input type='hidden' name=invtype[$invpaymntdet->ID] value=".$invpaymntdet->STATUS." />";
                    $dataret=$dataret."</td><td><div class='checkbox'><label><input type='checkbox' name=chkinvsettlemnt[$invpaymntdet->ID] class='inverted' value='1' /><span class='text'></span></label></div></td>";
//                    $dataret=$dataret."<td>
//                    <div class='checkbox'><label>
//                    <input type='checkbox' name=chkinvcancel[$invpaymntdet->ID] class='inverted' value='1' />
//                    <span class='text'></span></label></div>
//                        </td>";
                    $dataret=$dataret."</tr>";
                }
            }
            
            $dataret=$dataret."</tbody>
            </table>
        </div>
        <div class='form-group' style='padding-top: 8px;font-size: 18px;text-align: right;'>
            <div class='col-sm-11' style='padding-top: 8px;font-size: 18px;'>Total Amount : <strong><span id='totalspan'>0.00</span></strong></div><div class='col-sm-1' style='padding-left: 0px;'>
                <button class='btn btn-success shiny' onclick='finishassignprocess()'>
                        <span class='fa fa-check'></span> Done
                </button>
            </div>
        </div>";
        echo $dataret;
    }
    
    function suppliersautocomplete() {
        $supplierslist  =   $this->suppliers_model->getsupplierrsautocomplete($_REQUEST["term"]);
        echo json_encode($supplierslist);
    }
    
    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="selectsupplier(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->NAME.'&quot;)">'.$aRow->NAME.'</a>';
                $row[1] = '<a href="javascript:void(0)" onclick="selectsupplier(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->NAME.'&quot;)">'.$aRow->SEARCHKEY.'</a>';
                $row[2] = '<a href="javascript:void(0)" onclick="selectsupplier(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->NAME.'&quot;)">'.$aRow->TAXID.'</a>';
                $row[3] = '<a href="javascript:void(0)" onclick="selectsupplier(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->NAME.'&quot;)">'.$aRow->EMAIL.'</a>';
                $row[4] = '<a href="javascript:void(0)" onclick="selectsupplier(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->NAME.'&quot;)">'.$aRow->PHONE.'</a>';
                $row[5] = '<a href="javascript:void(0)" onclick="selectsupplier(&quot;'.$aRow->ID.'&quot;,&quot;'.$aRow->NAME.'&quot;)">'.$this->formatslist->formatCurrency(round($aRow->CURDEBT,5)).'</a>';
                $output['aaData'][] = $row;
                $j++;
           }
        } else {
            //
        }   
        echo json_encode( $output );
    }
    
}
