<?php

class ControllerSetupSalesman extends HController {

    protected function getAlias() {
        return 'setup/salesman';
    }

    protected function getPrimaryKey() {
        return 'salesman_id';
    }

    protected function getList() {
        parent::getList();

        $this->data['action_ajax'] = $this->url->link($this->getAlias() . '/getAjaxLists', 'token=' . $this->session->data['token'], 'SSL');

        $this->response->setOutput($this->render());
    }

    protected function getForm() {
        parent::getForm();

        if (isset($this->request->get['salesman_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
            $result = $this->model_setup_salesman->getsalesman($this->request->get['salesman_id']);
            foreach ($result as $field => $value) {
                if ($field == 'date_from' || $field == 'date_to') {
                    $this->data[$field] = stdDate($value);
                } else {
                    $this->data[$field] = $value;
                }
            }
        }



        $this->model['mapping_account'] = $this->load->model('gl/mapping_coa');
        $this->data['cash_accounts'] = $this->model['mapping_account']->getRows(array('company_id' => $this->session->data['company_id'], 'mapping_type_code' => 'CA'));
        $this->data['outstanding_accounts'] = $this->model['mapping_account']->getRows(array('company_id' => $this->session->data['company_id'], 'mapping_type_code' => 'AP'));
        $this->data['advance_accounts'] = $this->model['mapping_account']->getRows(array('company_id' => $this->session->data['company_id'], 'mapping_type_code' => 'ADP'));


        $this->data['action_validate_name'] = $this->url->link($this->getAlias() . '/validateName', 'token=' . $this->session->data['token'] . '&salesman_id=' . $this->request->get['salesman_id']);
        $this->data['strValidation']="{
            'rules':{
                'name': {'required':true, 'minlength': 3, 'remote':  {url: '" . $this->data['action_validate_name'] . "', type: 'post'}},
		        'cash_account_id': {'required':true},
		        'outstanding_account_id': {'required': true},
    		    'advance_account_id': {'required': true},

		        'email': {'email': true},
		        'mobile': {'required': true},
		        'phone': {'required': true},
             },
            'messages':{
                'name': {'required': '" . $this->language->get('error_name') . "'},
		        'cash_account_id': {'required': '" . $this->language->get('error_cash_account') . "'},
		        'payable_account_id': {'required': '" . $this->language->get('error_payable_account') . "'},
		        'payable_advance_id': {'required': '" . $this->language->get('error_advance_account') . "'},
		        'email': {'email': '" . $this->language->get('error_email') . "'},
		        'mobile': {'required': '" . $this->language->get('error_mobile') . "'},
		        'phone': {'required': '" . $this->language->get('error_phone') . "'},
		     },
		     'ignore':[]
          }";

        $this->response->setOutput($this->render());
    }

    protected function insertData($data) {
        $data['company_id'] = $this->session->data['company_id'];
        $this->model[$this->getAlias()]->add($this->getAlias(), $data);
    }

    public function getAjaxLists() {

        $this->load->language('setup/salesman');
        $this->model[$this->getAlias()] = $this->load->model($this->getAlias());
        $data = array();
        $aColumns = array('action', 'name', 'phone', 'email', 'created_at');

        /*
         * Paging
         */
        $sLimit = "";
        if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
            $data['criteria']['start'] = $_GET['iDisplayStart'];
            $data['criteria']['limit'] = $_GET['iDisplayLength'];
        }

        /*
         * Ordering
         */
        $sOrder = "";
        if (isset($_GET['iSortCol_0'])) {
            $sOrder = " ORDER BY  ";
            for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
                if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
                    $sOrder .= "`" . $aColumns[intval($_GET['iSortCol_' . $i])] . "` " .
                        ($_GET['sSortDir_' . $i] === 'asc' ? 'asc' : 'desc') . ", ";
                }
            }

            $sOrder = substr_replace($sOrder, "", -2);
            if ($sOrder == " ORDER BY") {
                $sOrder = "";
            }
            $data['criteria']['orderby'] = $sOrder;
        }


        /*
         * Filtering
         * NOTE this does not match the built-in DataTables filtering which does it
         * word by word on any field. It's possible to do here, but concerned about efficiency
         * on very large tables, and MySQL's regex functionality is very limited
         */
        $sWhere = "";
        if (isset($_GET['sSearch']) && $_GET['sSearch'] != "") {
            $sWhere = "WHERE (";
            for ($i = 0; $i < count($aColumns); $i++) {
                if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true" && $_GET['sSearch'] != '') {
                    $sWhere .= "`" . $aColumns[$i] . "` LIKE '%" . mysql_real_escape_string($_GET['sSearch']) . "%' OR ";
                }
            }
            $sWhere = substr_replace($sWhere, "", -3);
            $sWhere .= ')';
        }

        /* Individual column filtering */
        for ($i = 0; $i < count($aColumns); $i++) {
            if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true" && $_GET['sSearch_' . $i] != '') {
                if ($sWhere == "") {
                    $sWhere = "WHERE ";
                } else {
                    $sWhere .= " AND ";
                }
                $sWhere .= "`" . $aColumns[$i] . "` LIKE '%" . mysql_real_escape_string($_GET['sSearch_' . $i]) . "%' ";
            }
        }
        if ($sWhere != "") {
            $sWhere .= " AND company_id = '" . $this->session->data['company_id'] . "'";
        } else {
            $sWhere .= "WHERE company_id = '" . $this->session->data['company_id'] . "'";
        }

        if ($sWhere != "") {
            $data['filter']['RAW'] = substr($sWhere, 5, strlen($sWhere) - 5);
        }

        //d($data);
        $results = $this->model[$this->getAlias()]->getLists($data);
        $iFilteredTotal = $results['total'];
        $iTotal = $results['table_total'];


        /*
         * Output
         */
        $output = array(
            "sEcho" => intval($_GET['sEcho']),
            "iTotalRecords" => $iTotal,
            "iTotalDisplayRecords" => $iFilteredTotal,
            "aaData" => array()
        );

        foreach ($results['lists'] as $aRow) {
            $row = array();
            $actions = array();

            $actions[] = array(
                'text' => $this->language->get('text_edit'),
                'href' => $this->url->link($this->getAlias() . '/update', 'token=' . $this->session->data['token'] . '&' . $this->getPrimaryKey() . '=' . $aRow[$this->getPrimaryKey()], 'SSL'),
                'class' => 'fa fa-pencil'
            );

            $actions[] = array(
                'text' => $this->language->get('text_delete'),
                'href' => 'javascript:void(0);',
                'click' => "ConfirmDelete('" . $this->url->link($this->getAlias() . '/delete', 'token=' . $this->session->data['token'] . '&id=' . $aRow[$this->getPrimaryKey()], 'SSL') . "')",
                'class' => 'fa fa-times'
            );


            $strAction = '';
            foreach ($actions as $action) {
                $strAction .= '<a href="' . $action['href'] . '" title="' . $action['text'] . '" ' . (isset($action['click']) ? 'onClick="' . $action['click'] . '"' : '') . '>';
                if (isset($action['class'])) {
                    $strAction .= '<span class="' . $action['class'] . '"></span>';
                } else {
                    $strAction .= $action['text'];
                }
                $strAction .= '</a>&nbsp;';
            }

            $row[] = $strAction;
            for ($i = 1; $i < count($aColumns); $i++) {
                if ($aColumns[$i] == 'status') {
                    $row[] = ($aRow['status'] ==1 ? $this->language->get('text_enabled') : $this->language->get('text_disabled'));
                } elseif($aColumns[$i]=='created_at') {
                    $row[] = stdDateTime($aRow['created_at']);
                } else {
                    $row[] = $aRow[$aColumns[$i]];
                }
            }
            $output['aaData'][] = $row;
        }

        echo json_encode($output);
    }

    public function validateName()
    {
        $name = $this->request->post['name'];
        $company_id = $this->session->data['company_id'];
        $salesman_id = $this->request->get['salesman_id'];

        $this->load->language('setup/salesman');
        if ($name) {
            $this->model['salesman'] = $this->load->model('setup/salesman');
            $where = "company_id='" . $company_id . "' AND LOWER(name) = '".strtolower($name)."' AND salesman_id != '".$salesman_id."'";
            $coa = $this->model['salesman']->getRow($where);
            if ($coa) {
                echo json_encode($this->language->get('error_duplicate_name'));
            } else {
                echo json_encode("true");
            }
        } else {
            echo json_encode($this->language->get('error_name'));
        }
        exit;
    }

}

?>