<?php

class ControllerTransactionSaleInquiry extends HController {
    protected $document_type_id = 26;

    protected function getAlias() {
        return 'transaction/sale_inquiry';
    }

    protected function getPrimaryKey() {
        return 'sale_inquiry_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();

        $this->model['currency'] = $this->load->model('setup/currency');
//
        $this->data['base_currency_id'] = $this->company->getCurrency();
        $this->data['document_currency_id'] = $this->company->getCurrency();
        $this->data['conversion_rate'] = 1;

        if (isset($this->request->get['sale_inquiry_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
            $result = $this->model[$this->getAlias()]->getRow(array($this->getPrimaryKey() => $this->request->get[$this->getPrimaryKey()]));
            foreach ($result as $field => $value) {
                if ($field == 'invoice_date') {
                    $this->data[$field] = stdDate($value);
                } else {
                    $this->data[$field] = $value;
                }
            }
            $this->model['sale_inquiry_detail'] = $this->load->model('transaction/sale_inquiry_detail');
            $this->data['sale_inquiry_details'] = $this->model['sale_inquiry_detail']->getRows(array(
                'sale_inquiry_id' => $this->request->get['sale_inquiry_id']));
        }
      //  d($this->data['sale_inquiry_details']);

        $filter = array(
            'company_id' => $this->session->data['company_id']
        );
        $this->model['customer'] = $this->load->model('setup/customer');
        $this->data['customers'] = $this->model['customer']->getRows($filter);

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

        $this->model['warehouse'] = $this->load->model('setup/warehouse');
        $this->data['warehouses'] = $this->model['warehouse']->getRows(array('company_id' => $this->session->data['company_id'], 'company_branch_id' => $this->session->data['company_branch_id']));

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


        $this->model['ledger'] = $this->load->model('gl/ledger');
        $this->data['ledgers'] = $this->model['ledger']->getRows(array('document_type_id' => $this->document_type_id, 'document_id' => $this->request->get[$this->getPrimaryKey()]));

        $this->data['action_post'] = $this->url->link($this->getAlias() . '/post', 'token=' . $this->session->data['token'] . '&' . $this->getPrimaryKey() . '=' . $this->request->get[$this->getPrimaryKey()], 'SSL');
        $this->data['action_print'] = $this->url->link($this->getAlias() . '/printDocument', 'token=' . $this->session->data['token'] . '&' . $this->getPrimaryKey() . '=' . $this->request->get[$this->getPrimaryKey()], 'SSL');

        $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'}},
                'supplier_id': {'required': true},
                'net_amount': {'required': true},
            },
            'ignore': [],
        }";
        $this->response->setOutput($this->render());

    }

    protected function insertData($data) {
       // d($data,true);
        $document = $this->document_type->getNextInvoiceNo($this->document_type_id);
        $data['voucher_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['voucher_no'] = $document['invoice_no'];
        $data['base_currency_id'] = $this->data['base_currency_id'] = $this->company->getCurrency();
        $data['document_currency_id'] = $this->data['document_currency_id'] = $this->company->getCurrency();
        $data['conversion_rate'] = 1;


        $sale_inquiry_id = $this->model[$this->getAlias()]->add($this->getAlias(), $data);
//d($data,true);
        $this->model['sale_inquiry_detail'] = $this->load->model('transaction/sale_inquiry_detail');

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

            $detail['sale_inquiry_id'] = $sale_inquiry_id;
            $sale_inquiry_detail_id= $this->model['sale_inquiry_detail']->add($this->getAlias(), $detail);
            $filter = array(
                'company_id' => $this->session->data['company_id'],
                'product_id' => $detail['product_id']
            );
            $this->model['product'] = $this->load->model('setup/product');
            $product = $this->model['product']->getRow($filter);


        }


        return $sale_inquiry_id;
    }


    protected function insertRedirect($id, $data) {
        $url = $this->getURL();
        $this->redirect($this->url->link($this->getAlias().'/update', 'token=' . $this->session->data['token'] . '&sale_inquiry_id=' . $id, 'SSL'));
    }
    
    protected function updateData($primary_key, $data) {
        $sale_inquiry_id = $primary_key;
        $data['invoice_date'] = MySqlDate($data['invoice_date']);
        $data['base_currency_id'] = $this->data['base_currency_id'] = $this->company->getCurrency();
        $data['document_currency_id'] = $this->data['document_currency_id'] = $this->company->getCurrency();
        $data['conversion_rate'] = 1;
        //d($data,true);

        $this->model['sale_inquiry'] = $this->load->model('transaction/sale_inquiry');
        $this->model['sale_inquiry_detail'] = $this->load->model('transaction/sale_inquiry_detail');
        $this->model['sale_inquiry']->edit($this->getAlias(), $primary_key, $data);
        $this->model['sale_inquiry_detail']->deleteBulk($this->getAlias(), array('sale_inquiry_id' => $sale_inquiry_id));

        $this->model['document'] = $this->load->model('common/document');
        $document = $this->model['document']->getRow(
            array(
                'company_id' => $this->session->data['company_id'],
                'company_branch_id' => $this->session->data['company_branch_id'],
                'fiscal_year_id' => $this->session->data['fiscal_year_id'],
                'document_type_id' => $data['ref_document_type_id'],
                'document_id' => $data['ref_document_id']
            )
        );

        $this->model['product'] = $this->load->model('setup/product');
        $gl_data = array();
        foreach ($data['sale_inquiry_details'] as $detail) {
            $detail['sale_inquiry_id'] = $sale_inquiry_id;
            $this->model['sale_inquiry_detail']->add($this->getAlias(), $detail);
            $filter = array(
                'company_id' => $this->session->data['company_id'],
                'product_id' => $detail['product_id']
            );
            $product = $this->model['product']->getRow($filter);

        }


        return $sale_inquiry_id;
//d(array($gl,$detail,$data,true));
    }

    protected function updateRedirect($id, $data) {
        $url = $this->getURL();
        $this->redirect($this->url->link($this->getAlias().'/update', 'token=' . $this->session->data['token'] . '&sale_inquiry_id=' . $id, 'SSL'));
    }

    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;
        }
    }

    protected function deleteData($primary_key) {
        $this->model['sale_inquiry_detail'] = $this->load->model('transaction/sale_inquiry_detail');
        $this->model['sale_inquiry_detail']->deleteBulk($this->getAlias(), array('sale_inquiry_id' => $primary_key));

        $this->model[$this->getAlias()]->delete($this->getAlias(), $primary_key);
    }

//    public function getPurchaseOrderCharges() {
//        if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->request->post['sale_inquiry_id']) {
//            $this->model['sale_inquiry'] = $this->load->model('transaction/sale_inquiry');
//            $charges = $this->model['sale_inquiry']->getPurchaseOrderCharges($this->request->post['sale_inquiry_id']);
//            $json = array(
//                'success' => true,
//                'charges' => $charges
//            );
//        } else {
//            $this->load->language('transaction/sale_inquiry');
//            $json = array(
//                'success' => false,
//                'error' => $this->language->get('error_select_sale_inquiry')
//            );
//        }
//
//        $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_inquiry');
        $this->model[$this->getAlias()] = $this->load->model($this->getAlias());
        $data = array();
        $aColumns = array('action', 'voucher_no', 'voucher_date', 'customer_id','amount');
//d($aColumns,true);
        /*
         * 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);
       // d($results,true);
        $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'
                    );
                    $actions[] = array(
                        'text' => $this->language->get('text_post'),
                        'href' => 'javascript:void(0);',
                        'click' => "ConfirmPost('" . $this->url->link($this->getAlias() . '/post', 'token=' . $this->session->data['token'] . '&sale_inquiry_id=' . $aRow[$this->getPrimaryKey()], 'SSL') . "')",
                        'class' => 'fa fa-list'
                    );
                }



            $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]=='voucher_date') {
                    $row[] = stdDate($aRow['voucher_date']);
                } else {
                    $row[] = $aRow[$aColumns[$i]];
                }
            }
            $output['aaData'][] = $row;
        }

        echo json_encode($output);
    }

    public function ajaxValidateForm() {
        $post  = $this->request->post;
        $lang = $this->load->language('transaction/sale_inquiry');
        $error = array();

        if($post['invoice_date'] == '') {
            $error[] = $lang['error_voucher_date'];
        }

        if($post['customer_id'] == '') {
            $error[] = $lang['error_customer'];
        }

        $details = $post['sale_inquiry_details'];
        if(empty($details)) {
            $error[] = $lang['error_input_detail'];
        } else {
            $row_no = 0;
            foreach($details as $detail) {
                $row_no++;
                if($detail['product_code'] == '') {
                    $error[] = $lang['error_product_code'] . ' for Row ' . $row_no;
                }
                if($detail['product_id'] == '') {
                    $error[] = $lang['error_product'] . ' for Row ' . $row_no;
                }
                if($detail['qty'] == '') {
                    $error[] = $lang['error_qty'] . ' for Row ' . $row_no;
                }
                if($detail['unit_id'] == '') {
                    $error[] = $lang['error_unit'] . ' for Row ' . $row_no;
                }

            }
        }

        if (!$error) {
            $json = array(
                'success' => true
            );
        } else {
            $json = array(
                'success' => false,
                'error' => implode("\r\n",$error),
                'errors' => $error,
                'post' => $post
            );
        }

        echo json_encode($json);
        exit;
    }


    public function post() {
        $data = array(
            'is_post' => 1,
            'post_date' => date('Y-m-d H:i:s'),
            'post_by_id' => $this->user->getId()
        );

        $this->model['sale_inquiry'] = $this->load->model('transaction/sale_inquiry');
        $this->model['sale_inquiry']->edit($this->getAlias(),$this->request->get['sale_inquiry_id'],$data);

        $this->redirect($this->url->link($this->getAlias() . '/update', 'token=' . $this->session->data['token'] . '&' . $this->getPrimaryKey() . '=' . $this->request->get[$this->getPrimaryKey()], 'SSL'));

    }

    public function printDocument() {
        $sale_inquiry_id = $this->request->get['sale_inquiry_id'];
        $this->data['lang'] = $this->load->language($this->getAlias());

        $this->model['company'] = $this->load->model('setup/company');
        $company = $this->model['company']->getRow(array('company_id' => $this->session->data['company_id']));
        $this->data['company'] = $company;

        $this->model['company_branch'] = $this->load->model('setup/company_branch');
        $this->data['company_branch'] = $this->model['company_branch']->getRow(array('company_id' => $this->session->data['company_id'], 'company_branch_id' => $this->session->data['company_branch_id']));

        $this->load->model('tool/image');
        if ($company['company_logo'] && file_exists(DIR_IMAGE . $company['company_logo'])) {
            $company_logo = $this->model_tool_image->resize($company['company_logo'], 75, 75);
        } else {
            $company_logo = "";
        }

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

        $this->model['mapping_account'] = $this->load->model('gl/mapping_account');
        $arrBankAccounts = $this->model['mapping_account']->getArrays('coa_level3_id','level3_display_name',array('code' => 'BK'),array('level3_display_name'));

        $this->model['sale_inquiry'] = $this->load->model('transaction/sale_inquiry');
        $row = $this->model['sale_inquiry']->getRow(array('sale_inquiry_id' => $sale_inquiry_id));

        $this->model['customer'] = $this->load->model('setup/customer');
        $arrsupp = $this->model['customer']->getArrays('customer_id','name');

        $this->model['product'] = $this->load->model('setup/product');
        $arrPeoples = $this->model['product']->getArrays('product_id','name',array('company_id' => $this->session->data['company_id']));

        $this->model['warehouse'] = $this->load->model('setup/warehouse');
        $arrwarehouse = $this->model['warehouse']->getArrays('warehouse_id','name',array('company_id' => $this->session->data['company_id']));

        $this->model['unit'] = $this->load->model('setup/unit');
        $arrunit = $this->model['unit']->getArrays('unit_id','name',array('company_id' => $this->session->data['company_id']));

//        $this->model['currency'] = $this->load->model('setup/currency');
//        $arrcurrency = $this->model['currency']->getArrays('currency_id','name',array('company_id' => $this->session->data['company_id']));
        // d(array($row,$currency),true);

        $this->data['voucher_date'] = $row['voucher_date'];
        $this->data['voucher_no'] = $row['voucher_no'];
        $this->data['remarks'] = $row['remarks'];
        $this->data['address'] = $row['address'];
        $this->data['invoice_type'] = $row['invoice_type'];
        //$this->data['supplier_invoice_no'] = $row['supplier_invoice_no'];
       // $this->data['builty_no'] = $row['builty_no'];
        $this->data['people_type'] = $arrsupp[$row['customer_id']];
//        $this->data['invoice_currency'] = $arrcurrency[$row['invoice_currency_id']];
//        $this->data['base_currency'] = $arrcurrency[$row['base_currency_id']];
//        $this->data['conversion_rate'] = $row['conversion_rate'];
//d($row,true);
        $this->model['gl'] = $this->load->model('gl/coa');
        $arrCOAs = $this->model['gl']->getArrays('coa_id','display_name',array('company_id' => $this->session->data['company_id']));

        $this->model['sale_inquiry_detail'] = $this->load->model('transaction/sale_inquiry_detail');
        $details = $this->model['sale_inquiry_detail']->getRows(array('sale_inquiry_id' => $sale_inquiry_id));
        foreach($details as $detail) {

            $this->data['details'][] = array_merge($detail,array('product_id' => $arrPeoples[$detail['product_id']],'warehouse_id' => $arrwarehouse[$detail['warehouse_id']],'unit_id' => $arrunit[$detail['unit_id']]));


        }
//d($detail,true);
        $this->template = 'transaction/sale_inquiry_print.tpl';
        $contents = $this->render();

//        d($contents,true);

        try
        {
            // init HTML2PDF
            $html2pdf = new HTML2PDF('L', 'A5', 'en', true, 'UTF-8', array(0, 0, 0, 0));

            // display the full page
            $html2pdf->pdf->SetDisplayMode('fullpage');

            // convert
            $html2pdf->writeHTML($contents);

            // send the PDF
            $html2pdf->Output('StockLedger.pdf');
        }
        catch(HTML2PDF_exception $e) {
            echo $e;
            exit;
        }

    }

}

?>