<?php
class ControllerVehicleDispatchInvoice extends HController {
    protected $document_type_id = 30;

    protected function getAlias() {
        return 'vehicle/dispatch_invoice';
    }

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

    public function getAjaxLists() {
        $lang = $this->load->language('vehicle/dispatch_invoice');
        $this->model[$this->getAlias()] = $this->load->model($this->getAlias());
        $data = array();
        $aColumns = array('action', 'document_identity', 'document_date', 'customer_id','commodity','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 '%" . $this->db->escape($_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 '%" . $this->db->escape($_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();
            $actions[] = array(
                'text' => $lang['edit'],
                'href' => $this->url->link($this->getAlias() . '/update', 'token=' . $this->session->data['token'] . '&' . $this->getPrimaryKey() . '=' . $aRow[$this->getPrimaryKey()], 'SSL'),
                'btn_class' => 'btn btn-primary btn-xs',
                'class' => 'fa fa-pencil'
            );
            if($aRow['is_post'] == 0) {
                $actions[] = array(
                    'text' => $lang['delete'],
                    'href' => 'javascript:void(0);',
                    'click' => "ConfirmDelete('" . $this->url->link($this->getAlias() . '/delete', 'token=' . $this->session->data['token'] . '&id=' . $aRow[$this->getPrimaryKey()], 'SSL') . "')",
                    'btn_class' => 'btn btn-danger btn-xs',
                    'class' => 'fa fa-times'
                );
                $actions[] = array(
                    'text' => $lang['post'],
                    'href' => $this->url->link($this->getAlias() . '/post', 'token=' . $this->session->data['token'] . '&' . $this->getPrimaryKey() . '=' . $aRow[$this->getPrimaryKey()], 'SSL'),
                    'btn_class' => 'btn btn-info btn-xs',
                    'class' => 'fa fa-thumbs-up'
                );
            }

            $strAction = '';
            foreach ($actions as $action) {
                $strAction .= '<a '.(isset($action['btn_class'])?'class="'.$action['btn_class'].'"':'').' '.(isset($action['target'])?'target="'.$action['target'].'"':'').' href="' . $action['href'] . '" data-toggle="tooltip" 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;';
            }
            for ($i = 0; $i < count($aColumns); $i++) {
                if ($aColumns[$i] == 'action') {
                    $row[] = $strAction;
                } elseif ($aColumns[$i] == 'document_date') {
                    $row[] = stdDate($aRow['document_date']);
                } elseif ($aColumns[$i] == 'created_at') {
                    $row[] = stdDateTime($aRow['created_at']);
                } else {
                    $row[] = $aRow[$aColumns[$i]];
                }
            }
            $output['aaData'][] = $row;
        }
        echo json_encode($output);


    }

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

        if (isset($this->request->get['dispatch_invoice_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 == 'document_date') {
                    $this->data[$field] = stdDate($value);
                } else {
                    $this->data[$field] = $value;
                }
            }
            
            $this->model['dispatch_invoice_commodity'] = $this->load->model('vehicle/dispatch_invoice_commodity');
            $rows = $this->model['dispatch_invoice_commodity']->getRows(array('dispatch_invoice_id' => $result['dispatch_invoice_id']));
            $this->data['woc'] = array();
            foreach($rows as $row) {
                $this->data['woc'][$result['commodity']][$row['field']] = $row['value'];
            }

            $this->model['dispatch_invoice_detail'] = $this->load->model('vehicle/dispatch_invoice_detail');
            $this->data['dispatch_invoice_details'] = $this->model['dispatch_invoice_detail']->getRows(
                array(
                    'dispatch_invoice_id' => $this->request->get['dispatch_invoice_id']
                )
            );
            $this->model['ledger'] = $this->load->model('gl/ledger');
            $ledgers = $this->model['ledger']->getRows(array('document_type_id' => $this->document_type_id, 'document_id' => $this->request->get[$this->getPrimaryKey()]),array('sort_order ASC'));
            foreach($ledgers as $ledger) {
                if(isset($this->data['ledgers'][$ledger['coa_id']])) {
                    $this->data['ledgers'][$ledger['coa_id']]['debit'] += $ledger['debit'];
                    $this->data['ledgers'][$ledger['coa_id']]['credit'] += $ledger['credit'];
                } else {
                    $this->data['ledgers'][$ledger['coa_id']] = $ledger;
                }
            }
        }

        $this->model['coa']=$this->load->model('gl/coa_level3');
        $this->data['coas']=$this->model['coa']->getRows(array('company_id' => $this->session->data['company_id']));

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

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


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

        $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': {
                'document_date': {'required': true, 'remote':  {url: '" . $this->data['action_validate_date'] . "', type: 'post'}},
                'customer_id': {'required': true},
                'commodity': {'required': true},
            },
        }";
        $this->response->setOutput($this->render());
    }

    protected function insertData($data) {
//        d($data,true);
        $gl_data = array();

        $document = $this->document_type->getNextInvoiceNo($this->document_type_id);
        $data['document_date'] = MySqlDate($data['document_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['document_identity'] = $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;
        $data['gate_in'] = MySqlDateTime($data['gate_in'].':00');
        $data['gate_out'] = MySqlDateTime($data['gate_out'].':00');

      //  d(array($document,$data),true);
//
        $this->model['dispatch_invoice'] = $this->load->model('vehicle/dispatch_invoice');
        $dispatch_invoice_id = $this->model[$this->getAlias()]->add($this->getAlias(), $data);

        $this->model['customer'] = $this->load->model('setup/customer');
        $supplier = $this->model['customer']->getCustomer($data['customer_id']);
        $credit_account = $supplier['receivable_account_id'];
        $advanceAccount = $supplier['advance_account_id'];

        $sale_tax_account = $this->company->getSaleTaxAccount();
        $this->model['mapping_account'] = $this->load->model('gl/mapping_account');
        $IncometaxAccount = $this->model['mapping_account']->getRow(array('company_id' => $this->session->data['company_id'], 'code' => 'ICT'));
        $IncomeTaxAccount_id = $IncometaxAccount['coa_level3_id'];

        $FrieghtAccount = $this->model['mapping_account']->getRow(array('company_id' => $this->session->data['company_id'], 'code' => 'FR'));
        $FrieghtAccount_id = $FrieghtAccount['coa_level3_id'];

//////////////////////////// Master Ledger Entry /////////////////////////////////////

        $totalDebit = 0;
        $totalCredit = 0;
        $totalReceivable =0;

        $this->model['dispatch_invoice_commodity'] = $this->load->model('vehicle/dispatch_invoice_commodity');
        foreach ($data['woc'][$data['commodity']] as $field => $value) {
            $dataDetail = array(
                'dispatch_invoice_id' => $dispatch_invoice_id,
                'field' => $field,
                'value' => $value


            );
            if($field == "freight")
            {
                $totalCredit += $value;

                $gl_data[] = array(
                    'ref_document_type_id' => $this->document_type_id,
                    'ref_document_id' => $dispatch_invoice_id,
                    'ref_document_identity' => $data['document_identity'],
                    'coa_id' => $FrieghtAccount_id,
                    'document_debit' => 0,
                    'document_credit' => $value,
                    'debit' => 0,
                    'credit' => $value
                );
            }
            else if($field == "sales_tax_amount")
            {
                $totalCredit += $value;

                $gl_data[] = array(
                    'ref_document_type_id' => $this->document_type_id,
                    'ref_document_id' => $dispatch_invoice_id,
                    'ref_document_identity' => $data['document_identity'],
                    'coa_id' => $sale_tax_account,
                    'document_debit' => 0,
                    'document_credit' => $value,
                    'debit' => 0,
                    'credit' => $value
                );
            }
            else if($field == "income_tax_amount")
            {

                $totalCredit += $value;
                $gl_data[] = array(
                    'ref_document_type_id' => $this->document_type_id,
                    'ref_document_id' => $dispatch_invoice_id,
                    'ref_document_identity' => $data['document_identity'],
                    'coa_id' => $IncomeTaxAccount_id,
                    'document_debit' => 0,
                    'document_credit' => $value,
                    'debit' => 0,
                    'credit' => $value
                );
            }
            else if($field == "adv_payment")
            {
                $totalDebit = $value;
                $gl_data[] = array(
                    'ref_document_type_id' => $this->document_type_id,
                    'ref_document_id' => $dispatch_invoice_id,
                    'ref_document_identity' => $data['document_identity'],
                    'coa_id' => $advanceAccount,
                    'document_debit' => $value,
                    'document_credit' => 0,
                    'debit' => $value,
                    'credit' => 0
                );
            }

            $this->model['dispatch_invoice_commodity']->add($this->getAlias(), $dataDetail);

        }

        $this->model['dispatch_invoice_detail'] = $this->load->model('vehicle/dispatch_invoice_detail');

        foreach ($data['dispatch_invoice_details'] as $sort_order => $detail) {
            $detail['dispatch_invoice_id'] = $dispatch_invoice_id;
            $detail['sort_order'] = $sort_order;
//            d($sort_order,true);
           $dispatch_invoice_detail_id =  $this->model['dispatch_invoice_detail']->add($this->getAlias(), $detail);
            $totalCredit += $detail['credit'];
            $totalDebit += $detail['debit'];

            $gl_data[] = array(
                'document_detail_id' => $dispatch_invoice_detail_id,
                'ref_document_type_id' => $data['ref_document_type_id'],
                'ref_document_id' => $data['ref_document_id'],
                'ref_document_identity' => $data['ref_document_identity'],
                'coa_id' => $detail['coa_id'],
                'document_debit' => $detail['debit'],
                'document_credit' => $detail['credit'],
                'debit' => $detail['debit'],
                'credit' => $detail['credit'],
            );

        }

        $totalReceivable = $totalCredit - $totalDebit;
        $gl_data[] = array(
            'ref_document_type_id' => $this->document_type_id,
            'ref_document_id' => $dispatch_invoice_id,
            'ref_document_identity' => $data['document_identity'],
            'coa_id' => $credit_account,
            'document_debit' => $totalReceivable,
            'document_credit' => 0,
            'debit' => $totalReceivable,
            'credit' => 0
        );

        $this->model['ledger'] = $this->load->model('gl/ledger');
        //d($gl_data);
        foreach($gl_data as $sort_order => $ledger) {
            $ledger['company_id'] = $this->session->data['company_id'];
            $ledger['company_branch_id'] = $this->session->data['company_branch_id'];
            $ledger['fiscal_year_id'] = $this->session->data['fiscal_year_id'];
            $ledger['document_type_id'] = $this->document_type_id;
            $ledger['document_id'] = $dispatch_invoice_id;
            $ledger['document_identity'] = $data['document_identity'];
            $ledger['document_date'] = $data['document_date'];
            $ledger['sort_order'] = $sort_order;
            $ledger['base_currency_id'] = $data['base_currency_id'];
            $ledger['document_currency_id'] = $data['document_currency_id'];
            $ledger['conversion_rate'] = $data['conversion_rate'];
            $ledger['people_type_id'] = 1;
            $ledger['people_id'] = $data['customer_id'];
            $ledger['remarks'] = '';

            $ledger_id = $this->model['ledger']->add($this->getAlias(), $ledger);
//            d(array($data,$detail,$ledger_id,$ledger),true);
        }


        return $dispatch_invoice_id;
    }

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

    protected function updateData($primary_key, $data) {
        $dispatch_invoice_id = $primary_key;
        $data['document_date'] = MySqlDate($data['document_date']);
        $dispatch_invoice_id = $this->model[$this->getAlias()]->edit($this->getAlias(), $primary_key, $data);
        $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;


        $this->model['customer'] = $this->load->model('setup/customer');
        $supplier = $this->model['customer']->getCustomer($data['customer_id']);
        $credit_account = $supplier['receivable_account_id'];
        $advanceAccount = $supplier['advance_account_id'];

        $sale_tax_account = $this->company->getSaleTaxAccount();
        $this->model['mapping_account'] = $this->load->model('gl/mapping_account');
        $IncometaxAccount = $this->model['mapping_account']->getRow(array('company_id' => $this->session->data['company_id'], 'code' => 'ICT'));
        $IncomeTaxAccount_id = $IncometaxAccount['coa_level3_id'];

        $FrieghtAccount = $this->model['mapping_account']->getRow(array('company_id' => $this->session->data['company_id'], 'code' => 'FR'));
        $FrieghtAccount_id = $FrieghtAccount['coa_level3_id'];

//////////////////////////// Master Ledger Entry /////////////////////////////////////

        $totalDebit = 0;
        $totalCredit = 0;
        $totalReceivable =0;

        $this->model['dispatch_invoice_commodity'] = $this->load->model('vehicle/dispatch_invoice_commodity');
        $this->model['dispatch_invoice_commodity']->deleteBulk($this->getAlias(), array('dispatch_invoice_id' => $dispatch_invoice_id));
        foreach ($data['woc'][$data['commodity']] as $field => $value) {
            $dataDetail = array(
                'dispatch_invoice_id' => $dispatch_invoice_id,
                'field' => $field,
                'value' => $value
            );
            if($field == "freight")
            {
                $totalCredit += $value;
                $gl_data[] = array(
                    'ref_document_type_id' => $this->document_type_id,
                    'ref_document_id' => $dispatch_invoice_id,
                    'ref_document_identity' => $data['document_identity'],
                    'coa_id' => $FrieghtAccount_id,
                    'document_debit' => 0,
                    'document_credit' => $value,
                    'debit' => 0,
                    'credit' => $value
                );
            }
            else if($field == "sales_tax_amount")
            {
                $totalCredit += $value;
                $gl_data[] = array(
                    'ref_document_type_id' => $this->document_type_id,
                    'ref_document_id' => $dispatch_invoice_id,
                    'ref_document_identity' => $data['document_identity'],
                    'coa_id' => $sale_tax_account,
                    'document_debit' => 0,
                    'document_credit' => $value,
                    'debit' => 0,
                    'credit' => $value
                );
            }
            else if($field == "income_tax_amount")
            {
                $totalCredit += $value;
                $gl_data[] = array(
                    'ref_document_type_id' => $this->document_type_id,
                    'ref_document_id' => $dispatch_invoice_id,
                    'ref_document_identity' => $data['document_identity'],
                    'coa_id' => $IncomeTaxAccount_id,
                    'document_debit' => 0,
                    'document_credit' => $value,
                    'debit' => 0,
                    'credit' => $value
                );
            }
            else if($field == "adv_payment")
            {
                $totalDebit = $value;

                $gl_data[] = array(
                    'ref_document_type_id' => $this->document_type_id,
                    'ref_document_id' => $dispatch_invoice_id,
                    'ref_document_identity' => $data['document_identity'],
                    'coa_id' => $advanceAccount,
                    'document_debit' => $value,
                    'document_credit' => 0,
                    'debit' => $value,
                    'credit' => 0
                );
            }
            $this->model['dispatch_invoice_commodity']->add($this->getAlias(), $dataDetail);

        }
        $this->model['dispatch_invoice_detail'] = $this->load->model('vehicle/dispatch_invoice_detail');
        $this->model['dispatch_invoice_detail']->deleteBulk($this->getAlias(), array('dispatch_invoice_id' => $dispatch_invoice_id));

        foreach ($data['dispatch_invoice_details'] as $sort_order => $detail) {
            $detail['dispatch_invoice_id'] = $dispatch_invoice_id;
            $detail['sort_order'] = $sort_order;
//            d($sort_order,true);
            $dispatch_invoice_detail_id =  $this->model['dispatch_invoice_detail']->add($this->getAlias(), $detail);
            $totalCredit += $detail['credit'];
            $totalDebit += $detail['debit'];

            $gl_data[] = array(
                'document_detail_id' => $dispatch_invoice_detail_id,
                'ref_document_type_id' => $data['ref_document_type_id'],
                'ref_document_id' => $data['ref_document_id'],
                'ref_document_identity' => $data['ref_document_identity'],
                'coa_id' => $detail['coa_id'],
                'document_debit' => $detail['debit'],
                'document_credit' => $detail['credit'],
                'debit' => $detail['debit'],
                'credit' => $detail['credit'],
            );
        }

        $totalReceivable = $totalCredit - $totalDebit;
        $gl_data[] = array(
            'ref_document_type_id' => $this->document_type_id,
            'ref_document_id' => $dispatch_invoice_id,
            'ref_document_identity' => $data['document_identity'],
            'coa_id' => $credit_account,
            'document_debit' => $totalReceivable,
            'document_credit' => 0,
            'debit' => $totalReceivable,
            'credit' => 0
        );

        $this->model['ledger'] = $this->load->model('gl/ledger');
        $filter = 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' => $this->document_type_id,
            'document_id' => $dispatch_invoice_id
        );
        $this->model['ledger']->deleteBulk($this->getAlias(),$filter);
        //d($gl_data);
        foreach($gl_data as $sort_order => $ledger) {
            $ledger['company_id'] = $this->session->data['company_id'];
            $ledger['company_branch_id'] = $this->session->data['company_branch_id'];
            $ledger['fiscal_year_id'] = $this->session->data['fiscal_year_id'];
            $ledger['document_type_id'] = $this->document_type_id;
            $ledger['document_id'] = $dispatch_invoice_id;
            $ledger['document_identity'] = $data['document_identity'];
            $ledger['document_date'] = $data['document_date'];
            $ledger['sort_order'] = $sort_order;
            $ledger['base_currency_id'] = $data['base_currency_id'];
            $ledger['document_currency_id'] = $data['document_currency_id'];
            $ledger['conversion_rate'] = $data['conversion_rate'];
            $ledger['people_type_id'] = 2;
            $ledger['people_id'] = $data['customer_id'];
            $ledger['remarks'] = '';

            $ledger_id = $this->model['ledger']->add($this->getAlias(), $ledger);
//            d(array($data,$detail,$ledger_id,$ledger),true);
        }

        return $dispatch_invoice_id;
    }

    protected function updateRedirect($id, $data) {
        $url = $this->getURL();
        $this->redirect($this->url->link($this->getAlias().'/update', 'token=' . $this->session->data['token'] . '&dispatch_invoice_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['dispatch_invoice_commodity'] = $this->load->model('vehicle/dispatch_invoice_commodity');
        $this->model['dispatch_invoice_commodity']->deleteBulk($this->getAlias(),array('dispatch_invoice_id' => $primary_key));
        $this->model['dispatch_invoice_detail'] = $this->load->model('vehicle/dispatch_invoice_detail');
        $this->model['dispatch_invoice_detail']->deleteBulk($this->getAlias(),array('dispatch_invoice_id' => $primary_key));

        $this->model[$this->getAlias()]->delete($this->getAlias(), $primary_key);
        $this->model['ledger'] = $this->load->model('gl/ledger');
        $this->model['ledger']->deleteBulk($this->getAlias(), array('company_id' => $this->session->data['company_id'],'document_type_id' => $this->document_type_id, 'document_id' => $primary_key));

    }

    public function getDocumentNOs() {

        $work_order_id = $this->request->get['work_order_id'];
        $customer_id = $this->request->post['customer_id'];

        $filter = array(
            'company_id' => $this->session->data['company_id'],
            'customer_id' => $customer_id,
        );
        $this->model['work_order'] = $this->load->model('vehicle/work_order');
        $work_orders = $this->model['work_order']->getRows($filter,array('document_identity ASC'));
//        d($work_orders,true);

        $html = '<option value="">&nbsp;</option>';
        foreach($work_orders as $work_order) {
            $html .= '<option value="' . $work_order['work_order_id'] . '" '.($work_order_id == $work_order['work_order_id']?'selected="true"':'').'>'.$work_order['document_identity'].'</option>';
        }
        echo json_encode(array('success' => true, 'html' => $html));

    }

    public function getDocumentData() {

        $work_order_id = $this->request->post['ref_document_id'];
//        d($work_order_id,true);


        $this->model['work_order'] = $this->load->model('vehicle/work_order');
        $data = $this->model['work_order']->getRow(array('document_identity' => $work_order_id));

        $this->model['work_order_commodity'] = $this->load->model('vehicle/work_order_commodity');
        $dataDetails = $this->model['work_order_commodity']->getRows(array('work_order_id' => $data['work_order_id']));

        foreach($dataDetails as $dataDeatil)
        {
            $data['details'][$dataDeatil['field']] = $dataDeatil['value'];
        }
//        d($data,true);
        $json = array(
            'success' => true,
            'data' => $data,

        );
//        d($json,true);
        $this->response->setOutput(json_encode($json));

    }


}
?>