<?php

class ControllerGlDocumentSettlement extends HController {

    protected $document_type_id = 38;

    protected function getAlias() {
        return 'gl/document_settlement';
    }

    protected function getPrimaryKey() {
        return 'document_settlement_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('gl/document_settlement');
        $this->model[$this->getAlias()] = $this->load->model($this->getAlias());

        $data = array();
        $aColumns = array('action','document_date', 'document_identity' ,'partner_type','partner_name', 'remarks','created_at', 'check_box');

        /*
         * 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
         */
        $arrWhere = array();
        $arrWhere[] = "`company_id` = '".$this->session->data['company_id']."'";
        $arrWhere[] = "`company_branch_id` = '".$this->session->data['company_branch_id']."'";
        if (isset($_GET['sSearch']) && $_GET['sSearch'] != "") {
            $arrSSearch = array();
            for ($i = 0; $i < count($aColumns); $i++) {
                if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true" && $_GET['sSearch'] != '') {
                    $arrSSearch[] = "LOWER(`" . $aColumns[$i] . "`) LIKE '%" . $this->db->escape(strtolower($_GET['sSearch'])) . "%'";
                }
            }
            if(!empty($arrSSearch)) {
                $arrWhere[] = '(' . implode(' OR ', $arrSSearch) . ')';
            }
        }

        /* Individual column filtering */
        for ($i = 0; $i < count($aColumns); $i++) {
            if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true" && $_GET['sSearch_' . $i] != '') {
                $arrWhere[] = "LOWER(`" . $aColumns[$i] . "`) LIKE '%" . $this->db->escape(strtolower($_GET['sSearch_' . $i])) . "%' ";
            }
        }

        if (!empty($arrWhere)) {
            //$data['filter']['RAW'] = substr($sWhere, 5, strlen($sWhere) - 5);
            $data['filter']['RAW'] = implode(' AND ', $arrWhere);
        }

        //d($data, true);
        $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' => $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'
            );

            $actions[] = array(
                'text' => $lang['print'],
                'target' => '_blank',
                'href' => $this->url->link($this->getAlias() . '/printDocument', 'token=' . $this->session->data['token'] . '&' . $this->getPrimaryKey() . '=' . $aRow[$this->getPrimaryKey()], 'SSL'),
                'btn_class' => 'btn btn-info btn-xs',
                'class' => 'fa fa-print'
            );

            if($aRow['is_post']==0) {
                $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'
                );

                $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'
                );
            }

            $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] == 'created_at') {
                    $row[] = stdDateTime($aRow['created_at']);
                } elseif ($aColumns[$i] == 'document_date') {
                    $row[] = stdDate($aRow['document_date']);
                } elseif ($aColumns[$i] == 'check_box') {
                    $row[] = '<input type="checkbox" name="selected[]" value="' . $aRow[$this->getPrimaryKey()] . '" />';
                } else {
                    $row[] = $aRow[$aColumns[$i]];
                }

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

        echo json_encode($output);
    }

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

        $this->data['document_identity'] = $this->data['lang']['auto'];
        $this->data['document_date'] = stdDate();
        $this->data['base_currency_id'] = $this->session->data['base_currency_id'];
        $this->data['base_currency'] = $this->session->data['base_currency_name'];
        $this->data['document_currency_id'] = $this->session->data['base_currency_id'];
        $this->data['conversion_rate'] = "1.00";

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

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

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

        if (isset($this->request->get['document_settlement_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
            $this->data['isEdit'] = 1;
            $this->data['document_type_id'] = $this->document_type_id;
            $this->data['document_id'] = $this->request->get['document_settlement_id'];

            $result = $this->model[$this->getAlias()]->getRow(array('document_settlement_id' => $this->request->get['document_settlement_id']));
            foreach ($result as $field => $value) {
                if ($field == 'document_date') {
                    $this->data[$field] = stdDate($value);
                } else {
                    $this->data[$field] = $value;
                }
            }

            $this->model['document'] = $this->load->model('common/document');
            $this->model['document_settlement_detail'] = $this->load->model('gl/document_settlement_detail');
            $filter = array(
                'document_settlement_id' => $this->request->get['document_settlement_id']
            );
            $details = $this->model['document_settlement_detail']->getRows($filter,array('sort_order DESC'));
            foreach($details as $detail) {
                $row_id = $detail['sort_order'];
                if(empty($detail['cheque_date']) || $detail['cheque_date']=='0000-00-00') {
                    $detail['cheque_date'] = '';
                } else {
                    $detail['cheque_date'] = stdDate($detail['cheque_date']);
                }
                if($detail['ref_document_type_id'] && $detail['ref_document_identity']) {
                    $ref_document = $this->model['document']->getRow(array('document_type_id' => $detail['ref_document_type_id'], 'document_identity' => $detail['ref_document_identity']));
                    $detail['href'] = $this->url->link($ref_document['route'].'/update', 'token=' . $this->session->data['token'] . '&' . $ref_document['primary_key_field'] . '=' . $ref_document['primary_key_value'], 'SSL');
                }
                $this->data['document_settlement_details'][$row_id] = $detail;
            }

            $this->model['partner'] = $this->load->model('common/partner');
            $this->data['partners'] = $this->model['partner']->getPartners(array('company_id' => $this->session->data['company_id'], 'partner_type_id' => $result['partner_type_id']));
        }

        $this->data['href_get_document_ledger'] = $this->url->link('common/function/getDocumentLedger', 'token=' . $this->session->data['token'] . '&' . $this->getPrimaryKey() . '=' . $this->request->get[$this->getPrimaryKey()], 'SSL');
        $this->data['href_get_partner'] = $this->url->link($this->getAlias() . '/getPartner', 'token=' . $this->session->data['token']);
        $this->data['href_get_documents'] = $this->url->link($this->getAlias() . '/getDocuments', 'token=' . $this->session->data['token']);
        $this->data['href_get_document_data'] = $this->url->link($this->getAlias() . '/getDocumentData', 'token=' . $this->session->data['token']);
        $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_un_post'] = $this->url->link($this->getAlias() . '/Unpost', '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/function/validateDate', 'token=' . $this->session->data['token']);
        $this->data['strValidation'] = "{
            'rules': {
                'document_date': {'required': true, 'remote':  {url: '" . $this->data['action_validate_date'] . "', type: 'post'}},
                'transaction_account_id': {'required': true},
                'amount': {'required': true},
            },
            ignore:[],
        }";

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

    public function getPartner() {
        $partner_type_id = $this->request->post['partner_type_id'];
        $partner_id = $this->request->post['partner_id'];
        $this->model['partner'] = $this->load->model('common/partner');
        $partners = $this->model['partner']->getPartners(array('company_id'=>$this->session->data['company_id'], 'partner_type_id' => $partner_type_id));

        $html = '<option value="">&nbsp;</option>';
        foreach($partners as $partner) {
            $html .= '<option data-wht_tax="'.$partner['wht_tax'].'" data-other_tax="'.$partner['other_tax'].'" value="'.$partner['partner_id'].'" '.($partner['partner_id']==$partner_id?'selected="true"':'').'>'.$partner['name'].'</option>';
        }

        $json = array(
            'success' => true,
            'html' => $html
        );

        echo json_encode($json);
    }

    public function getDocuments() {
        $partner_type_id = $this->request->post['partner_type_id'];
        $partner_id = $this->request->post['partner_id'];
        $this->model['document'] = $this->load->model('common/document');
        $this->model['partner'] = $this->load->model('common/partner');

        $partner = $this->model['partner']->getRow(array('partner_type_id' => $partner_type_id, 'partner_id' => $partner_id));

        $COAS = array();
        $COAS[$partner['outstanding_account_id']] = array(
            'coa_id' => $partner['outstanding_account_id'],
            'level4_display_name' => $partner['outstanding_account']
        );
//        $COAS[$partner['cash_account_id']] = array(
//            'coa_level3_id' => $partner['cash_account_id'],
//            'level3_display_name' => $partner['cash_account']
//        );
        $COAS[$partner['advance_account_id']] = array(
            'coa_id' => $partner['advance_account_id'],
            'level4_display_name' => $partner['advance_account']
        );


        $where = "`partner_type_id` = '".$partner_type_id."' AND `partner_id` = '".$partner_id."' and company_branch_id = '".$this->session->data['company_branch_id']."' and outstanding_amount > 0 ";
        $where .= " AND is_post=1 AND company_branch_id = '".$this->session->data['company_branch_id']."' AND company_id = '".$this->session->data['company_id']."'";
        $documents = $this->model['document']->getOutstandingDocuments($where);


        $arrDocuments = array();
        $html = '<option value="">&nbsp;</option>';
        foreach($documents as $document) {
            $model_document_actual = $this->load->model($document['route']);
            $row = $model_document_actual->getRow(array($document['primary_key_field'] => $document['primary_key_value']));
            $document['document_tax'] = $row['item_tax'];
            $arrDocuments[$document['ref_document_identity']] = $document;
            $arrDocuments[$document['ref_document_identity']]['href'] = $this->url->link($document['route'] . '/update', 'token=' . $this->session->data['token'] . '&' . $document['primary_key_field'] . '=' . $document['primary_key_value'], 'SSL');

            $html .= '<option value="'.$document['ref_document_identity'].'">'.$document['ref_document_identity'].'</option>';
        }
//        d(array($partner_id,$documents,$html,$arrDocuments),true);


        $json = array(
            'success' => true,
            'html' => $html,
            'documents' => $arrDocuments,
            'partner_coas' => $COAS,
        );

        // d($json,true);

        echo json_encode($json);
    }

    protected function insertData($data) {
        $this->model['document_type'] = $this->load->model('common/document_type');
        $this->model['document'] = $this->load->model('common/document');
        $this->model['document_settlement_detail'] = $this->load->model('gl/document_settlement_detail');
        $this->model['ledger'] = $this->load->model('gl/ledger');

        $document = $this->model['document_type']->getNextDocument($this->document_type_id);

        $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['document_identity'];
        $data['document_date'] = MySqlDate($data['document_date']);
        $data['base_total_debit'] = $data['total_debit'] * $data['conversion_rate'];
        $data['base_total_credit'] = $data['total_credit'] * $data['conversion_rate'];

        $document_settlement_id = $this->model[$this->getAlias()]->add($this->getAlias(), $data);
        $data['document_id'] = $document_settlement_id;

        $insert_document = 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' => $data['document_id'],
            'document_identity' => $data['document_identity'],
            'document_date' => $data['document_date'],
            'partner_type_id' => $data['partner_type_id'],
            'partner_id' => $data['partner_id'],
            'document_currency_id' => $data['document_currency_id'],
            'document_amount' => $data['total_debit'],
            'conversion_rate' => $data['conversion_rate'],
            'base_currency_id' => $data['base_currency_id'],
            'base_amount' => $data['base_total_debit'],
        );
        $document_id = $this->model['document']->add($this->getAlias(), $insert_document);


        //d($data['document_settlement_details'], true);
        foreach ($data['document_settlement_details'] as $sort_order => $detail) {
            $detail['document_settlement_id'] = $document_settlement_id;
            $detail['sort_order'] = $sort_order;
            $detail['company_id'] = $this->session->data['company_id'];
            $detail['company_branch_id'] = $this->session->data['company_branch_id'];
            $detail['fiscal_year_id'] = $this->session->data['fiscal_year_id'];
            $detail['document_currency_id'] = $data['document_currency_id'];
            $detail['base_currency_id'] = $data['base_currency_id'];
            $detail['conversion_rate'] = $data['conversion_rate'];
            $detail['base_debit'] = $detail['debit'] * $data['conversion_rate'];
            $detail['base_credit'] = $detail['credit'] * $data['conversion_rate'];

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

            $gl_data[] = array(
                'document_detail_id' => $document_settlement_detail_id,
                'coa_id' => $detail['coa_id'],
                'document_currency_id' => $data['document_currency_id'],
                'document_debit' => $detail['debit'],
                'document_credit' => $detail['credit'],
                'base_currency_id' => $data['base_currency_id'],
                'conversion_rate' => $data['conversion_rate'],
                'debit' => $detail['debit'] * $data['conversion_rate'],
                'credit' => $detail['credit'] * $data['conversion_rate'],
                'partner_type_id' => $data['partner_type_id'],
                'partner_id' => $data['partner_id'],
                'ref_document_type_id' => $detail['ref_document_type_id'],
                'ref_document_identity' => $detail['ref_document_identity'],
                'remarks' => $detail['remarks'],
            );

        }

        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'] = $data['document_id'];
            $ledger['document_identity'] = $data['document_identity'];
            $ledger['document_date'] = $data['document_date'];

            $ledger_id = $this->model['ledger']->add($this->getAlias(), $ledger);
        }

        return $document_settlement_id;
    }

    protected function updateData($primary_key, $data) {
        $this->model['document_type'] = $this->load->model('common/document_type');
        $this->model['document'] = $this->load->model('common/document');

        $this->model['document_settlement_detail'] = $this->load->model('gl/document_settlement_detail');
        $this->model['ledger'] = $this->load->model('gl/ledger');

        $this->model['document']->delete($this->getAlias(), $primary_key);
        $this->model['document_settlement_detail']->deleteBulk($this->getAlias(), array('document_settlement_id' => $primary_key));
        $this->model['ledger']->deleteBulk($this->getAlias(), array('document_id' => $primary_key));

        $data['document_date'] = MySqlDate($data['document_date']);
        $data['base_total_debit'] = $data['total_debit'] * $data['conversion_rate'];
        $data['base_total_credit'] = $data['total_credit'] * $data['conversion_rate'];

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

        $insert_document = 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' => $data['document_id'],
            'document_identity' => $data['document_identity'],
            'document_date' => $data['document_date'],
            'partner_type_id' => $data['partner_type_id'],
            'partner_id' => $data['partner_id'],
            'document_currency_id' => $data['document_currency_id'],
            'document_amount' => $data['total_debit'],
            'conversion_rate' => $data['conversion_rate'],
            'base_currency_id' => $data['base_currency_id'],
            'base_amount' => $data['base_total_debit'],
        );
        $document_id = $this->model['document']->add($this->getAlias(), $insert_document);


        foreach ($data['document_settlement_details'] as $sort_order => $detail) {
            $detail['document_settlement_id'] = $document_settlement_id;
            $detail['sort_order'] = $sort_order;
            $detail['company_id'] = $this->session->data['company_id'];
            $detail['company_branch_id'] = $this->session->data['company_branch_id'];
            $detail['fiscal_year_id'] = $this->session->data['fiscal_year_id'];
            $detail['document_currency_id'] = $data['document_currency_id'];
            $detail['base_currency_id'] = $data['base_currency_id'];
            $detail['conversion_rate'] = $data['conversion_rate'];
            $detail['base_debit'] = $detail['debit'] * $data['conversion_rate'];
            $detail['base_credit'] = $detail['credit'] * $data['conversion_rate'];

            $document_settlement_detail_id =  $this->model['document_settlement_detail']->add($this->getAlias(), $detail);
            $gl_data[] = array(
                'document_detail_id' => $document_settlement_detail_id,
                'coa_id' => $detail['coa_id'],
                'document_currency_id' => $data['document_currency_id'],
                'document_debit' => $detail['debit'],
                'document_credit' => $detail['credit'],
                'base_currency_id' => $data['base_currency_id'],
                'conversion_rate' => $data['conversion_rate'],
                'debit' => $detail['debit'] * $data['conversion_rate'],
                'credit' => $detail['credit'] * $data['conversion_rate'],
                'partner_type_id' => $data['partner_type_id'],
                'partner_id' => $data['partner_id'],
                'ref_document_type_id' => $detail['ref_document_type_id'],
                'ref_document_identity' => $detail['ref_document_identity'],
                'remarks' => $detail['remarks'],
            );
        }
        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'] = $data['document_id'];
            $ledger['document_identity'] = $data['document_identity'];
            $ledger['document_date'] = $data['document_date'];

            $ledger_id = $this->model['ledger']->add($this->getAlias(), $ledger);
        }
        return $document_settlement_id;
    }

    protected function deleteData($primary_key) {
        $this->model['document'] = $this->load->model('common/document');
        $this->model['document_settlement_detail'] = $this->load->model('gl/document_settlement_detail');
        $this->model['ledger'] = $this->load->model('gl/ledger');

        $this->model['ledger']->deleteBulk($this->getAlias(), array('document_id' => $primary_key));
        $this->model['document_settlement_detail']->deleteBulk($this->getAlias(), array('document_settlement_id' => $primary_key));
        $this->model['document']->delete($this->getAlias(), $primary_key);
        $this->model[$this->getAlias()]->delete($this->getAlias(), $primary_key);

    }

    public function Unpost() {

        $lang = $this->load->language($this->getAlias());
        $data = array(
            'is_post' => 0,
            'post_date' => date('Y-m-d H:i:s'),
            'post_by_id' => $this->session->data['user_id']
        );
        $this->model[$this->getAlias()] = $this->load->model($this->getAlias());
        $this->model[$this->getAlias()]->edit($this->getAlias(),$this->request->get[$this->getPrimaryKey()],$data);

        $this->model['document'] = $this->load->model('common/document');
        $this->model['document']->edit($this->getAlias(),$this->request->get[$this->getPrimaryKey()],$data);

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


    public function ajaxValidateForm() {
        $post  = $this->request->post;
        $ID = $this->request->get;
//        d($ID,true);
//       d($post,true);
        $lang = $this->load->language($this->getAlias());
        $error = array();

        if($post['voucher_date'] == '') {
            $error[] = $lang['error_voucher_date'];
        }
        if($post['transaction_account_id'] == '') {
            $error[] = $lang['error_transaction_account'];
        }
        if($post['document_currency_id'] == '') {
            $error[] = $lang['error_document_currency'];
        }
        if($post['conversion_rate'] == '' || $post['conversion_rate'] <= 0 ) {
            $error[] = $lang['error_conversion_rate'];
        }

        $conversation = $post['conversion_rate'];
        $details = $post['document_settlement_details'];
        //d($details,true);
        if($post['people_id'] && $post['people_id'] != "") {
            $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'],
                'people_type_id' => $post['people_type_id'],
                'people_id' => $post['people_id'],
            );

            $this->model['ledger'] = $this->load->model('gl/ledger');

            $Amount =array();
            foreach($details as $stock){
                if(isset($Amount[$stock['ref_document_identity']])) {
                    $Amount[$stock['ref_document_identity']] += $stock['amount'];
                } else
                {
                    $Amount[$stock['ref_document_identity']] = $stock['amount'];
                }
            }

            foreach($Amount as  $ref_document_id => $amount)
            {

                $filter ['ref_document_id'] = $ref_document_id;
                $filter ['document_id'] = $ID['document_settlement_id'];

                $outstanding = $this->model['ledger']->getDocumentOutstanding($filter);
                if($outstanding['outstanding'] < $amount * $conversation)
                {
                    $error[] =  $lang['error_amounts'] ;
                    $error[] =   ' Ref Document No= ' . $ref_document_id .' , Invoice Amount= ' . $outstanding['outstanding'] . ' , Pay Amount= '. $amount * $conversation;
                }
            }

        }

        if(empty($details)) {
            $error[] = $lang['error_input_detail'];
        } else {
            $row_no = 0;
            foreach($details as $detail) {
                $row_no++;

                if($detail['coa_id'] == '') {
                    $error[] = $lang['error_coa_id'] . ' for Row ' . $row_no;
                }

                if($detail['amount'] == '') {
                    $error[] = $lang['error_amount'] . ' for Row ' . $row_no;
                }
            }

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

            echo json_encode($json);
            exit;

        }
    }

    public function printDocument() {
        ini_set('max_execution_time',0);
        ini_set('memory_limit',-1);

        $lang = $this->load->language($this->getAlias());
        $post = $this->request->post;
        $session = $this->session->data;
        $document_settlement_id = $this->request->get['document_settlement_id'];

        $this->model['partner'] = $this->load->model('common/partner');
        $this->model['document_settlement'] = $this->load->model('gl/document_settlement');
        $this->model['document_settlement_detail'] = $this->load->model('gl/document_settlement_detail');
        $this->model['document_settlement'] = $this->load->model('gl/document_settlement');


        $voucher = $this->model['document_settlement']->getRow(array('document_settlement_id' => $document_settlement_id));
        $details = $this->model['document_settlement_detail']->getRows(array('document_settlement_id' => $document_settlement_id));

        $this->model['ledger'] = $this->load->model('gl/ledger');
        $LedgerDetails = $this->model['ledger']->getTransactionLedger(38,$document_settlement_id);

//        d($LedgerDetails,true);


        $pdf = new PDF('P', PDF_UNIT, 'A4', true, 'UTF-8', false);

        // set document information
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('Huzaifa Khambaty');
        $pdf->SetTitle('Document Settlement');
        $pdf->SetSubject('Document Settlement');

        //Set Header
        $pdf->data = array(
            'company_name' => $session['company_name'],
            //'report_name' => $lang['heading_title'],
            'report_name' => 'Document Settlement',
            'company_logo' => $session['company_image'],
            'remarks' => $voucher['remarks'],
            'document_identity' => $voucher['document_identity'],
            'dc_no' => $voucher['dc_no'],
            'document_date' => $voucher['document_date'],
            'partner_name' => $voucher['partner_name'],
            'remarks' => $voucher['remarks'],
            'ref_identity' => $voucher['ref_document_identity'],
            'ref_id' => $voucher['ref_document_type_id'],
            'ledger_details' => $LedgerDetails

        );

        // set margins
        //$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetMargins(15, 36, 5);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        // set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, 40);

        // add a page
        $pdf->AddPage();
        // set font

        $pdf->SetFont('times', 'B', 9);
        $pdf->Cell(130, 6, 'Remarks: ', 0, false, 'L', 0, '', 0, false, 'M', 'M');
        // set font

        $pdf->SetFont('times', 'B', 9);
        $pdf->Cell(20, 6, 'Voucher No: ', 0, false, 'R', 0, '', 0, false, 'M', 'M');
        // set font
        $pdf->SetFont('times', '', 9);
        $pdf->Cell(40, 6, $voucher['document_identity'], 0, false, 'L', 0, '', 0, false, 'M', 'M');
        // set font
        $pdf->ln(6);

        $pdf->SetFont('times', 'B', 9);
        $pdf->Cell(153, 6, 'Voucher Date: ', 0, false, 'R', 0, '', 0, false, 'M', 'M');
        // set font
        $pdf->SetFont('times', '', 9);
        $pdf->Cell(20, 6, stdDate($voucher['document_date']), 0, false, 'L', 0, '', 0, false, 'M', 'M');

        $pdf->SetFont('times', '', 9);
        $pdf->SetFillColor(255,255,255);
        $pdf->MultiCell(125, 8, html_entity_decode($voucher['remarks']), 0, 'L', 1, 2, 16, 39, true);
        $pdf->ln(7);

        $pdf->SetFont('times', '', 8);
        $pdf->SetFillColor(255, 255, 255);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->Cell(25, 7, 'Code.', 'T,B', false, 'C', 1, '', 1);
        $pdf->Cell(80, 7, 'Accounts Description', 'T,B', false, 'C', 1, '', 1);
        $pdf->Cell(35, 7, 'Cheque No', 'T,B', false, 'C', 1, '', 1);
        $pdf->Cell(25, 7, 'Debit', 'T,B', false, 'C', 1, '', 1);
        $pdf->Cell(25, 7, 'Credit', 'T,B', false, 'C', 1, '', 1);

        $pdf->SetFont('times', '', 8);
        $pdf->SetFillColor(255, 255, 255);
        $pdf->SetTextColor(0, 0, 0);
        $total_debit = 0;
        $total_credit = 0;
        foreach($LedgerDetails as $LedgerDetail) {
            $pdf->ln(6);

            $pdf->Cell(25, 6, $LedgerDetail['account_code'], 0, false, 'L', 0, '', 1);
            $pdf->Cell(80, 6, html_entity_decode($LedgerDetail['level4_name']), 0, false, 'L', 0, '', 1);
            $pdf->Cell(35, 6, html_entity_decode($LedgerDetail['cheque_no']), 0, false, 'L', 0, '', 1);
            $pdf->Cell(25, 6, number_format($LedgerDetail['debit'],4), 0, false, 'R', 0, '', 1);
            $pdf->Cell(25, 6, number_format($LedgerDetail['credit'],2), 0, false, 'R', 0, '', 1);

            $total_debit += $LedgerDetail['debit'];
            $total_credit += $LedgerDetail['credit'];
        }
        $pdf->ln(4);

        $x = $pdf->GetX();
        $y = $pdf->GetY();
        $pdf->setXY($x,$y);
        $pdf->SetFont('times', 'B', 9);

        $pdf->Ln(7);
        $pdf->Cell(140, 7, '', 0, false, 'R', 0, '', 0, false, 'M', 'M');
        $pdf->Cell(25, 7, number_format($total_debit,2), 'T,B', false, 'R', 0, '', 0, false, 'M', 'M');
        $pdf->Cell(25, 7, number_format($total_credit,2), 'T,B', false, 'R', 0, '', 0, false, 'M', 'M');

        $pdf->AddPage();

        if(count($details) > 0)
        {
            $pdf->setPage(2);
        }


//        $pdf->SetFont('times', 'B', 10);
//        $pdf->SetFillColor(215, 215, 215);
//        $pdf->SetTextColor(0, 0, 0);
//        $pdf->Cell(190, 6, 'Voucher Detail', 0, false, 'C', 1, '', 1);

//        $pdf->ln(10);
//
//        $pdf->SetFont('times', 'B', 9);
//        $pdf->Cell(12, 7, 'Po No:  ', 0, false, 'L', 0, '', 0, false, 'M', 'M');
//        // set font
//        $pdf->SetFont('times', '', 9);
//        if($pdf->data['ref_id'] == '4')
//        {
//            $pdf->Cell(70, 7, $pdf->data['ref_identity'], 'B', false, 'L', 0, '', 0, false, 'M', 'M');
//        }
//        else{
//            $pdf->Cell(70, 7, '', 'B', false, 'C', 0, '', 0, false, 'M', 'M');
//
//        }
//        // set font
//        $pdf->SetFont('times', 'B', 9);
//        $pdf->Cell(15, 7, 'Bilty No: ', 0, false, 'R', 0, '', 0, false, 'M', 'M');
//        // set font
//        $pdf->SetFont('times', '', 9);
//        $pdf->Cell(33, 7, $pdf->data['bilty_no'], 'B', false, 'C', 0, '', 0, false, 'M', 'M');
//
//        $pdf->SetFont('times', 'B', 9);
//        $pdf->Cell(15, 7, 'Bilty Date: ', 0, false, 'R', 0, '', 0, false, 'M', 'M');
//        // set font
//        $pdf->SetFont('times', '', 9);
//
//        $BiltyDate = $pdf->data['bilty_date'];
//        if($BiltyDate == '' && $BiltyDate =='0000-00-00')
//        {
//            $BiltyDate = '';
//        }
//        else
//        {
//            $BiltyDate = stdDate($BiltyDate);
//        }
//
//        $pdf->Cell(33, 7, stdDate($BiltyDate), 'B', false, 'C', 0, '', 0, false, 'M', 'M');
//
//        $pdf->ln(8);
//        $pdf->SetFont('times', 'B', 9);
//        $pdf->Cell(17, 6, 'Supplier: ', 0, false, 'L', 0, '', 0, false, 'M', 'M');
//        // set font
//        $pdf->SetFont('times', '', 9);
//        $pdf->Cell(140, 6, $pdf->data['partner_name'], 'B', false, 'L', 0, '', 0, false, 'M', 'M');
//        // set font
//
//        $pdf->ln(8);
        $pdf->SetFont('times', '', 7);
//        $pdf->SetFillColor(215, 215, 215);
//        $pdf->SetTextColor(0, 0, 0);
//        $pdf->Cell(22, 8, 'Ref Doc Nos.', 1, false, 'C', 1, '', 1);
//        $pdf->Cell(20, 8, 'Product Code.', 1, false, 'C', 1, '', 1);
//        $pdf->Cell(70, 8, 'Product Name', 1, false, 'C', 1, '', 1);
//        $pdf->Cell(15, 8, 'Unit', 1, false, 'C', 1, '', 1);
//        $pdf->Cell(19, 8, 'Quantity', 1, false, 'C', 1, '', 1);
//        $pdf->Cell(19, 8, 'Net Rate', 1, false, 'C', 1, '', 1);
//        $pdf->Cell(24, 8, 'Amount', 1, false, 'C', 1, '', 1);

        $pdf->SetFillColor(255, 255, 255);
        $pdf->SetTextColor(0, 0, 0);
        $total_detail_debit = 0;
        $total_detail_credit = 0;

        $pdf->ln(13);
        foreach($details as $detail) {
            $pdf->ln(8);
            $pdf->Cell(30, 7, $detail['ref_document_identity'], 0, false, 'C', 0, '', 1);
            $pdf->Cell(80, 7, $detail['remarks'], 0, false, 'C', 0, '', 1);
            $pdf->Cell(20, 7, number_format($detail['document_amount']), 0, false, 'R', 0, '', 1);
            $pdf->Cell(20, 7, number_format($detail['balance_amount']), 0, false, 'R', 0, '', 1);
            $pdf->Cell(20, 7, number_format($detail['debit']), 0, false, 'R', 0, '', 1);
            $pdf->Cell(20, 7, number_format($detail['credit'],4), 0, false, 'R', 0, '', 1);

            $total_detail_debit += $detail['debit'];
            $total_detail_credit += $detail['credit'];
        }
        $pdf->ln(2);


        $pdf->SetFont('times', '', 7);


        $pdf->Ln(10);
        $pdf->Cell(150, 7, '', 0, false, 'R', 0, '', 0, false, 'M', 'M');
        $pdf->Cell(20, 7, number_format($total_detail_debit,2), 'T,B', false, 'R', 0, '', 0, false, 'M', 'M');
        $pdf->Cell(1, 7, '', 0, false, 'R', 0, '', 0, false, 'M', 'M');
        $pdf->Cell(20, 7, number_format($total_detail_credit,2), 'T,B', false, 'R', 0, '', 0, false, 'M', 'M');

        //Close and output PDF document
        $pdf->Output('Document Settlement - '.$voucher['document_identity'].'.pdf', 'I');

    }
}
class PDF extends TCPDF {
    public $data = array();

    //Page header
    public function Header() {
        // Logo
        /*
        if($this->data['company_logo'] != '') {
            $image_file = DIR_IMAGE.$this->data['company_logo'];
            //$this->Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false, $hidden=false, $fitonpage=false);
            //$this->Image($image_file, 10, 5, 150, '', '', '', 'C', false, 300, '', false, false, 1, false, false, false);
            $x = 15;
            $y = 0;
            $w = 180;
            $h = 40;
            //$this->Rect($x, $y, $w, $h, 'F', array(), array(128,255,128));
            $this->Image($image_file, $x, $y, $w, $h, '', '', '', false, 300, '', false, false, 0, 'LM', false, false);
        }
        */
        // Set font

        if ($this->page == 1) {
            $this->SetFont('helvetica', 'B', 20);
            $this->Ln(2);
            // Title
            $this->Cell(0, 10, $this->data['company_name'], 0, false, 'C', 0, '', 0, false, 'M', 'M');
            $this->Ln(10);

            $this->SetFont('helvetica', '', 16);
            $this->Cell(0, 8, $this->data['report_name'], 0, false, 'C', 0, '', 0, false, 'M', 'M');
            $this->Ln(10);

        } else {

            $this->SetFont('helvetica', 'B', 20);
            $this->Ln(2);
            // Title
            $this->Cell(0, 10, $this->data['company_name'], 0, false, 'C', 0, '', 0, false, 'M', 'M');
            $this->Ln(10);

            $this->SetFont('helvetica', '', 16);
            $this->Cell(0, 8, $this->data['report_name'], 0, false, 'C', 0, '', 0, false, 'M', 'M');
            $this->Ln(10);

            $this->SetFont('times', 'B', 10);
            $this->SetFillColor(215, 215, 215);
            $this->SetTextColor(0, 0, 0);
            $this->Cell(190, 6, 'Voucher Detail', 0, false, 'C', 1, '', 1);

            $this->ln(12);
            $this->SetFont('times', 'B', 9);
            $this->Cell(17, 6, 'Supplier: ', 0, false, 'L', 0, '', 0, false, 'M', 'M');
            // set font
            $this->SetFont('times', '', 9);
            $this->Cell(140, 6, html_entity_decode($this->data['partner_name']), 'B', false, 'L', 0, '', 0, false, 'M', 'M');
            // set font

            $this->ln(10);
            $this->SetFont('times', '', 7);
            $this->SetFillColor(255, 255, 255);
//            $this->SetTextColor(0, 0, 0);
            $this->Cell(30, 8, 'PV Number.', 'T,B', false, 'C', 1, '', 1);
            $this->Cell(80, 8, 'Remarks', 'T,B', false, 'C', 1, '', 1);
            $this->Cell(20, 8, 'Document Amt', 'T,B', false, 'C', 1, '', 1);
            $this->Cell(20, 8, 'Balance Amt', 'T,B', false, 'C', 1, '', 1);
            $this->Cell(20, 8, 'Debit', 'T,B', false, 'C', 1, '', 1);
            $this->Cell(20, 8, 'Credit', 'T,B', false, 'C', 1, '', 1);
        }

    }

    // Page footer
    public function Footer() {
        // Position at 15 mm from bottom
        $this->SetY(-30);
        // Set font
        $this->SetFont('helvetica', 'B', 8);
        // Page number
        //      $this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
        $this->Cell(180, 4, '', 'B', false, 'L', 0, '', 0, false, 'M', 'M');
        $this->Ln(10);
        $this->Ln(5);
        $this->Cell(30, 7, 'Prepared By', 'T', false, 'C', 0, '', 0, false, 'M', 'M');
        $this->Cell(10, 7, '', 0, false, 'C', 0, '', 0, false, 'M', 'M');
        $this->Cell(30, 7, 'Checked By', 'T', false, 'C', 0, '', 0, false, 'M', 'M');
        $this->Cell(10, 7, '', 0, false, 'C', 0, '', 0, false, 'M', 'M');
        $this->Cell(30, 7, 'Approved By', 'T', false, 'C', 0, '', 0, false, 'M', 'M');
//        $this->Cell(10, 7, '', 0, false, 'C', 0, '', 0, false, 'M', 'M');
//        $this->Cell(40, 7, 'Vice President Ind.Division', 'T', false, 'C', 0, '', 0, false, 'M', 'M');
        $this->Ln(7);
        $this->Cell(0, 5, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
    }
}
?>