<?php



class ControllerTransactionSaleOrder extends HController {

    protected $document_type_id = 5;



    protected function getAlias() {

        return 'transaction/sale_order';

    }



    protected function getPrimaryKey() {

        return 'sale_order_id';

    }



    protected function getList() {

        parent::getList();



        $arrStatus = array(

            1 => $this->language->get('text_enabled'),

            2 => $this->language->get('text_disabled'),

        );



        $filter_column = array(

            'title' => array('function' => 'text_like_both'),

            'status' => array('function' => 'select_equal', 'option_list' => $arrStatus),

            'created_at' => array('function' => 'date_between')

        );



        $clsFilter = new filter();

        $this->data['filter'] = $clsFilter->getFilterColumns($filter_column, $this->getFilter());



        $results = $this->getListData();

        foreach ($results['lists'] as $result) {

            $action = array();



            $action[] = array(

                'text' => $this->language->get('text_edit'),

                'href' => $this->url->link($this->getAlias() . '/update', 'token=' . $this->session->data['token'] . '&' . $this->getPrimaryKey() . '=' . $result[$this->getPrimaryKey()] . $url, 'SSL')

            );



            $this->data['results'][] = array(

                'sale_order_id' => $result['sale_order_id'],

                'title' => $result['title'],

                'builty_no' => $result['builty_no'],

                'supplier_id' => $arrSupplier[$result['supplier_id']],

                'status' => ($result['status'] == 1 ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),

                'created_at' => date($this->language->get('date_format_short'), strtotime($result['created_at'])),

                'selected' => isset($this->request->post['selected']) && in_array($result['sale_order_id'], $this->request->post['selected']),

                'action' => $action

            );

        }



        $sort_column = array('title' => 'Title', 'status' => 'Status', 'created_at' => 'Created At');



        $ignore_columns = array($this->getPrimaryKey(), 'selected', 'action');

        $this->setSortURL($sort_column, $ignore_columns);



        $this->setPagination($results['total']);

//        d($this->data['order'],true);



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

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

    }



    protected function insertData($data) {

        $document = $this->document_type->getNextInvoiceNo($this->document_type_id);

        $data['invoice_date'] = MySqlDate($data['invoice_date']);

        $data['company_id'] = $this->session->data['company_id'];

        $data['company_branch_id'] = $this->session->data['company_branch_id'];

        $data['fiscal_year_id'] = $this->session->data['fiscal_year_id'];

        $data['document_type_id'] = $this->document_type_id;

        $data['document_prefix'] = $document['document_prefix'];

        $data['document_no'] = $document['document_no'];

        $data['invoice_no'] = $document['invoice_no'];

        

        

      $sale_order_id = $this->model[$this->getAlias()]->add($this->getAlias(), $data);



        $this->model['sale_order_detail'] = $this->load->model('transaction/sale_order_detail');

		

        foreach ($data['sale_order_detail'] as $detail) {

            $detail['sale_order_id'] = $sale_order_id;

            $sale_order_detail_id= $this->model['sale_order_detail']->add($this->getAlias(), $detail);

        }



        return $sale_order_id;

    }

	

    protected function getForm() {

        parent::getForm();



        if (isset($this->request->get['sale_order_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {

            $result = $this->model_transaction_sale_order->getSaleOrder($this->request->get['sale_order_id']);

            foreach ($result as $field => $value) {

                if ($field == 'invoice_date') {

                    $this->data[$field] = stdDate($value);

                } else {

                    $this->data[$field] = $value;

                }

            }

            $this->model['sale_order_detail'] = $this->load->model('transaction/sale_order_detail');

            $this->data['sale_order_details'] = $this->model['sale_order_detail']->getSaleOrderDetailsByFilter(array(

                'sale_order_id' => $this->request->get['sale_order_id']));

        }

        

        $this->model['customer'] = $this->load->model('setup/customer');

        $this->data['customers'] = $this->model['customer']->getCustomers(array('company_id' => $this->session->data['company_id']));



        $this->model['product'] = $this->load->model('setup/product');

        $this->data['products'] = $this->model['product']->getProducts(array('company_id' => $this->session->data['company_id']));







        $this->model['unit'] = $this->load->model('setup/unit');

        $this->data['units'] = $this->model['unit']->getUnits();



        $this->data['action_validate_date'] = $this->url->link('common/home/validateDate', 'token=' . $this->session->data['token']);

        $this->data['strValidation'] = "{

            'rules': {

                'invoice_date': {'required': true, 'remote':  {url: '" . $this->data['action_validate_date'] . "', type: 'post'}},

            },

        }";



//        //        $this->document->addScript("view/javascript/jquery/jquery.dataTables.min.js");

//        $this->document->addLink("view/stylesheet/dataTables.css", "stylesheet");

//        $this->document->addScript("view/js/plugins/dataTables/js/jquery.dataTables.js");

//        $this->document->addScript("view/js/plugins/dataTables/js/jquery.dataTables.columnFilter.js");

////        $this->document->addLink("view/js/plugins/dataTables/css/jquery.dataTables.css", "stylesheet");

//



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

    }



    protected function updateData($primary_key, $data) {

        $sale_order_id = $primary_key;

		$data['invoice_date'] = MySqlDate($data['invoice_date']);

        $this->model['sale_order'] = $this->load->model('transaction/sale_order');

        $this->model['sale_order_detail'] = $this->load->model('transaction/sale_order_detail');



        $this->model['sale_order']->edit($this->getAlias(), $primary_key, $data);



    $this->model['sale_order_detail']->deleteBulk($this->getAlias(), array('sale_order_id' => $sale_order_id));



        foreach ($data['sale_order_detail'] as $detail) {

            $detail['sale_order_id'] = $sale_order_id;



            $this->model['sale_order_detail']->add($this->getAlias(), $detail);

        }

    }



    protected function validateForm() {

        if ($this->request->post['invoice_date'] == '') {

            $this->error['invoice_date'] = $this->language->get('error_required_invoice_date');

        }





        if (!isset($this->request->post['sale_order_detail'])) {

            $this->error['warning'] = $this->language->get('Insert Sale Order Detail');

        }







        if (!$this->error) {

            return true;

        } else {

            return false;

        }

    }



    protected function validateDelete() {

        if (!$this->user->hasPermission('delete', $this->getAlias())) {

            $this->error['warning'] = $this->language->get('error_permission_delete');

        }



        if (!$this->error) {

            return true;

        } else {

            return false;

        }

    }



    public function getSaleOrderCharges() {

        if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->request->post['sale_order_id']) {

            $this->model['sale_order'] = $this->load->model('transaction/sale_order');

            $charges = $this->model['sale_order']->getSaleOrderCharges($this->request->post['sale_order_id']);

            $json = array(

                'success' => true,

                'charges' => $charges

            );

        } else {

            $this->load->language('transaction/sale_order');

            $json = array(

                'success' => false,

                'error' => $this->language->get('error_select_sale_order')

            );

        }



        $this->response->setOutput(json_encode($json));

    }



    public function getAjaxLists() {



        $this->model['customer'] = $this->load->model('setup/customer');

        $arrCustomer = $this->model['customer']->getCustomerArray();



        $this->load->language('transaction/sale_order');

        $this->model[$this->getAlias()] = $this->load->model($this->getAlias());

        $data = array();

        $aColumns = array('action', 'invoice_no', 'invoice_date', 'customer_id', 'net_amount');



        /*

         * 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'] . "'";

            $sWhere .= " AND company_branch_id = '" . $this->session->data['company_branch_id'] . "'";

            $sWhere .= " AND fiscal_year_id = '" . $this->session->data['fiscal_year_id'] . "'";

        } else {

            $sWhere .= "WHERE company_id = '" . $this->session->data['company_id'] . "'";

            $sWhere .= " AND company_branch_id = '" . $this->session->data['company_branch_id'] . "'";

            $sWhere .= " AND fiscal_year_id = '" . $this->session->data['fiscal_year_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();



            if($aRow['is_post'] == 1){

                $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'

                );

            }

            else{

                $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] == 'customer_id') {

                    $row[] = $arrCustomer[$aRow['customer_id']];

                }elseif($aColumns[$i]=='invoice_date') {
                    $row[] = stdDate($aRow['invoice_date']);
                } else {

                    $row[] = $aRow[$aColumns[$i]];

                }

            }

            $output['aaData'][] = $row;

        }



        echo json_encode($output);

    }



}



?>