<?php

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

class Customers
        extends MY_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('partner/customers_model');
        $this->load->library('Formatslist');
    }

//GET CUSTOMERS
    public function index() {
        $data['reccustimgcheck'] = $this->customers_model->checkcustimageexisttable();
        $data['reccustmembcheck'] = $this->customers_model->checkcustmembexisttable();
        $data['taxcustcat'] = $this->common->getAll('TAXCUSTCATEGORIES');
        $data['template'] = 'partner/customers_ovw';
        $this->load->view('template',$data);
    }

    
    public function payments() {
        $data['reccustimgcheck'] = $this->customers_model->checkcustimageexisttable();
        $data['reccustmembcheck'] = $this->customers_model->checkcustmembexisttable();
        $data['taxcustcat'] = $this->common->getAll('TAXCUSTCATEGORIES');
        $data['template'] = 'partner/customer_payments_ovw';
        $this->load->view('template',$data);
    }
    public function getcustomers() {
//        $data['data'] = $this->customers_model->getcustomers();
//        echo json_encode($data);
        $reccustmembchk = $this->customers_model->checkcustmembexisttable();
        $aColumns = array(
            'sl',
            'TAXID',
            'SEARCHKEY',
            'NAME',
            'CARD',
            'MAXDEBT',
            'CURDEBT',
            'TAXCATEGORY',
            'ADDRESS',
            '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 < 9; $i++) {
                if ($aColumns[$i] == 'TAXID') {
                    $aColumns[$i] = 'TAXID';
                } else if ($aColumns[$i] == 'SEARCHKEY') {
                    $aColumns[$i] = 'SEARCHKEY';
                } else if ($aColumns[$i] == 'NAME') {
                    $aColumns[$i] = 'CUSTOMERS.NAME';
                } else if ($aColumns[$i] == 'CARD') {
                    $aColumns[$i] = 'CARD';
                } else if ($aColumns[$i] == 'MAXDEBT') {
                    $aColumns[$i] = 'MAXDEBT';
                } else if ($aColumns[$i] == 'CURDEBT') {
                    $aColumns[$i] = 'CURDEBT';
                } else if ($aColumns[$i] == 'TAXCATEGORY') {
                    $aColumns[$i] = 'T.NAME';
                } else if ($aColumns[$i] == 'ADDRESS') {
                    $aColumns[$i] = 'ADDRESS';
                }
                $sWhere .= $aColumns[$i] . " LIKE '%" . $_GET['sSearch'] . "%' OR ";
            }
            $sWhere = substr_replace($sWhere,
                    "",
                    -3);
            $sWhere .= ')';
            if($reccustmembchk==1){
                $nWhere = " OR CUSTOMERS.ID IN (SELECT CUSTOMER_ID FROM CUSTOMER_MEMBERS WHERE SEARCHKEY LIKE '%".$_GET['sSearch']."%' OR MEMBER_NAME LIKE '%".$_GET['sSearch']."%' OR MEMBER_PHONE LIKE '%".$_GET['sSearch']."%' OR MEMBER_ADDRESS LIKE '%".$_GET['sSearch']."%')";
            }
        }
        // get data
        $order = str_replace("ORDER BY",
                '',
                $sOrder);
        $limit = ' ' . $sLimit;
        if ($sWhere != '') {
            $where = ' AND ';
            $where .= str_replace("WHERE", '', $sWhere);
        } else {
            $where = ' ';
            $nWhere='';
        }
        if($reccustmembchk==1){
            $where  =   $where .$nWhere;
        }
        $sql = "SELECT `CUSTOMERS`.`ID`,`CUSTOMERS`.`TAXID`, `CUSTOMERS`.`SEARCHKEY`, `CUSTOMERS`.`NAME`, `CUSTOMERS`.`CARD`, `CUSTOMERS`.`MAXDEBT`, `CUSTOMERS`.`CURDEBT`, `T`.`NAME` AS `TAXCATEGORY`, `CUSTOMERS`.`ADDRESS`, `CUSTOMERS`.`PHONE`, `CUSTOMERS`.`EMAIL`, `CUSTOMERS`.`FAX`, `CUSTOMERS`.`NOTES`, `CUSTOMERS`.`TAXCATEGORY` AS `TAXCATID` FROM `CUSTOMERS` LEFT JOIN `TAXCUSTCATEGORIES` AS `T` ON `T`.`ID` = `CUSTOMERS`.`TAXCATEGORY`";
        $sql .= " WHERE 1 " .$where. $sOrder . $limit;
//           echo $sql;exit;
        $arr = $this->common->customquery($sql);
        $totalCount_sql = " Select count(*) AS total FROM `CUSTOMERS` LEFT JOIN `TAXCUSTCATEGORIES` AS `T` ON `T`.`ID` = `CUSTOMERS`.`TAXCATEGORY`";
//            $totalCount_sql .= " WHERE TRANSACTION_TYPE_ID='0' ";
        $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();
                if($reccustmembchk==1)
                    $row[0] = '<a href="#" class="details-control"><i class="fa fa-plus"></i></a>';
                else
                    $row[0] = $j;
                $row[1] = $aRow->TAXID;
                $row[2] = $aRow->SEARCHKEY;
                $row[3] = $aRow->NAME;
                $row[4] = $aRow->CARD;
                $row[5] = $this->formatslist->formatCurrencywithHash($aRow->MAXDEBT);
                $row[6] = $this->formatslist->formatCurrencywithHash($aRow->CURDEBT);
                $row[7] = $aRow->TAXCATEGORY;
                $row[8] = $aRow->ADDRESS;
                $row[9] = $aRow->ID;
                $output['aaData'][] = $row;
                $j++;
            }
        } else {
            //
        }
        echo json_encode($output);
    }
    
    public function getcustomerPayments() {

        $aColumns = array(
            
            'SEARCHKEY',
            'NAME',
            'INVOICE_ID');
        // set limit
        $sLimit = "";
        if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
            $sLimit = "LIMIT " . $_GET['iDisplayStart'] . ", " . $_GET['iDisplayLength'];
        }
        //Ordering

        /*
         * Filtering
         */
        $sWhere = "";
        if ($_GET['sSearch'] != "") {
            $sWhere = "WHERE (";
            for ($i = 1; $i < 3; $i++) {
                if ($aColumns[$i] == 'SEARCHKEY') {
                    $aColumns[$i] = 'CUSTOMERS.SEARCHKEY';
                } else if ($aColumns[$i] == 'NAME') {
                    $aColumns[$i] = 'CUSTOMERS.NAME';
                } else if ($aColumns[$i] == 'INVOICE') {
                    $aColumns[$i] = 'TICKETS.TICKETID';
                } 
                $sWhere .= $aColumns[$i] . " LIKE '%" . $_GET['sSearch'] . "%' OR ";
            }
            $sWhere = substr_replace($sWhere,
                    "",
                    -3);
            $sWhere .= ')';
            
        }
        // get data
        //$order = str_replace("ORDER BY", '', $sOrder);
        $sOrder = 'ORDER BY CUSTOMERPAYMENTS.PAYMENT_DATE DESC, CUSTOMERPAYMENTS.CREATED_AT DESC';
        $limit = ' ' . $sLimit;
        if ($sWhere != '') {
            $where = ' AND ';
            $where .= str_replace("WHERE", '', $sWhere);
        } else {
            $where = ' ';
            $nWhere='';
        }
       
        $sql = "SELECT CUSTOMERS.ID, CUSTOMERS.SEARCHKEY, CUSTOMERS.NAME, "
                . "CUSTOMERPAYMENTS.* FROM CUSTOMERPAYMENTS  JOIN CUSTOMERS  ON CUSTOMERS.ID = CUSTOMERPAYMENTS.CUSTOMER_ID";
        $sql .= " WHERE 1 " .$where. $sOrder . $limit;

        $arr = $this->common->customquery($sql);
        $totalCount_sql = " Select count(*) AS total FROM CUSTOMERPAYMENTS";
//            $totalCount_sql .= " WHERE TRANSACTION_TYPE_ID='0' ";
        $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] = $aRow->PAYMENT_DATE;
                $row[1] = $aRow->NAME. ' ('.$aRow->SEARCHKEY .')';
                $row[2] = $aRow->INVOICE_ID;
                $row[3] = $this->formatslist->formatCurrencywithHash($aRow->TOTAL);
                $row[4] = $this->formatslist->formatCurrencywithHash($aRow->PAID);
                $row[5] = $this->formatslist->formatCurrencywithHash($aRow->ADJUSTMENTS);
                $row[6] = $this->formatslist->formatCurrencywithHash($aRow->BALANCE);
                $row[7] = $aRow->STATUS;
                $row[8] = $aRow->ID;
                $output['aaData'][] = $row;
                $j++;
            }
        } else {
            //
        }
        echo json_encode($output);
    }
    
    public function getinvdetails()
    {
        $invid = $this->input->post('invid');
        
        $sql = "SELECT RECEIPTS.ID AS RECEIPTID, TICKETS.TICKETID, CUSTOMERS.ID AS CUSTOMERID, "
                . "CONCAT(CUSTOMERS.NAME,' (',CUSTOMERS.SEARCHKEY,')') AS CUSTOMERNAME, "
                . "RECEIPTS.DATENEW, SUM(PAYMENTS.TOTAL) AS INVTOTAL "
                . "from TICKETS JOIN RECEIPTS ON RECEIPTS.ID=TICKETS.ID "
                . " JOIN PAYMENTS ON PAYMENTS.RECEIPT=TICKETS.ID"
                . " JOIN CUSTOMERS ON CUSTOMERS.ID=TICKETS.CUSTOMER "
                . " WHERE TICKETS.TICKETTYPE=0 AND PAYMENTS.PAYMENT='debt' AND TICKETS.TICKETID = ".$invid." ;";
        $arr = $this->common->customquery($sql);
        
        if($arr && $arr[0]->RECEIPTID!=null)
        {
            
            if($arr[0]->CUSTOMERNAME)
            {
                $sql = "SELECT SUM(CUSTOMERPAYMENTS.PAID+CUSTOMERPAYMENTS.ADJUSTMENTS) AS PAID "
                . "from CUSTOMERPAYMENTS WHERE RECEIPT_ID='".$arr[0]->RECEIPTID."';";
        $payments = $this->common->customquery($sql);
            
            $data = [
                'success' => true,
                'receiptid' => $arr[0]->RECEIPTID,
                'invoiceid' => $arr[0]->TICKETID,
                'customerid' => $arr[0]->CUSTOMERID,
                'customer' => $arr[0]->CUSTOMERNAME,
                'total' => $arr[0]->INVTOTAL,
                'date' => $arr[0]->DATENEW,
                
                'message' => "Invoice found"
                    ];
            
            if($payments)
            {
                $data['paid']=$payments[0]->PAID;
            }
            else
            {
                $data['paid']=0;
            }

                echo json_encode($data);
            }
            else
            {
                $data = [
                'success' => false,
                'message' => "Invoice has no customer."
                    ];

                echo json_encode($data);
                
            }
            
        }
        else
        {  
            
            $data = [
                'success' => false,
                'message' => "Credit invoice not found"
                    ];

                echo json_encode($data);
            
          }
    }
    
    public function savepayment()
    {
        $data = array(

            'PAYMENT_DATE' => date('Y-m-d',strtotime($this->input->post('paymentdate'))),
            'CUSTOMER_ID' => $this->input->post('customerid'),
            'RECEIPT_ID' => $this->input->post('receiptid'),
            'INVOICE_ID' => $this->input->post('invoiceid'),
            'TOTAL' => $this->input->post('invtotal'),
            'PAID' => $this->input->post('invpaying'),
            'ADJUSTMENTS' => $this->input->post('invadj'),
            'BALANCE' => $this->input->post('invbalance'),
            'STATUS' => $this->input->post('invsettle'),
            );
        
            //var_dump($data);exit;
        
                $this->common->insert('CUSTOMERPAYMENTS',
                        $data);
                
                $paid=$this->input->post('invpaying')+$this->input->post('invadj');
                
                 $sql = "UPDATE CUSTOMERS SET CURDEBT=CURDEBT-". $paid. ", CURDATE=CURDATE() WHERE ID='".$this->input->post('customerid')."'";
                $dataupdate = $this->db->query($sql);

            $data = [
                'success' => true,
                'message' => "Payment updated successfully."
                    ];

                echo json_encode($data);
            
       
    }

    public function addcustomers() {
        $id = $this->input->post('id');
        if($this->input->post('VISIBLE')==1){
            $visible    =   1;
        }else{
            $visible    =   0;
        }
        $data = array(
            //  'ID' => uniqid(), 
            'TAXID' => $this->input->post('TAXID'),
            'NAME' => $this->input->post('name'),
            'SEARCHKEY' => $this->input->post('searchkey'),
            'CARD' => $this->input->post('card'),
            'MAXDEBT' => ($this->input->post('maxdebt')) ? $this->input->post('maxdebt') : 0,
//            'CURDEBT' => ($this->input->post('curdebt')) ? $this->input->post('curdebt') : 0,
            'TAXCATEGORY' => ($this->input->post('taxcategory')) ? $this->input->post('taxcategory') : NULL,
            'ADDRESS' => ($this->input->post('address')) ? $this->input->post('address') : NULL,
            'PHONE' => ($this->input->post('phone')) ? $this->input->post('phone') : NULL,
            'EMAIL' => ($this->input->post('email')) ? $this->input->post('email') : NULL,
            'FAX' => ($this->input->post('fax')) ? $this->input->post('fax') : NULL,
            'NOTES' => ($this->input->post('notes')) ? $this->input->post('notes') : NULL,
            'VISIBLE'=>$visible
        );
        if ($id == '') {
            $existdata = $this->common->existdata('CUSTOMERS',
                    $data);
            // print_r( $existdata);die();
            if (!empty($existdata)) {
                $this->session->set_flashdata('success_msg',
                        'The record is already exist');
            } else {
                $data["ID"] = uniqid();
                $this->common->insert('CUSTOMERS',
                        $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('CUSTOMERS',
                    $where,
                    $data);
        }
        redirect('partner/customers');
    }

    public function editcustomers($id) {
        $where = array(
            'ID' => $id,);
        $data = $this->common->getWhere('CUSTOMERS',
                $where);

        echo json_encode($data);
    }

    public function deletecustomers($id) {

        $where = array(
            'ID' => $id);
        $this->common->delete('CUSTOMERS',
                $where);
        $this->session->set_flashdata('success_msg',
                'The record has been deleted successfuly.');
        redirect('partner/customers');
    }

    public function order() {
        if ($this->uri->segment(3)) {
            $ord = ($this->uri->segment(4)) ? $this->uri->segment(4) : 'ASC';
            $this->index($this->uri->segment(3),
                    $ord);
        }
    }

    //GET CUSTOMER AUTOCOMPLETE
    function getcustomersautocomplete() {
        $term = $this->input->post('term',
                TRUE);
        $this->load->model('partner/customers_model');
        $rows = $this->customers_model->getcustomersautocomplete($term);
        $keywords = array();
        foreach ($rows as $row) array_push($keywords,
                    $row->NAME);
        echo json_encode($keywords);
    }

    function getsearchkeyautocomplete() {
        $term = $this->input->post('term',
                TRUE);
        $this->load->model('partner/customers_model');
        $rows = $this->customers_model->getsearchkeyautocomplete($term);
        $keywords = array();
        foreach ($rows as $row) array_push($keywords,
                    $row->SEARCHKEY);
        echo json_encode($keywords);
    }

    //GET CARD AUTOCOMPLETE
    function getcustomercardautocomplete() {
        $term = $this->input->post('term',
                TRUE);
        $this->load->model('partner/customers_model');
        $rows = $this->customers_model->getcustomercardautocomplete($term);
        $keywords = array();
        foreach ($rows as $row) array_push($keywords,
                    $row->CARD);
        echo json_encode($keywords);
    }

    //GET CUST CATEGORY AUTOCOMPLETE
    function getcategoriesautocomplete() {
        $term = $this->input->post('term',
                TRUE);
        $this->load->model('partner/customers_model');
        $rows = $this->customers_model->getcategoriesautocomplete($term);
        $keywords = array();
        foreach ($rows as $row) array_push($keywords,
                    $row->TAXCATEGORY);
        echo json_encode($keywords);
    }

    //GET CUSTOMERS


    function _taxCatName($id) {
        $this->load->model('partner/customers_model');
        return $this->customers_model->cCatName($id);
    }

    public function index2($ordby = 'ID',
            $ord = 'ASC') {
        $this->load->library('pagination');
        $this->load->model('partner/customers_model');
        $config['base_url'] = site_url() . 'partner/customers/';
        $config['total_rows'] = $this->customers_model->customersCount();
        $config['per_page'] = ($this->session->userdata('records')) ? $this->session->userdata('records') : 20;
        $config['num_links'] = 10;
        $config['full_tag_open'] = '<div id="pagination">';
        $config['full_tag_close'] = '</div>';
        $config['uri_segment'] = 2;
        $this->pagination->initialize($config);
        $order_by = (in_array($ordby,
                        array(
                    'ID',
                    'NAME',
                    'CARD',
                    'MAXDEBT',
                    'CURDEBT',
                    'POINTS',
                    'TAXCATEGORY',
                    'ADDRESS'))) ? $ordby : 'ID';
        $asc_dsc = (in_array($ord,
                        array(
                    'ASC',
                    'DESC'))) ? $ord : 'ASC';
        $data['per_page'] = $config['per_page'];
        $exp = explode(".",
                $config['total_rows'] / $config['per_page']);
        $data['last_page'] = $exp[0] * $config['per_page'];
        $data['current_page'] = ($this->uri->segment(2) / $config['per_page']);
        $data['next_page'] = ($this->uri->segment(2) < $data['last_page']) ? $this->uri->segment(2) + $config['per_page'] : $data['last_page'];
        $data['previous_page'] = ($this->uri->segment(2) >= $config['per_page']) ? $this->uri->segment(2) - $config['per_page'] : '';
        $data['customers'] = $this->customers_model->getCustomers(
                $config['per_page'],
                $this->uri->segment(2),
                $order_by,
                $asc_dsc
        );
        $this->load->view('settings/header');
        $this->load->view('partner/customers_ovw',
                $data);
        $this->load->view('settings/footer');
    }

    private function _getCustomerCategories($id = NULL) {
        $this->load->model('partner/customers_model');
        $catarr = $this->customers_model->getCustomerCategories();
        $data = '<option value="">Select</option>';
        for ($i = 0; $i < count($catarr); $i++) {
            if ($id != NULL && $id == $catarr[$i]->ID) $data .= "<option selected=\"yes\" value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
            else $data .= "<option value=\"" . $catarr[$i]->ID . "\">" . $catarr[$i]->NAME . "</option>\n";
        }
        return $data;
    }

    //PARTNER CATEGORY
    public function categories() {

        $data['template'] = 'partner/partnercategory_ovw';
        $this->load->view('template',
                $data);
    }

    //GET PARTNER CATEGORIES
    public function getcategories() {
        $data['data'] = $this->common->getAll('TAXCUSTCATEGORIES');
        echo json_encode($data);
    }

    public function addcategories() {
        $id = $this->input->post('id');
        $data = array(
            'ID' => uniqid(),
            'NAME' => $this->input->post('name')
        );
        if ($id == '') {
            $existdata = $this->common->existdata('TAXCUSTCATEGORIES',
                    $data);
            // print_r( $existdata);die();
            if (!empty($existdata)) {

                $this->session->set_flashdata('success_msg',
                        'The record is already exist');
            } else {
                $this->common->insert('TAXCUSTCATEGORIES',
                        $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('TAXCUSTCATEGORIES',
                    $where,
                    $data);
        }
        redirect('partner/customers/categories');
    }

    public function editcategories($id) {
        $where = array(
            'ID' => $id,);
        $data = $this->common->getWhere('TAXCUSTCATEGORIES',
                $where);

        echo json_encode($data);
    }

    public function deletecategories($id) {

        $where = array(
            'ID' => $id);
        $this->common->delete('TAXCUSTCATEGORIES',
                $where);
        $this->session->set_flashdata('success_msg',
                'The record has been deleted successfuly.');
        redirect('partner/customers/categories');
    }

    private function getUserID($user) {
        $this->load->model('settings/users_model');
        return $this->users_model->getUserID($user);
    }

    function exportcsv() {
        $file = "partner/customers.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);
    }

    function getcustomerautocomplete() {
        $term = $this->input->post('term',
                TRUE);
        $this->load->model('partner/customers_model');
        $rows = $this->customers_model->getcustomerautocomplete($term);
        $keywords = array();
        foreach ($rows as $row) array_push($keywords,
                    $row->NAME);
        echo json_encode($keywords);
    }

    private function getcustcat($name) {
        $this->load->model('partner/suppliers_model');
        return $this->suppliers_model->getcustcat($name);
    }

    function partnerrecord() {
        $oper = $this->input->post('oper');
        $id = uniqid();
        $this->load->model('partner/customers_model');
        /*  if($oper=='del')
          {
          $id = $this->input->post('id');
          if($id)
          {
          $this->customers_model->deletepartnercat($id);
          $fdata = array('msgt' => 'S', 'msg' => 'partner category deleted successfully.');
          $this->session->set_flashdata($fdata);
          redirect(site_url() . 'partner/customers/categories');
          }
          else {
          $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete partnercategory.');
          $this->session->set_flashdata($fdata);
          redirect(site_url() . 'partner/customers/categories');
          }
          } */
        $this->load->library('form_validation');
        $this->form_validation->set_rules('NAME',
                'NAME',
                'trim|required');


        if ($this->form_validation->run() == true) {
            $form_data = array(
                'ID' => $id,
                'NAME' => $this->input->post('NAME'),
            );
            var_dump($form_data);
            if ($oper == 'add') {
                if ($this->customers_model->addpartnercat($form_data) == TRUE) {
                    $fdata = array(
                        'msgt' => 'S',
                        'msg' => 'Partnercategory added successfully.');
                    $this->session->set_flashdata($fdata);
                    return true;
                }
            } elseif ($oper == 'edit') {

                $id = $this->input->post('id');
                if ($id) {
                    $this->customers_model->updatepartnercat($id,
                            $form_data);
                }
            }
        }
    }

    function record() {
        $oper = $this->input->post('oper');
        $id = uniqid();
        $this->load->model('partner/customers_model');
        //$taxcategory = $this->getcustcat($this->input->post('TAXCATEGORY'));

        /* if($oper=='del')
          {
          $id = $this->input->post('id');
          if($id)
          {
          $this->customers_model->delete($id);
          $fdata = array('msgt' => 'S', 'msg' => 'Customer deleted successfully.');
          $this->session->set_flashdata($fdata);
          redirect(site_url() . 'partner/customers');
          }
          else {
          $fdata = array('msgt' => 'E', 'msg' => 'Cannot delete Customer.');
          $this->session->set_flashdata($fdata);
          redirect(site_url() . 'partner/customers');
          }
          }
          else { */
        $form_data = array(
            'ID' => $id,
            'SEARCHKEY' => ($this->input->post('SEARCHKEY')) ? $this->input->post('SEARCHKEY') : NULL,
            'NAME' => $this->input->post('NAME'),
            'CARD' => ($this->input->post('CARD')) ? $this->input->post('CARD') : NULL,
            'TAXCATEGORY' => $this->input->post('TAXCATID'),
            'MAXDEBT' => ($this->input->post('MAXDEBT')) ? $this->input->post('MAXDEBT') : 0,
//            'CURDEBT' => ($this->input->post('CURDEBT')) ? $this->input->post('CURDEBT') : NULL,
            'ADDRESS' => ($this->input->post('ADDRESS')) ? $this->input->post('ADDRESS') : NULL,
            'PHONE' => ($this->input->post('PHONE')) ? $this->input->post('PHONE') : NULL,
            'EMAIL' => ($this->input->post('EMAIL')) ? $this->input->post('EMAIL') : NULL,
            'FAX' => ($this->input->post('FAX')) ? $this->input->post('NOTES') : NULL,
            'NOTES' => ($this->input->post('NOTES')) ? $this->input->post('NOTES') : NULL
        );
//        var_dump($form_data);
        if ($oper == 'add') {
            if ($this->customers_model->add($form_data) == TRUE) {
                $fdata = array(
                    'msgt' => 'S',
                    'msg' => 'Customer added successfully.');
                $this->session->set_flashdata($fdata);
                return true;
            }
        } elseif ($oper == 'edit') {
            $id = $this->input->post('id');
            if ($id) {
                $this->customers_model->update($id,
                        $form_data);
            }
        }
    }

    function add($form_data) {
        $this->db->insert('CUSTOMERS',
                $form_data);
        if ($this->db->affected_rows() == '1') {
            return TRUE;
        }
        return FALSE;
    }

    //Partner Categories 
    function getcustcatautocomplete() {
        $term = $this->input->post('term',
                TRUE);
        $this->load->model('partner/customers_model');
        $rows = $this->customers_model->getcustcatautocomplete($term);
        $keywords = array();
        foreach ($rows as $row) array_push($keywords,
                    array(
                'label' => $row->NAME,
                'value' => $row->ID
            ));

        echo json_encode($keywords);
    }

    function deletepartnercat() {
        $this->load->model('partner/customers_model');
        if ($this->uri->segment(4)) {

            if ($this->customers_model->deletepartnercat($this->uri->segment(4)) == true) {
                $fdata = array(
                    'msgt' => 'S',
                    'msg' => 'Partner category deleted successfully.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'partner/customers/categories');
            } else {
                $fdata = array(
                    'msgt' => 'E',
                    'msg' => 'Cannot delete partner category.');
                $this->session->set_flashdata($fdata);

                redirect(site_url() . 'partner/customers/categories');
            }
        }
    }

    function deletecustomer() {
        $this->load->model('partner/customers_model');
        if ($this->uri->segment(4)) {

            if ($this->customers_model->delete($this->uri->segment(4)) == true) {
                $fdata = array(
                    'msgt' => 'S',
                    'msg' => 'customer deleted successfully.');
                $this->session->set_flashdata($fdata);
                redirect(site_url() . 'partner/customers');
            } else {
                $fdata = array(
                    'msgt' => 'E',
                    'msg' => 'Cannot delete  customer.');
                $this->session->set_flashdata($fdata);

                redirect(site_url() . 'partner/customers');
            }
        }
    }

    function savecustormersphoto() {
        $formdata["ID"] = uniqid();
        $formdata["CUSTOMER"] = $_POST["camcustid"];
        $content = explode(",", $_POST["capturedimg"]);
        $formdata["CONTENT"] = base64_decode($content[1]);
        if ($this->customers_model->customerImageSave($formdata) == true) {
            $response = array(
                'MSG' => '1');
            echo json_encode($response);
        } else {
            $response = array(
                'MSG' => "0");
            echo json_encode($response);
        }
    }

    function listcustomerimage($id = '') {
        $reccustimg = $this->customers_model->customerImageList($id);
        if ($reccustimg) {
            $msg = '<div class="col-xs-12 col-md-12"><input type="hidden" name="custId" id="custId" value="' . $id . '" />';
            foreach ($reccustimg as $custimg) {
                $msg .= '<div class="col-xs-12 col-md-4"><a href="#" onclick=deleteImageFunction("' . $custimg->ID . '") class="deletelink"><i class="fa fa-trash"></i></a><img src="data:image/png;base64,' . base64_encode($custimg->CONTENT) . '" style="width: 100%;margin-bottom: 10px;" /></div>';
            }
            $msg .= '</div>';
        } else {
            $msg = '<div class="col-xs-12 col-md-12" style="height:150px;"><input type="hidden" name="custId" id="custId" value="' . $id . '" />No image found</div>';
        }
        echo $msg;
    }

    function Chooosecustomerimage($id = '') {
        $reccustimg = $this->customers_model->customerImageList($id);
        if ($reccustimg) {
            $msg = '<div class="col-xs-12 col-md-12"><input type="hidden" name="custId" id="custId" value="' . $id . '" />';
            foreach ($reccustimg as $custimg) {
                $msg .= '<div class="col-xs-12 col-md-4"><img src="data:image/png;base64,' . base64_encode($custimg->CONTENT) . '" style="width: 100%;margin-bottom: 10px;" id="img_'.$custimg->ID.'" /><a href="#" onclick=chooseImageFunction("' . $custimg->ID . '") class="deletelink btn btn-blue">Choose</a></div>';
            }
            $msg .= '</div>';
        } else {
            $msg = '<div class="col-xs-12 col-md-12" style="height:150px;"><input type="hidden" name="custId" id="custId" value="' . $id . '" />No image found</div>';
        }
        echo $msg;
    }
    
    
    function deletecustomerimage($id = '') {
        if ($this->customers_model->customerimagedelete($id) == true) {
            $response = array(
                'MSG' => '1');
            echo json_encode($response);
        } else {
            $response = array(
                'MSG' => "0");
            echo json_encode($response);
        }
    }

    function latestcustomerId() {
        $this->db->select('MAX(CAST(TAXID AS UNSIGNED)) as custId');
        $q = $this->db->get('CUSTOMERS')->result();
        $custid = (int) $q[0]->custId;
        if ($custid > 0) {
            $custid = $custid + 1;
        } else {
            $custid = 1000;
        }
        echo $custid;
    }

    function listmembers($id=''){
        $reccustmembs = $this->customers_model->customerMembersList($id);
        if($reccustmembs){
            echo '<div class="form-group"><a href="#" class="btn btn-success shiny btn-xs" onclick="addnewmembers()"><i class="fa fa-plus"></i></a></div><table class="table table-striped table-hover table-bordered editable"><tr><td>Slno</td><td>Member Name</td><td>Member Phone</td><td></td></tr>';
            $sl=1;
            foreach($reccustmembs as $custmemb){
                echo "<tr><td>".$sl."</td><td>";
                echo $custmemb->MEMBER_NAME;
                echo "</td>";
                echo "<td>";
                echo $custmemb->MEMBER_PHONE;
                echo "</td>";
                echo "<td><a href='#' onclick=editcustmemb('".$custmemb->ID."') class='btn btn-success shiny btn-xs'><i class='fa fa-edit'></i></a>&nbsp;&nbsp;<a href='#' class='btn btn-maroon shiny btn-xs' onclick=deleterecsub('".$custmemb->ID."')><i class='fa fa-trash'></i></a></td></tr>";
                $sl++;
            }
            echo "</table>";
        }else{
            echo '<div class="form-group"><a href="#" class="btn btn-success shiny btn-xs" onclick="addnewmembers()"><i class="fa fa-plus"></i></a></div><table class="table table-striped table-hover table-bordered editable"><tr><td>Slno</td><td>Member Name</td><td>Member Phone</td><td></td></tr><tr><td colspan="4">No records found</td></tr></table>';
        }
    }
    
    function addcustmember(){
        $dataArr["CUSTOMER_ID"]     = $this->input->post('CMEMB_ID');
        $dataArr["SEARCHKEY"]       = $this->input->post('CMEMB_SEARCHKEY');
        $dataArr["MEMBER_NAME"]     = $this->input->post('CMEMB_MEMBER_NAME');
        $dataArr["MEMBER_PHONE"]    = $this->input->post('CMEMB_MEMBER_PHONE');
        $dataArr["MEMBER_ADDRESS"]  = $this->input->post('CMEMB_MEMBER_ADDRESS');
        if($this->input->post('ID')==''){
            $dataArr["ID"]              = uniqid();
            echo $this->customers_model->customerMembersAdd($dataArr);
        }else{
            echo $this->customers_model->customerMembersupdate($dataArr,$this->input->post('ID'));
        }
    }
    
    function editcustmember(){
        $custmembrec    =    $this->customers_model->getcustomermember($this->input->post('editid'));
        echo json_encode($custmembrec, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }
    
    function deletecustmember(){
        $where = array('ID' => $this->input->post('delid'));
        $this->common->delete('CUSTOMER_MEMBERS', $where);
        echo true;
    }
    
    
    function subtablemembers($id=''){
        $reccustmembs = $this->customers_model->customerMembersList($id);
        echo json_encode($reccustmembs);
    }
    
    // Customer card printing
    function getcustomerdetails($id='') {
        $sql = "SELECT * FROM CUSTOMERS WHERE ID LIKE '".$id."'";
        return $this->common->customquery($sql);
    }
    
    function customercardprint($pid='') {
        $data['customerid']=$pid;
        $data['customer'] = $this->getcustomerdetails($pid);
        $data['fields']=$this->getcustomerlabeldetails($pid);
        $data['template'] = 'partner/customer_details';
        $this->load->view('template',$data);
    }
    
    function getcustomerlabeldetails($id='') {      
        $this->load->model('inventory/customers_model');
        $result     =   $this->customers_model->getCustomerById($id);
        $result     =   $result[0];
        $result->CUSTOMERNAME = $result->NAME;
        $result->CUSTOMERCARD = $result->CARD;
        $result->CUSTOMERCODE = $result->TAXID;
        $result->CUSTOMERADDRESS = $result->ADDRESS;
        $result->CUSTOMERCITY = $result->CITY;
        $result->CUSTOMERREGION = $result->REGION;
        $result->CUSTOMERCOUNTRY = $result->COUNTRY;
        $result->CUSTOMEREMAIL = $result->EMAIL;
        $result->CUSTOMERPHONE = $result->PHONE;  
        $labelformat = $this->getcustomerlabelformat();
        $labelfields = "";
        foreach ($labelformat->children() as $child) {
            if($child->getName()=='photo') {
                $fieldname = '';
                preg_match('~{(.*?)}~', $child, $fieldname);
                $labelfields .= '"' . $child->getName() . '": "' . $child . '", ';
            } else {
                $fieldname = '';
                preg_match('~{(.*?)}~', $child, $fieldname);
                if (count($fieldname) > 1) {
                    list($pre, $post) = explode($fieldname[0], $child);
                    $varstring  =   str_replace('"','&quot;',$result->{$fieldname[1]});
                    $labelfields .= '"' . $child->getName() . '": "' . $pre . $varstring . $post . '", ';
                } else {
                    $labelfields .= '"' . $child->getName() . '": "' . $child . '", ';
                }
            }
        }
        $labelfields = rtrim($labelfields, ", ");
        $labelfields = "{" . $labelfields . "}";
        return $labelfields;
    }

    function getcustomerlabelformat() {
        $labelformats = $this->customers_model->getCustomercardlabelformat();
        $labelformat = $labelformats->label[0];
        return $labelformat;
    }

    function printlabel() {
        $_POST["customer"] = $this->input->post('customerid');
        $custid = $this->input->post('customerid');
        $result = $this->customers_model->getCustomerById($custid);
//        $this->load->library('label_helper');
        $labelsizes = $this->customers_model->getCustomercardlabelformat();
        $labelformat = $this->getcustomerlabelformat();
        $data = array();
        $info = array();
        $n=0;
        array_push($data, $info);
        $labelsize=$labelsizes->label->attributes();
        // Include the main TCPDF library (search for installation path).
        require FCPATH.'application/libraries/tcpdf/tcpdf.php';
        // create new PDF document
        $custom_layout = array((string)$labelsize['width'], (string)$labelsize['height']);
        $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, $custom_layout, true, 'UTF-8', false);
        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor("Saleculator");
        $pdf->SetTitle("Customer Labels");
        $pdf->SetSubject("Saleculator Customer Labels");
        $pdf->SetKeywords("saleculator, label, Customer, saleculator");
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetHeaderMargin(0);
        $pdf->SetFooterMargin(0);
        $pdf->SetAutoPageBreak(true, 0);
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
        if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
            require_once(dirname(__FILE__).'/lang/eng.php');
            $pdf->setLanguageArray($l);
        }
        $pdf->AddPage();
            foreach ($_POST as $key => $value) {
                if ($key != 'submit' && $key != 'customerid' && $key != 'customer') {
                    if ($key == 'barcode') {
                        $info[$n]['barcode'] = $value;
                    } else if ($key == 'photo') {
                        $info[$n]['photo'] = $value;
                    } else {
                        $info[$n]['value'] = $value;
                    }
                    foreach ($labelformat->children() as $child) {
                        foreach ($child->attributes() as $a => $b) {
                            if($child->getName()==$key)
                            {$info[$n][$a] = $b;}
                        }
                    }
                    $n=$n+1;
                }
            }
            $cnt    =   count($info);
//            $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
            if($cnt>0){
                for($i=0;$i<$cnt;$i++){
                    if(isset($info[$i]["value"])) {
                        $pdf->SetFont('', '', $info[$i]["size"],'','',true);
                        $pdf->SetFillColor(255,255,255);
        // MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0)
                        $pdf->MultiCell((string)$labelsize['width'],0, $info[$i]["value"], 0, $info[$i]["align"], 'C', 0, $info[$i]["x"], $info[$i]["y"]);
                    } else if(isset($info[$i]["barcode"])){
                        $style = array(
                            'stretch' => false,
                            'fitwidth' => true,
                            'cellfitalign' => '',
                            'border' => false,
                            'fgcolor' => array(0,0,0),
                            'bgcolor' => false,
                            'text' => true,
                            'font' => 'helvetica',
                            'fontsize' => $info[$i]["size"],
                            'stretchtext' => 1
                        );
                        $pdf->SetXY($info[$i]["x"], $info[$i]["y"]);
                        $pdf->Cell(0, 0, '', 0, 1);
                        $pdf->write1DBarcode($info[$i]["barcode"], 'C39', '', '', '', $info[$i]["size"], 0.4, $style, 'N');
                        $pdf->Ln();
                    } else if(isset($info[$i]["photo"])){
                        if($info[$i]["photo"]) {
                            $custimg            =   $this->customers_model->getcustomerimage($info[$i]["photo"]);
                            $pdf->setJPEGQuality(75);
                            $imgdata = base64_decode(base64_encode($custimg->CONTENT));
                            $pdf->Image('@'.$imgdata,$info[$i]["x"],$info[$i]["y"],$info[$i]["size"],0);
                        }
                    }
                }
            }
        //Close and output PDF document
        $pdf->Output('example_009.pdf', 'I');
    }
}