<?php 
    if (!defined('BASEPATH')) exit('No direct script access allowed');

    class Payments extends MY_Controller {
        function __construct() {
            parent::__construct();
            $this->load->library('Formatslist');
            $this->load->model('payment/payment_model');
               $this->load->library('form_validation');
            $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        }

        private function _gethostsequence($id = NULL) {
            $this->load->model('payment/payment_model');
            $catarr = $this->payment_model->gethostsequence();
            $data = '';
            for ($i = 0; $i < count($catarr); $i++) {
                if ($id != NULL && $id == $catarr[$i]->HOSTSEQUENCE)
                    $data .= "<option id=\"option_custom\" selected=\"yes\" value=\"" . $catarr[$i]->HOSTSEQUENCE . "\">" . $catarr[$i]->HOSTSEQUENCE . "</option>\n";
                else
                    $data .= "<option id=\"option_custom\" value=\"" . $catarr[$i]->HOSTSEQUENCE . "\">" . $catarr[$i]->HOSTSEQUENCE . "</option>\n";
            }
            return $data;
        }
        public function index() {
            $data['hostsequence'] = $this->_gethostsequence();
            $data['template'] = 'payment/payments_view';
            $this->load->view('template',$data);
        }

        public function getpayments() {
   //        $data['data'] = $this->payment_model->getpayments();
   //        echo json_encode($data);
            $aColumns = array(
                   'sl',
                   'DATENEW',
                   'NAME',
                   'HOST',
                   'HOSTSEQUENCE',
                   'PAYMENT',
                   'NOTES',
                   'TOTAL');
               // 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 < 8; $i++) {
                       if ($aColumns[$i] == 'DATENEW') {
                           $aColumns[$i] = 'DATENEW';
   //                        $tablename = 'b';
                       } else if ($aColumns[$i] == 'NAME') {
                           $aColumns[$i] = 'NAME';
                       } else if ($aColumns[$i] == 'HOST') {
                           $aColumns[$i] = 'HOST';
                          // $tablename = 'd';
                       } else if ($aColumns[$i] == 'HOSTSEQUENCE') {
                           $aColumns[$i] = 'HOSTSEQUENCE';
                           //$tablename = 'a';
                       } else if ($aColumns[$i] == 'PAYMENT') {
                           $aColumns[$i] = 'PAYMENT';
                           //$tablename = 'c';
                       } else if ($aColumns[$i] == 'NOTES') {
                           $aColumns[$i] = 'NOTES';
                           //$tablename = 'a';
                       } else if ($aColumns[$i] == 'TOTAL') {
                           $aColumns[$i] = 'TOTAL';
                           //$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['fromdate']) {
                $where = $where." AND RECEIPTS.DATENEW>='".date("Y-m-d H:i:s",strtotime($_GET['fromdate']." 00:00"))."'";
            }
            if($_GET['todate']) {
                $where = $where." AND RECEIPTS.DATENEW<='".date("Y-m-d H:i:s",strtotime($_GET['todate']." 23:59:59"))."'";
            }

            $sql = "SELECT `PAYMENTS`.`ID`, `RECEIPTS`.`DATENEW`, `CLOSEDCASH`.`HOST`,"
                    . " `CLOSEDCASH`.`HOSTSEQUENCE`, `PAYMENTS`.`PAYMENT`, `PAYMENTS`.`NOTES`, `PAYMENTS`.`TOTAL`,ACCOUNTHEADS.NAME"
                    . " FROM `PAYMENTS` LEFT JOIN `RECEIPTS` ON `PAYMENTS`.`RECEIPT` = `RECEIPTS`.`ID`"
                    . " LEFT JOIN ACCOUNTHEADS ON ACCOUNTHEADS.ID=RECEIPTS.ACCOUNTHEAD"
                    . " LEFT JOIN `CLOSEDCASH` ON `RECEIPTS`.`MONEY` = `CLOSEDCASH`.`MONEY`";
            $sql.= " WHERE 1 " . $where . $sOrder . $limit;

            $arr = $this->common->customquery($sql);
            $totalCount_sql = " Select count(*) AS total".
                " FROM `PAYMENTS` LEFT JOIN `RECEIPTS` ON `PAYMENTS`.`RECEIPT` = `RECEIPTS`.`ID` LEFT JOIN `CLOSEDCASH` ON `RECEIPTS`.`MONEY` = `CLOSEDCASH`.`MONEY`";
            $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->datetimeFormat($aRow->DATENEW);
                    $row[2] = $aRow->NAME;
                    $row[3] = $aRow->HOST;
                    $row[4] = $aRow->HOSTSEQUENCE;
                    $row[5] = $aRow->PAYMENT;
                    $row[6] = $aRow->NOTES;
                    $row[7] = $this->formatslist->formatCurrencywithHash($aRow->TOTAL);
                    $row[8] = $aRow->ID;
                    $output['aaData'][] = $row;
                    $j++;
                }
            } else {
                //
            }
            echo json_encode($output);
        }

        public function getpaymenthostname() {
    //        $sql = "SELECT `PAYMENTS`.`ID`, `RECEIPTS`.`DATENEW`, `CLOSEDCASH`.`HOST`, `CLOSEDCASH`.`HOSTSEQUENCE`, `PAYMENTS`.`PAYMENT`, `PAYMENTS`.`NOTES`, `PAYMENTS`.`TOTAL` FROM `PAYMENTS` LEFT JOIN `RECEIPTS` ON `PAYMENTS`.`RECEIPT` = `RECEIPTS`.`ID` LEFT JOIN `CLOSEDCASH` ON `RECEIPTS`.`MONEY` = `CLOSEDCASH`.`MONEY` order by `CLOSEDCASH`.`HOST`";
    //        $data['data'] = $this->common->customquery($sql);
    //        echo json_encode($data);
            $aColumns = array(
                'sl',
                'DATENEW',
                'NAME',
                'HOST',
                'HOSTSEQUENCE',
                'PAYMENT',
                'NOTES',
                'TOTAL');
            // 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 = 1; $i < 8; $i++) {
                    if ($aColumns[$i] == 'DATENEW') {
                        $aColumns[$i] = 'DATENEW';
//                        $tablename = 'b';
                    } else if ($aColumns[$i] == 'NAME') {
                        $aColumns[$i] = 'NAME';
                    } else if ($aColumns[$i] == 'HOST') {
                        $aColumns[$i] = 'HOST';
                       // $tablename = 'd';
                    } else if ($aColumns[$i] == 'HOSTSEQUENCE') {
                        $aColumns[$i] = 'HOSTSEQUENCE';
                        //$tablename = 'a';
                    } else if ($aColumns[$i] == 'PAYMENT') {
                        $aColumns[$i] = 'PAYMENT';
                        //$tablename = 'c';
                    } else if ($aColumns[$i] == 'NOTES') {
                        $aColumns[$i] = 'NOTES';
                        //$tablename = 'a';
                    } else if ($aColumns[$i] == 'TOTAL') {
                        $aColumns[$i] = 'TOTAL';
                        //$tablename = '';
                    }
                    $sWhere .= $aColumns[$i] . " LIKE '%" . $_GET['sSearch'] . "%' OR ";
                }
                $sWhere = substr_replace($sWhere, "", -3);
                $sWhere .= ')';
            }
            if($sOrder){
                // get data
//                $order = str_replace("ORDER BY", '', $sOrder);
                $order = $sOrder;
            }else{
                $order = ' order by `CLOSEDCASH`.`HOST`';
            }
            $limit = ' ' . $sLimit;
            if ($sWhere != '') {
                $where = ' AND ';
                $where .= str_replace("WHERE",
                        '',
                        $sWhere);
            } else {
                $where = '';
            }
            if($_GET['fromdate']) {
                $where = $where." AND RECEIPTS.DATENEW>='".date("Y-m-d",strtotime($_GET['fromdate']))."'";
            }
            if($_GET['todate']) {
                $where = $where." AND RECEIPTS.DATENEW<='".date("Y-m-d",strtotime($_GET['todate']))."'";
            }
            $sql = "SELECT `PAYMENTS`.`ID`, `RECEIPTS`.`DATENEW`, `CLOSEDCASH`.`HOST`, `CLOSEDCASH`.`HOSTSEQUENCE`, `PAYMENTS`.`PAYMENT`,"
                    . " `PAYMENTS`.`NOTES`, `PAYMENTS`.`TOTAL`,ACCOUNTHEADS.NAME FROM `PAYMENTS`"
                    . " LEFT JOIN `RECEIPTS` ON `PAYMENTS`.`RECEIPT` = `RECEIPTS`.`ID`"
                    . " LEFT JOIN ACCOUNTHEADS ON ACCOUNTHEADS.ID=RECEIPTS.ACCOUNTHEAD"
                    . " LEFT JOIN `CLOSEDCASH` ON `RECEIPTS`.`MONEY` = `CLOSEDCASH`.`MONEY`";
            $sql.= " WHERE 1 " . $where . $order . $limit;

//            echo $sql;exit;

            $arr = $this->common->customquery($sql);
            $totalCount_sql = " Select count(*) AS total".
                " FROM `PAYMENTS` LEFT JOIN `RECEIPTS` ON `PAYMENTS`.`RECEIPT` = `RECEIPTS`.`ID`"
                    . " LEFT JOIN `CLOSEDCASH` ON `RECEIPTS`.`MONEY` = `CLOSEDCASH`.`MONEY`";
            $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] = $key + 1;
                    $row[1] = $this->formatslist->datetimeFormat($aRow->DATENEW);
                    $row[2] = $aRow->NAME;
                    $row[3] = $aRow->HOST;
                    $row[4] = $aRow->HOSTSEQUENCE;
                    $row[5] = $aRow->PAYMENT;
                    $row[6] = $aRow->NOTES;
                    $row[7] = $this->formatslist->formatCurrencywithHash($aRow->TOTAL);
                    $row[8] = $aRow->ID;
                    $output['aaData'][] = $row;
                    $j++;
                }
            } else {
                //
            }
            echo json_encode($output);
        }

        public function getpaymenttypes() {
             $aColumns = array(
                    'sl',
                    'DATENEW',
                    'NAME',
                    'HOST',
                    'HOSTSEQUENCE',
                    'PAYMENT',
                    'NOTES',
                    'TOTAL');
                // 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 = 1; $i < 8; $i++) {
                        if ($aColumns[$i] == 'DATENEW') {
                            $aColumns[$i] = 'DATENEW';
    //                        $tablename = 'b';
                        } else if ($aColumns[$i] == 'NAME') {
                            $aColumns[$i] = 'NAME';
                        } else if ($aColumns[$i] == 'HOST') {
                            $aColumns[$i] = 'HOST';
                           // $tablename = 'd';
                        } else if ($aColumns[$i] == 'HOSTSEQUENCE') {
                            $aColumns[$i] = 'HOSTSEQUENCE';
                            //$tablename = 'a';
                        } else if ($aColumns[$i] == 'PAYMENT') {
                            $aColumns[$i] = 'PAYMENT';
                            //$tablename = 'c';
                        } else if ($aColumns[$i] == 'NOTES') {
                            $aColumns[$i] = 'NOTES';
                            //$tablename = 'a';
                        } else if ($aColumns[$i] == 'TOTAL') {
                            $aColumns[$i] = 'TOTAL';
                            //$tablename = '';
                        }
                        $sWhere .= $aColumns[$i] . " LIKE '%" . $_GET['sSearch'] . "%' OR ";
                    }
                    $sWhere = substr_replace($sWhere, "", -3);
                    $sWhere .= ')';
                }
                if($sOrder){
                    // get data
                    $order = str_replace("ORDER BY",
                        '',
                        $sOrder);
                }else{
                    $order = ' order by `PAYMENTS`.`PAYMENT`';
                }
                $limit = ' ' . $sLimit;
                if ($sWhere != '') {
                    $where = ' AND ';
                    $where .= str_replace("WHERE",
                            '',
                            $sWhere);
                } else {
                    $where = '';
                }
                if($_GET['fromdate']) {
                    $where = $where." AND RECEIPTS.DATENEW>='".date("Y-m-d",strtotime($_GET['fromdate']))."'";
                }
                if($_GET['todate']) {
                    $where = $where." AND RECEIPTS.DATENEW<='".date("Y-m-d",strtotime($_GET['todate']))."'";
                }
                $sql = "SELECT `PAYMENTS`.`ID`, `RECEIPTS`.`DATENEW`, `CLOSEDCASH`.`HOST`, `CLOSEDCASH`.`HOSTSEQUENCE`,ACCOUNTHEADS.NAME,"
                        . " `PAYMENTS`.`PAYMENT`, `PAYMENTS`.`NOTES`, `PAYMENTS`.`TOTAL` FROM `PAYMENTS`"
                        . " LEFT JOIN `RECEIPTS` ON `PAYMENTS`.`RECEIPT` = `RECEIPTS`.`ID`"
                        . " LEFT JOIN ACCOUNTHEADS ON ACCOUNTHEADS.ID=RECEIPTS.ACCOUNTHEAD"
                        . " LEFT JOIN `CLOSEDCASH` ON `RECEIPTS`.`MONEY` = `CLOSEDCASH`.`MONEY`";
               $sql.= " WHERE 1 " . $where . $sOrder . $limit;

                $arr = $this->common->customquery($sql);
                $totalCount_sql = " Select count(*) AS total".
                    " FROM `PAYMENTS` LEFT JOIN `RECEIPTS` ON `PAYMENTS`.`RECEIPT` = `RECEIPTS`.`ID` LEFT JOIN `CLOSEDCASH` ON `RECEIPTS`.`MONEY` = `CLOSEDCASH`.`MONEY`";
                $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] = $key + 1;
                        $row[1] = $this->formatslist->datetimeFormat($aRow->DATENEW);
                        $row[2] = $aRow->NAME;
                        $row[3] = $aRow->HOST;
                        $row[4] = $aRow->HOSTSEQUENCE;
                        $row[5] = $aRow->PAYMENT;
                        $row[6] = $aRow->NOTES;
                        $row[7] = $this->formatslist->formatCurrencywithHash($aRow->TOTAL);
                        $row[8] = $aRow->ID;
                        $output['aaData'][] = $row;
                        $j++;
                    }
                } else {
                    //
                }
                echo json_encode($output);
        }

        public function getpaymentaccount() {
             $aColumns = array(
                'sl',
                'DATENEW',
                'NAME',
                'HOST',
                'HOSTSEQUENCE',
                'PAYMENT',
                'NOTES',
                'TOTAL');
            // 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 = 1; $i < 8; $i++) {
                    if ($aColumns[$i] == 'DATENEW') {
                        $aColumns[$i] = 'DATENEW';
//                        $tablename = 'b';
                    } else if ($aColumns[$i] == 'NAME') {
                        $aColumns[$i] = 'NAME';
                    } else if ($aColumns[$i] == 'HOST') {
                        $aColumns[$i] = 'HOST';
                       // $tablename = 'd';
                    } else if ($aColumns[$i] == 'HOSTSEQUENCE') {
                        $aColumns[$i] = 'HOSTSEQUENCE';
                        //$tablename = 'a';
                    } else if ($aColumns[$i] == 'PAYMENT') {
                        $aColumns[$i] = 'PAYMENT';
                        //$tablename = 'c';
                    } else if ($aColumns[$i] == 'NOTES') {
                        $aColumns[$i] = 'NOTES';
                        //$tablename = 'a';
                    } else if ($aColumns[$i] == 'TOTAL') {
                        $aColumns[$i] = 'TOTAL';
                        //$tablename = '';
                    }
                    $sWhere .= $aColumns[$i] . " LIKE '%" . $_GET['sSearch'] . "%' OR ";
                }
                $sWhere = substr_replace($sWhere, "", -3);
                $sWhere .= ')';
            }
            if($sOrder){
                // get data
                $order = str_replace("ORDER BY",
                    '',
                    $sOrder);
            }else{
                $order = ' order by ACCOUNTHEADS.NAME';
            }
            $limit = ' ' . $sLimit;
            if ($sWhere != '') {
                $where = ' AND ';
                $where .= str_replace("WHERE",
                        '',
                        $sWhere);
            } else {
                $where = '';
            }
            if($_GET['fromdate']) {
                $where = $where." AND RECEIPTS.DATENEW>='".date("Y-m-d",strtotime($_GET['fromdate']))."'";
            }
            if($_GET['todate']) {
                $where = $where." AND RECEIPTS.DATENEW<='".date("Y-m-d",strtotime($_GET['todate']))."'";
            }
            $sql = "SELECT `PAYMENTS`.`ID`, `RECEIPTS`.`DATENEW`, `CLOSEDCASH`.`HOST`, `CLOSEDCASH`.`HOSTSEQUENCE`,ACCOUNTHEADS.NAME,"
                    . " `PAYMENTS`.`PAYMENT`, `PAYMENTS`.`NOTES`, `PAYMENTS`.`TOTAL` FROM `PAYMENTS`"
                    . " LEFT JOIN `RECEIPTS` ON `PAYMENTS`.`RECEIPT` = `RECEIPTS`.`ID`"
                    . " LEFT JOIN ACCOUNTHEADS ON ACCOUNTHEADS.ID=RECEIPTS.ACCOUNTHEAD"
                    . " LEFT JOIN `CLOSEDCASH` ON `RECEIPTS`.`MONEY` = `CLOSEDCASH`.`MONEY`";
           $sql.= " WHERE 1 " . $where . $sOrder . $limit;

            $arr = $this->common->customquery($sql);
            $totalCount_sql = " Select count(*) AS total".
                " FROM `PAYMENTS` LEFT JOIN `RECEIPTS` ON `PAYMENTS`.`RECEIPT` = `RECEIPTS`.`ID` LEFT JOIN `CLOSEDCASH` ON `RECEIPTS`.`MONEY` = `CLOSEDCASH`.`MONEY`";
            $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] = $key + 1;
                    $row[1] = $this->formatslist->datetimeFormat($aRow->DATENEW);
                    $row[2] = $aRow->NAME;
                    $row[3] = $aRow->HOST;
                    $row[4] = $aRow->HOSTSEQUENCE;
                    $row[5] = $aRow->PAYMENT;
                    $row[6] = $aRow->NOTES;
                    $row[7] = $this->formatslist->formatCurrencywithHash($aRow->TOTAL);
                    $row[8] = $aRow->ID;
                    $output['aaData'][] = $row;
                    $j++;
                }
            } else {
                //
            }
            echo json_encode($output);
        }




        //MATERIALREQUESTLINES FOR CHANGE LINE STATUS
        public function newcashin() {
            $data['template'] = 'payment/cashin_view';
            $this->load->view('template',$data);      
        }
        public function newcashout() {
            $data['template'] = 'payment/cashout_view';
            $this->load->view('template',$data);   
        }
        public function customerpayment() {
            $data['customers'] = $this->common->getAll("CUSTOMERS");
            $data['template'] = 'payment/customerpayment_view';
            $this->load->view('template',$data);   
        }
        public function supplierpayment() {
             $data['supplier'] = $this->common->getAll("SUPPLIERS");
            $data['template'] = 'payment/supplierpayment_view';
            $this->load->view('template',$data);   
        }
        public function getcustpaymentdetails(){
            $cname = $this->input->post('customers');
            $result_array= $this->payment_model->getcustpaymentdetails($cname);
           // print_r($result);
            foreach($result_array as $result) { 
            $data = '{"customerid": "' . $result->TAXID . '", "name": "' . $result->NAME . '", "card": "' . $result->CARD . '", "maxdebt": "' . $result->MAXDEBT . '", "debtcurrent": "' . $result->CURDEBT . '", "debtdate": "' . $result->CURDATE . '"}';
        }
            echo $data;
        }
        public function getsupplierpaymentdetails(){
            $sname = $this->input->post('suppliers');
            $result_array= $this->payment_model->getsupplierpaymentdetails($sname);
            foreach($result_array as $result) { 
            $data = '{"supplierid": "' . $result->TAXID . '", "name": "' . $result->NAME . '", "card": "' . $result->CARD . '", "maxcredit": "' . $result->MAXDEBT . '", "creditcurrent": "' . $result->CURDEBT . '", "creditdate": "' . $result->CURDATE . '"}';
        }
            echo $data;
        }

           public function cashin() {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('cashin', 'Cash In', 'trim|required|numeric');
            $money = $this->payment_model->gethostseqid();
            $date = date('Y-m-d h:i:s');
                if ($this->form_validation->run() == TRUE) {
                        $add = array(
                         'ID' => uniqid(), 
                         'MONEY' => $money[0]->MONEY,
                         'DATENEW' => $date
                        );
                    $this->common->insert('RECEIPTS',$add);
                     $insertdata = $this->common->getinsertdata('RECEIPTS',$add);

                foreach($insertdata as $insert_data)
                {
                  $rc_record = $insert_data->ID;
                }
                      $add_py = array(
                         'ID' => uniqid(), 
                        'RECEIPT' => $rc_record,
                        'PAYMENT' => "cashin",
                        'TOTAL' =>  $this->input->post('cashin'),
                        'NOTES' => $this->input->post('notes')
                   );
                    $this->common->insert('PAYMENTS',$add_py);
                     $this->session->set_flashdata('success_msg', 'Record inserted successfully.');
                    redirect(base_url() . 'payment/payments');
                } else {
                    $data['template'] = 'payment/cashin_view';
                   $this->load->view('template',$data);
                }

        }

        public function cashout() {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('cashout', 'Cash Out', 'trim|required|numeric');
            $money = $this->payment_model->gethostseqid();
            $date = date('Y-m-d h:i:s');

                if ($this->form_validation->run() == TRUE) {
                        $add = array(
                           'ID' => uniqid(), 
                         'MONEY' => $money[0]->MONEY,
                         'DATENEW' => $date
                        );
                   $this->common->insert('RECEIPTS',$add);
                     $insertdata = $this->common->getinsertdata('RECEIPTS',$add);

                foreach($insertdata as $insert_data)
                {
                  $rc_record = $insert_data->ID;
                }
                      $add_py = array(
                         'ID' => uniqid(), 
                        'RECEIPT' => $rc_record,
                        'PAYMENT' => "cashout",
                        'TOTAL' =>  $this->input->post('cashout'),
                        'NOTES' => $this->input->post('notes')
                   );
                    $this->common->insert('PAYMENTS',$add_py);

                   $this->session->set_flashdata('success_msg', 'Record inserted successfully.');
                    redirect(base_url() . 'payment/payments');
                } else {
                      $data['template'] = 'payment/cashout_view';
                     $this->load->view('template',$data);  
                }

        }
        public function customerpay() {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('customers', 'Customer', 'required');
            $this->form_validation->set_rules('cashin', 'Cash In', 'required|numeric');
            $customer = $this->input->post('customers');
            $debcurrentd = $this->payment_model->getcustomers($customer);
            $cashin = $this->input->post('cashin');
            foreach ($debcurrentd as $debcurrent) {
            $newdebt = $debcurrent->CURDEBT - $cashin;
               }
            $money = $this->payment_model->gethostseqid();
            $ticketsnumd = $this->payment_model->getticketsnum();
             foreach ($ticketsnumd as $ticketsnum) {
            $ticketsnum = $ticketsnum->ID + '1';
               }
            $user = $this->getUserID($this->session->userdata('user'));
            $customer = $this->input->post('customers');

            $date = date('Y-m-d h:i:s');
                if ($this->form_validation->run() == TRUE) {

                      $add = array(
                         'ID' => uniqid(), 
                         'MONEY' => $money[0]->MONEY,
                         'DATENEW' => $date
                        );
                    $this->common->insert('RECEIPTS',$add);
                    $insertdata = $this->common->getinsertdata('RECEIPTS',$add);

                foreach($insertdata as $insert_data)
                {
                  $rc_record = $insert_data->ID;
                }
                      $add_py = array(
                        'ID' => uniqid(), 
                        'RECEIPT' => $rc_record,
                        'PAYMENT' => "cash",
                        'TOTAL' =>  $this->input->post('cashin'),
                        'NOTES' => $this->input->post('notes')
                   );
                    $this->common->insert('PAYMENTS',$add_py);


                      $add_deb = array(
                       'ID' => uniqid(), 
                'RECEIPT' => $rc_record,
                'PAYMENT' => 'debtpaid',
                'TOTAL' => $this->input->post('cashin')*-1,
                'NOTES' =>  $this->input->post('notes')
            );

            $this->common->insert('PAYMENTS', $add_deb);

                   $add_tk = array(                
                'ID' => $rc_record,
                'TICKETTYPE' => 2,
                'TICKETID' => $ticketsnum,
                'PERSON' =>  $user,
                'CUSTOMER' => $customer,
                'STATUS' => 0
            );

            $this->common->insert('TICKETS', $add_tk);

                      $this->payment_model->updateticketsnum($ticketsnum);
                      if($newdebt < 0)
                      {
                      $this->payment_model->updatecustomers(0);
                      }
                      else
                      {   echo $newdebt;
                         echo $customer;
                          $this->payment_model->updatecustomers($newdebt,$customer);
                      }
                      if($newdebt <= 0)
                      {
                          $this->payment_model->updatecustomers2($date,$customer);
                      }
                   $this->session->set_flashdata('success_msg', 'Record inserted successfully.');
                    redirect(base_url() . 'payment/payments');
                } else {
                     $data['customers'] = $this->common->getAll("CUSTOMERS");
                     $data['template'] = 'payment/customerpayment_view';
                     $this->load->view('template',$data);   
                }
        }
        public function supplierpay() {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('suppliers', 'Supplier', 'required');
            $this->form_validation->set_rules('cashin', 'Cash In', 'required|numeric');
            $supplier = $this->input->post('suppliers');
            $creditcurrentd = $this->payment_model->getsuppliers($supplier);
            $cashin = $this->input->post('cashin');
            foreach($creditcurrentd as $creditcurrent) {
            $newcredit = $creditcurrent->CURDEBT - $cashin;
             }
            $money = $this->payment_model->gethostseqid();
            $ticketsnumsupplierd = $this->payment_model->getticketsnumsupplier();
            foreach ($ticketsnumsupplierd as $ticketsnumsupplier) {
            $ticketsnumsupplier = $ticketsnumsupplier->ID + '1';
                }
            $user = $this->getUserID($this->session->userdata('user'));
            $supplier = $this->input->post('suppliers');

            $date = date('Y-m-d h:i:s');
                if ($this->form_validation->run() == TRUE) {

                      $add = array(
                         'ID' => uniqid(), 
                         'MONEY' => $money[0]->MONEY,
                         'DATENEW' => $date
                        );
                   $this->common->insert('RECEIPTS',$add);
                    $insertdata = $this->common->getinsertdata('RECEIPTS',$add);

                foreach($insertdata as $insert_data)
                {
                  $rc_record = $insert_data->ID;
                }
                      $add_py = array(
                         'ID' => uniqid(), 
                        'RECEIPT' => $rc_record,
                        'PAYMENT' => "creditpaid",
                        'TOTAL' =>  $this->input->post('cashin')*-1,
                        'NOTES' => $this->input->post('notes')
                   );
                    $this->common->insert('PAYMENTS',$add_py);

                   $add_tk = array(
                'ID' => $rc_record,
                'TICKETTYPE' => 3,
                'TICKETID' => $ticketsnumsupplier,
                'PERSON' =>  $user,
                'SUPPLIER' => $supplier,
                'STATUS' => 0
            );

            $this->common->insert('TICKETS', $add_tk);


                      $this->payment_model->updateticketsnumsupplier($ticketsnumsupplier);
                      if($newcredit < 0)
                      {
                      $this->payment_model->updatesuppliers(0);
                      }
                      else
                      {

                          $this->payment_model->updatesuppliers($newcredit,$supplier);
                      }
                      if($newcredit <= 0)
                      {
                          $this->payment_model->updatesuppliers2($date,$supplier);
                      }
                   $this->session->set_flashdata('success_msg', 'Record inserted successfully.');
                    redirect(base_url() . 'payment/payments');
                } else {
                    //echo "error";die();
                      $data['supplier'] = $this->common->getAll("SUPPLIERS");
                     $data['template'] = 'payment/supplierpayment_view';
                     $this->load->view('template',$data);
                }

        }
        // GET USER NAME BY ID
        private function getUserID($user) {
            $this->load->model('settings/users_model');
            return $this->users_model->getUserID($user);
        }
        // GET SUPPLIER ID BY NAME
        private function _getCUSTOMERIDbN($name) {
            $this->load->model('payment/payment_model');
            return $this->payment_model->getcustomeridbn($name);
        }
            private function _getSUPPLIERIDbN($name) {
            $this->load->model('partner/suppliers_model');
            return $this->suppliers_model->getsupplieridbn($name);
        }
        function exportcsv() {
            $file="payments.csv";
            header("Content-Disposition: attachment; filename=" . urlencode($file));
            header("Content-Type: application/force-download");
            header("Content-Type: application/octet-stream");
            header("Content-Type: application/download");
            header("Content-Description: File Transfer");
            header("Content-type: application/csv");
            header("Pragma: no-cache");
            header("Expires: 0");
            $export= $this->input->post('exportdata');
            $this->load->helper('download');
            force_download($file, $export);
        }
    }