<?php

class ControllerInventoryPurchaseInvoice extends HController {

    protected $document_type_id = 1;

    protected function getAlias() {
        return 'inventory/purchase_invoice';
    }

    protected function getPrimaryKey() {
        return 'purchase_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($this->getAlias());
        $this->model[$this->getAlias()] = $this->load->model($this->getAlias());
        $data = array();
        $aColumns = array('action', 'document_date', 'document_identity', 'partner_type','partner_name','remarks', 'item_amount', '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']."'";
        $arrWhere[] = "`fiscal_year_id` = '".$this->session->data['fiscal_year_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] == 'document_date') {
                    $row[] = stdDate($aRow['document_date']);
                } elseif ($aColumns[$i] == 'created_at') {
                    $row[] = stdDateTime($aRow['created_at']);
                } elseif ($aColumns[$i] == 'check_box') {
                    if($aRow['is_post']==0) {
                        $row[] = '<input type="checkbox" name="selected[]" value="' . $aRow[$this->getPrimaryKey()] . '" />';
                    } else {
                        $row[] = '';
                    }
                } else {
                    $row[] = $aRow[$aColumns[$i]];
                }

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

        echo json_encode($output);
    }

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

//        $this->model['product'] = $this->load->model('inventory/product');
//        $this->data['products'] = $this->model['product']->getRows(array('company_id' => $this->session->data['company_id']));

        $this->model['currency'] = $this->load->model('setup/currency');
        $this->data['currencys'] = $this->model['currency']->getRows();

        $this->model['unit'] = $this->load->model('inventory/unit');
        $this->data['units'] = $this->model['unit']->getRows(array('company_id' => $this->session->data['company_id']));

        $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->data['arrWarehouses'] = json_encode($this->data['warehouses']);

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

        $this->model['inventory_expense'] = $this->load->model('inventory/expense');
        $this->data['inventory_expenses'] = $this->model['inventory_expense']->getRows(array('company_id' => $this->session->data['company_id']),array('name'));

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

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

        $this->data['document_date'] = stdDate();
        if (isset($this->request->get['purchase_invoice_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
            $this->data['isEdit'] = 1;
            $result = $this->model[$this->getAlias()]->getRow(array('purchase_invoice_id' => $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['purchase_invoice_detail'] = $this->load->model('inventory/purchase_invoice_detail');
            $this->data['purchase_invoice_details'] = $this->model['purchase_invoice_detail']->getRows(array('purchase_invoice_id' => $this->request->get['purchase_invoice_id']), array('sort_order'));

            $this->model['purchase_invoice_expense'] = $this->load->model('inventory/purchase_invoice_expense');
            $this->data['purchase_invoice_expenses'] = $this->model['purchase_invoice_expense']->getRows(array('purchase_invoice_id' => $this->request->get['purchase_invoice_id']), array('sort_order'));

            $this->model['purchase_invoice_ledger'] = $this->load->model('inventory/purchase_invoice_ledger');
            $this->data['purchase_invoice_ledgers'] = $this->model['purchase_invoice_ledger']->getRows(array('purchase_invoice_id' => $this->request->get['purchase_invoice_id']), array('sort_order'));
        }

        $this->data['href_get_product_json'] = $this->url->link($this->getAlias() . '/getProductJson', 'token=' . $this->session->data['token'] . '&' . $this->getPrimaryKey() . '=' . $this->request->get[$this->getPrimaryKey()], 'SSL');
        $this->data['href_get_ref_document_no'] = $this->url->link($this->getAlias() . '/getReferenceDocumentNos', 'token=' . $this->session->data['token'] . '&' . $this->getPrimaryKey() . '=' . $this->request->get[$this->getPrimaryKey()], 'SSL');
        $this->data['href_get_ref_document'] = $this->url->link($this->getAlias() . '/getReferenceDocument', 'token=' . $this->session->data['token'] . '&' . $this->getPrimaryKey() . '=' . $this->request->get[$this->getPrimaryKey()], 'SSL');
        $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/function/validateDate', 'token=' . $this->session->data['token']);
        $this->data['strValidation'] = "{
            'rules': {
                'document_date': {'required': true, 'remote':  {url: '" . $this->data['action_validate_date'] . "', type: 'post'}},
                'partner_id': {'required': true},
                'rate_type': {'required': true},
                'net_amount': {'required': true},
            },
            'ignore': [],
        }";

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

    protected function insertData($data) {
        $this->model['purchase_invoice_detail'] = $this->load->model('inventory/purchase_invoice_detail');
        $this->model['purchase_invoice_expense'] = $this->load->model('inventory/purchase_invoice_expense');
        $this->model['purchase_invoice_ledger'] = $this->load->model('inventory/purchase_invoice_ledger');
        $this->model['stock_ledger'] = $this->load->model('common/stock_ledger');
        $this->model['ledger'] = $this->load->model('gl/ledger');
        $this->model['document'] = $this->load->model('common/document');
        $this->model['document_type'] = $this->load->model('common/document_type');
        $this->model['partner'] = $this->load->model('common/partner');
        $this->model['company'] = $this->load->model('setup/company');
        $this->model['product']= $this->load->model('inventory/product');
        $this->model['setting']= $this->load->model('common/setting');

        //d($data, true);
        $document = $this->model['document_type']->getNextDocument($this->document_type_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['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_date'] = MySqlDate($data['document_date']);
        $data['base_amount'] = $data['net_amount'] * $data['conversion_rate'];
        $purchase_invoice_id = $this->model[$this->getAlias()]->add($this->getAlias(), $data);
        $data['document_id'] = $purchase_invoice_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' => $purchase_invoice_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['item_amount'],
            'conversion_rate' => $data['conversion_rate'],
            'base_currency_id' => $data['base_currency_id'],
            'base_amount' => $data['item_amount'],
        );
        $document_id = $this->model['document']->add($this->getAlias(), $insert_document);
        //d($insert_document,true);
        $setting = $this->model['setting']->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'],
            'module' => 'general',
            'field' => 'cash_account_id',
        ));
        $cash_account_id = $setting['value'];

        $setting = $this->model['setting']->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'],
            'module' => 'inventory',
            'field' => 'purchase_discount_account_id',
        ));
        $purchase_discount_account_id = $setting['value'];

        $setting = $this->model['setting']->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'],
            'module' => 'inventory',
            'field' => 'sale_tax_account_id',
        ));
        $sale_tax_account_id = $setting['value'];

        $setting = $this->model['setting']->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'],
            'module' => 'inventory',
            'field' => 'gr_ir_account_id',
        ));
        $gr_ir_account_id = $setting['value'];

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

        $sort_order = 0;
        foreach($data['purchase_invoice_ledgers'] as $detail) {
            $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['purchase_invoice_id'] = $purchase_invoice_id;
            $detail['sort_order'] = $sort_order;

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

            $gl_data[] = array(
                'document_detail_id' => $purchase_invoice_ledger_id,
                'coa_id' => $detail['coa_id'],
                'manual_ref_no' => $data['manual_ref_no'],
                'document_debit' => $detail['debit'],
                'document_credit' => $detail['credit'],
                'debit' => $detail['debit'],
                'credit' => $detail['credit'],
                'document_amount' => $data['total_debit'],
                'amount' => $data['total_debit'],
            );
            $sort_order++;
        }

        $sort_order = 0;
        foreach($data['purchase_invoice_expenses'] as $detail) {
            $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['purchase_invoice_id'] = $purchase_invoice_id;
            $detail['sort_order'] = $sort_order;

            $purchase_invoice_expense_id = $this->model['purchase_invoice_expense']->add($this->getAlias(), $detail);
            $sort_order++;
        }

        foreach ($data['purchase_invoice_details'] as $sort_order => $detail) {
            $product = $this->model['product']->getRow(array('product_id'=> $detail['product_id']));

            $detail['unit_id'] = $product['unit_id'];
            $detail['purchase_invoice_id'] = $purchase_invoice_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'];
            $purchase_invoice_detail_id = $this->model['purchase_invoice_detail']->add($this->getAlias(), $detail);

            $stock_ledger = array(
                'company_id' => $detail['company_id'],
                'company_branch_id' => $detail['company_branch_id'],
                'fiscal_year_id' => $detail['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'],
                'document_detail_id' => $purchase_invoice_detail_id,
                'warehouse_id' => $detail['warehouse_id'],
                'product_id' => $detail['product_id'],
                'document_unit_id' => $detail['unit_id'],
                'document_qty' => $detail['qty'],
                'unit_conversion' => 1,
                'base_unit_id' => $detail['unit_id'],
                'base_qty' => $detail['qty'],
                'container_no' => $detail['container_no'],
                'batch_no' => $detail['batch_no'],
                'document_currency_id' => $detail['document_currency_id'],
                'document_rate' => $detail['rate'],
                'document_amount' => $detail['amount'],
                'currency_conversion' => $detail['conversion_rate'],
                'base_currency_id' => $detail['base_currency_id'],
                'base_rate' => ($detail['rate'] * $detail['conversion_rate']),
                'base_amount' => ($detail['amount'] * $detail['conversion_rate']),
                'base_cubic_meter' => $detail['total_cubic_meter'],
                'base_cubic_feet' => $detail['total_cubic_feet']
            );
            $stock_ledger_id = $this->model['stock_ledger']->add($this->getAlias(), $stock_ledger);

//            if($detail['document_type_id'] == 17) {
//                $gl_data[] = array(
//                    'document_detail_id' => $purchase_invoice_detail_id,
//                    'ref_document_type_id' => $detail['ref_document_type_id'],
//                    'ref_document_id' => $detail['ref_document_id'],
//                    'ref_document_identity' => $detail['ref_document_identity'],
//                    'coa_id' => $gr_ir_account_id,
//                    'manual_ref_no' => $data['manual_ref_no'],
//                    'document_debit' => $detail['after_expense_amount'],
//                    'document_credit' => 0,
//                    'debit' => ($detail['after_expense_amount'] * $data['conversion_rate']),
//                    'credit' => 0,
//                    'product_id' => $detail['product_id'],
//                    'qty' => $detail['qty'],
//                    'document_amount' => $detail['after_expense_amount'],
//                    'amount' => ($detail['after_expense_amount'] * $data['conversion_rate']),
//                );
//            } else {
//                $product = $this->model['product']->getRow(array('product_id' => $detail['product_id']));
//                $gl_data[] = array(
//                    'document_detail_id' => $purchase_invoice_detail_id,
//                    'ref_document_type_id' => $detail['ref_document_type_id'],
//                    'ref_document_identity' => $detail['ref_document_identity'],
//                    'coa_id' => $product['inventory_account_id'],
//                    'manual_ref_no' => $data['manual_ref_no'],
//                    'document_debit' => $detail['after_expense_amount'],
//                    'document_credit' => 0,
//                    'debit' => ($detail['after_expense_amount'] * $data['conversion_rate']),
//                    'credit' => 0,
//                    'product_id' => $detail['product_id'],
//                    'qty' => $detail['qty'],
//                    'document_amount' => $detail['after_expense_amount'],
//                    'amount' => ($detail['after_expense_amount'] * $data['conversion_rate']),
//                );
//            }
//
//            if(floatval($detail['discount_amount']) > 0) {
//                $gl_data[] = array(
//                    'document_detail_id' => $purchase_invoice_detail_id,
//                    'ref_document_type_id' => $detail['ref_document_type_id'],
//                    'ref_document_identity' => $detail['ref_document_identity'],
//                    'coa_id' => $purchase_discount_account_id,
//                    'manual_ref_no' => $data['manual_ref_no'],
//                    'document_debit' => 0,
//                    'document_credit' => $detail['discount_amount'],
//                    'debit' => 0,
//                    'credit' => ($detail['discount_amount'] * $data['conversion_rate']),
//                    'product_id' => $detail['product_id'],
//                    'qty' => $detail['qty'],
//                    'document_amount' => $detail['discount_amount'],
//                    'amount' => ($detail['discount_amount'] * $data['conversion_rate']),
//                );
//            }
//
//            if(floatval($detail['tax_amount']) > 0) {
//                $gl_data[] = array(
//                    'document_detail_id' => $purchase_invoice_detail_id,
//                    'ref_document_type_id' => $detail['ref_document_type_id'],
//                    'ref_document_id' => $detail['ref_document_id'],
//                    'ref_document_identity' => $detail['ref_document_identity'],
//                    'coa_id' => $sale_tax_account_id,
//                    'manual_ref_no' => $data['manual_ref_no'],
//                    'document_debit' => $detail['tax_amount'],
//                    'document_credit' => 0,
//                    'debit' => ($detail['tax_amount'] * $data['conversion_rate']),
//                    'credit' => 0,
//                    'product_id' => $detail['product_id'],
//                    'qty' => $detail['qty'],
//                    'document_amount' => $detail['tax_amount'],
//                    'amount' => ($detail['tax_amount'] * $data['conversion_rate']),
//                );
//            }
//        }
//
//        if(floatval($data['discount']) > 0) {
//            $gl_data[] = array(
//                'ref_document_type_id' => $this->document_type_id,
//                'ref_document_identity' => $data['document_identity'],
//                'coa_id' => $purchase_discount_account_id,
//                'manual_ref_no' => $data['manual_ref_no'],
//                'document_debit' => 0,
//                'document_credit' => $data['discount'],
//                'debit' => 0,
//                'credit' => ($data['discount'] * $data['conversion_rate'])
//            );
//        }
//
//        $gl_data[] = array(
//            'ref_document_type_id' => $this->document_type_id,
//            'ref_document_identity' => $data['document_identity'],
//            'coa_id' => $outstanding_account_id,
//            'manual_ref_no' => $data['manual_ref_no'],
//            'document_debit' => 0,
//            'document_credit' => $data['net_amount'],
//            'debit' => 0,
//            'credit' => ($data['net_amount'] * $data['conversion_rate']),
//        );
//
//        if($data['invoice_type']=='Cash') {
//            $gl_data[] = array(
//                'ref_document_type_id' => $this->document_type_id,
//                'ref_document_identity' => $data['document_identity'],
//                'coa_id' => $outstanding_account_id,
//                'manual_ref_no' => $data['manual_ref_no'],
//                'document_credit' => 0,
//                'document_debit' => $data['net_amount'],
//                'credit' => 0,
//                'debit' => ($data['net_amount'] * $data['conversion_rate']),
//            );
//
//            $gl_data[] = array(
//                'ref_document_type_id' => $this->document_type_id,
//                'ref_document_identity' => $data['document_identity'],
//                'coa_id' => $cash_account_id,
//                'manual_ref_no' => $data['manual_ref_no'],
//                'document_debit' => 0,
//                'document_credit' => $data['net_amount'],
//                'debit' => 0,
//                'credit' => ($data['net_amount'] * $data['conversion_rate']),
//            );
        }

        //d($gl_data, true);
        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'] = $purchase_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['partner_type_id'] = $data['partner_type_id'];
            $ledger['partner_id'] = $data['partner_id'];
            $ledger['remarks'] = $data['remarks'];

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

    protected function updateData($primary_key, $data) {
        //d($data,true);
        $this->model['purchase_invoice_detail'] = $this->load->model('inventory/purchase_invoice_detail');
        $this->model['document'] = $this->load->model('common/document');
        $this->model['ledger'] = $this->load->model('gl/ledger');
        $this->model['stock_ledger'] = $this->load->model('common/stock_ledger');
        $this->model['partner'] = $this->load->model('common/partner');
        $this->model['company'] = $this->load->model('setup/company');
        $this->model['product']= $this->load->model('inventory/product');
        $this->model['setting']= $this->load->model('common/setting');
        $this->model['purchase_invoice_detail'] = $this->load->model('inventory/purchase_invoice_detail');
        $this->model['purchase_invoice_expense'] = $this->load->model('inventory/purchase_invoice_expense');
        $this->model['purchase_invoice_ledger'] = $this->load->model('inventory/purchase_invoice_ledger');

        $invoice = $this->model[$this->getAlias()]->getRow(array('purchase_invoice_id'=>$primary_key));
        $data['created_at'] = $invoice['created_at'];
        $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_date'] = MySqlDate($data['document_date']);
        $data['base_amount'] = $data['net_amount'] * $data['conversion_rate'];
        $purchase_invoice_id = $this->model[$this->getAlias()]->edit($this->getAlias(), $primary_key, $data);
        $data['document_id'] = $purchase_invoice_id;

        $this->model['purchase_invoice_detail']->deleteBulk($this->getAlias(), array('purchase_invoice_id' => $purchase_invoice_id));
        $this->model['purchase_invoice_expense']->deleteBulk($this->getAlias(), array('purchase_invoice_id' => $purchase_invoice_id));
        $this->model['purchase_invoice_ledger']->deleteBulk($this->getAlias(), array('purchase_invoice_id' => $purchase_invoice_id));
        $this->model['document']->deleteBulk($this->getAlias(), array('company_id' => $this->session->data['company_id'],'document_type_id' => $this->document_type_id, 'document_id' => $primary_key));
        $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));
        $this->model['stock_ledger']->deleteBulk($this->getAlias(), array('company_id' => $this->session->data['company_id'],'document_type_id' => $this->document_type_id, 'document_id' => $primary_key));

        $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' => $purchase_invoice_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['item_amount'],
            'conversion_rate' => $data['conversion_rate'],
            'base_currency_id' => $data['base_currency_id'],
            'base_amount' => $data['item_amount'],
            'created_at' => $data['created_at'],
        );
        $document_id = $this->model['document']->add($this->getAlias(), $insert_document);
//d($insert_document,true);
        $setting = $this->model['setting']->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'],
            'module' => 'general',
            'field' => 'cash_account_id',
        ));
        $cash_account_id = $setting['value'];

        $setting = $this->model['setting']->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'],
            'module' => 'inventory',
            'field' => 'purchase_discount_account_id',
        ));
        $purchase_discount_account_id = $setting['value'];

        $setting = $this->model['setting']->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'],
            'module' => 'inventory',
            'field' => 'sale_tax_account_id',
        ));
        $sale_tax_account_id = $setting['value'];

        $setting = $this->model['setting']->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'],
            'module' => 'inventory',
            'field' => 'gr_ir_account_id',
        ));
        $gr_ir_account_id = $setting['value'];

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

        $sort_order = 0;
        foreach($data['purchase_invoice_ledgers'] as $detail) {
            $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['purchase_invoice_id'] = $purchase_invoice_id;
            $detail['sort_order'] = $sort_order;
            $detail['created_at'] = $data['created_at'];

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

            $gl_data[] = array(
                'document_detail_id' => $purchase_invoice_ledger_id,
                'coa_id' => $detail['coa_id'],
                'manual_ref_no' => $data['manual_ref_no'],
                'document_debit' => $detail['debit'],
                'document_credit' => $detail['credit'],
                'debit' => $detail['debit'],
                'credit' => $detail['credit'],
                'document_amount' => $data['total_debit'],
                'amount' => $data['total_debit'],
            );
            $sort_order++;
        }

        $sort_order = 0;
        foreach($data['purchase_invoice_expenses'] as $detail) {
            $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['purchase_invoice_id'] = $purchase_invoice_id;
            $detail['sort_order'] = $sort_order;

            $purchase_invoice_expense_id = $this->model['purchase_invoice_expense']->add($this->getAlias(), $detail);
            $sort_order++;
        }

        foreach ($data['purchase_invoice_details'] as $sort_order => $detail) {
            $product = $this->model['product']->getRow(array('product_id'=> $detail['product_id']));

            $detail['unit_id'] = $product['unit_id'];
            $detail['purchase_invoice_id'] = $purchase_invoice_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_total'] = $detail['net_amount'] * $data['conversion_rate'];
            $purchase_invoice_detail_id = $this->model['purchase_invoice_detail']->add($this->getAlias(), $detail);

            $stock_ledger = array(
                'company_id' => $detail['company_id'],
                'company_branch_id' => $detail['company_branch_id'],
                'fiscal_year_id' => $detail['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'],
                'document_detail_id' => $purchase_invoice_detail_id,
                'warehouse_id' => $detail['warehouse_id'],
                'product_id' => $detail['product_id'],
                'document_unit_id' => $detail['unit_id'],
                'document_qty' => $detail['qty'],
                'unit_conversion' => 1,
                'base_unit_id' => $detail['unit_id'],
                'base_qty' => $detail['qty'],
                'container_no' => $detail['container_no'],
                'batch_no' => $detail['batch_no'],
                'document_currency_id' => $detail['document_currency_id'],
                'document_rate' => $detail['rate'],
                'document_amount' => $detail['amount'],
                'currency_conversion' => $detail['conversion_rate'],
                'base_currency_id' => $detail['base_currency_id'],
                'base_rate' => ($detail['rate'] * $detail['conversion_rate']),
                'base_amount' => ($detail['amount'] * $detail['conversion_rate']),
                'base_cubic_meter' => $detail['total_cubic_meter'],
                'base_cubic_feet' => $detail['total_cubic_feet'],
                'created_at' => $data['created_at']
            );
            $stock_ledger_id = $this->model['stock_ledger']->add($this->getAlias(), $stock_ledger);

//            if($detail['document_type_id'] == 17) {
//                $gl_data[] = array(
//                    'document_detail_id' => $purchase_invoice_detail_id,
//                    'ref_document_type_id' => $detail['ref_document_type_id'],
//                    'ref_document_id' => $detail['ref_document_id'],
//                    'ref_document_identity' => $detail['ref_document_identity'],
//                    'coa_id' => $gr_ir_account_id,
//                    'manual_ref_no' => $data['manual_ref_no'],
//                    'document_debit' => $detail['after_expense_amount'],
//                    'document_credit' => 0,
//                    'debit' => ($detail['after_expense_amount'] * $data['conversion_rate']),
//                    'credit' => 0,
//                    'product_id' => $detail['product_id'],
//                    'qty' => $detail['qty'],
//                    'document_amount' => $detail['after_expense_amount'],
//                    'amount' => ($detail['after_expense_amount'] * $data['conversion_rate']),
//                );
//            } else {
//                $product = $this->model['product']->getRow(array('product_id' => $detail['product_id']));
//                $gl_data[] = array(
//                    'document_detail_id' => $purchase_invoice_detail_id,
//                    'ref_document_type_id' => $detail['ref_document_type_id'],
//                    'ref_document_identity' => $detail['ref_document_identity'],
//                    'coa_id' => $product['inventory_account_id'],
//                    'manual_ref_no' => $data['manual_ref_no'],
//                    'document_debit' => $detail['after_expense_amount'],
//                    'document_credit' => 0,
//                    'debit' => ($detail['after_expense_amount'] * $data['conversion_rate']),
//                    'credit' => 0,
//                    'product_id' => $detail['product_id'],
//                    'qty' => $detail['qty'],
//                    'document_amount' => $detail['after_expense_amount'],
//                    'amount' => ($detail['after_expense_amount'] * $data['conversion_rate']),
//                );
//            }
//
//            if(floatval($detail['discount_amount']) > 0) {
//                $gl_data[] = array(
//                    'document_detail_id' => $purchase_invoice_detail_id,
//                    'ref_document_type_id' => $detail['ref_document_type_id'],
//                    'ref_document_identity' => $detail['ref_document_identity'],
//                    'coa_id' => $purchase_discount_account_id,
//                    'manual_ref_no' => $data['manual_ref_no'],
//                    'document_debit' => 0,
//                    'document_credit' => $detail['discount_amount'],
//                    'debit' => 0,
//                    'credit' => ($detail['discount_amount'] * $data['conversion_rate']),
//                    'product_id' => $detail['product_id'],
//                    'qty' => $detail['qty'],
//                    'document_amount' => $detail['discount_amount'],
//                    'amount' => ($detail['discount_amount'] * $data['conversion_rate']),
//                );
//            }
//
//            if(floatval($detail['tax_amount']) > 0) {
//                $gl_data[] = array(
//                    'document_detail_id' => $purchase_invoice_detail_id,
//                    'ref_document_type_id' => $detail['ref_document_type_id'],
//                    'ref_document_id' => $detail['ref_document_id'],
//                    'ref_document_identity' => $detail['ref_document_identity'],
//                    'coa_id' => $sale_tax_account_id,
//                    'manual_ref_no' => $data['manual_ref_no'],
//                    'document_debit' => $detail['tax_amount'],
//                    'document_credit' => 0,
//                    'debit' => ($detail['tax_amount'] * $data['conversion_rate']),
//                    'credit' => 0,
//                    'product_id' => $detail['product_id'],
//                    'qty' => $detail['qty'],
//                    'document_amount' => $detail['tax_amount'],
//                    'amount' => ($detail['tax_amount'] * $data['conversion_rate']),
//                );
//            }
//        }
//
//        if(floatval($data['discount']) > 0) {
//            $gl_data[] = array(
//                'ref_document_type_id' => $this->document_type_id,
//                'ref_document_identity' => $data['document_identity'],
//                'coa_id' => $purchase_discount_account_id,
//                'manual_ref_no' => $data['manual_ref_no'],
//                'document_debit' => 0,
//                'document_credit' => $data['discount'],
//                'debit' => 0,
//                'credit' => ($data['discount'] * $data['conversion_rate'])
//            );
//        }
//
//        $gl_data[] = array(
//            'ref_document_type_id' => $this->document_type_id,
//            'ref_document_identity' => $data['document_identity'],
//            'coa_id' => $outstanding_account_id,
//            'manual_ref_no' => $data['manual_ref_no'],
//            'document_debit' => 0,
//            'document_credit' => $data['net_amount'],
//            'debit' => 0,
//            'credit' => ($data['net_amount'] * $data['conversion_rate']),
//        );
//
//        if($data['invoice_type']=='Cash') {
//            $gl_data[] = array(
//                'ref_document_type_id' => $this->document_type_id,
//                'ref_document_identity' => $data['document_identity'],
//                'coa_id' => $outstanding_account_id,
//                'manual_ref_no' => $data['manual_ref_no'],
//                'document_credit' => 0,
//                'document_debit' => $data['net_amount'],
//                'credit' => 0,
//                'debit' => ($data['net_amount'] * $data['conversion_rate']),
//            );
//
//            $gl_data[] = array(
//                'ref_document_type_id' => $this->document_type_id,
//                'ref_document_identity' => $data['document_identity'],
//                'coa_id' => $cash_account_id,
//                'manual_ref_no' => $data['manual_ref_no'],
//                'document_debit' => 0,
//                'document_credit' => $data['net_amount'],
//                'debit' => 0,
//                'credit' => ($data['net_amount'] * $data['conversion_rate']),
//            );
        }

        //d($gl_data, true);
        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'] = $purchase_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['partner_type_id'] = $data['partner_type_id'];
            $ledger['partner_id'] = $data['partner_id'];
            $ledger['remarks'] = $data['remarks'];
            $ledger['created_at'] = $data['created_at'];

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

    protected function deleteData($primary_key) {
        $this->model[$this->getAlias()]->delete($this->getAlias(), $primary_key);

        $this->model['purchase_invoice_detail'] = $this->load->model('inventory/purchase_invoice_detail');
        $this->model['purchase_invoice_detail']->deleteBulk($this->getAlias(), array('purchase_invoice_id' => $primary_key));

        $this->model['purchase_invoice_expense'] = $this->load->model('inventory/purchase_invoice_expense');
        $this->model['purchase_invoice_expense']->deleteBulk($this->getAlias(), array('purchase_invoice_id' => $primary_key));

        $this->model['purchase_invoice_ledger'] = $this->load->model('inventory/purchase_invoice_ledger');
        $this->model['purchase_invoice_ledger']->deleteBulk($this->getAlias(), array('purchase_invoice_id' => $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));

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

        $this->model['stock_ledger'] = $this->load->model('common/stock_ledger');
        $this->model['stock_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 getProductJson() {
        $search = $this->request->post['q'];
        $page = $this->request->post['page'];

        $this->model['product'] = $this->load->model('inventory/product');
        $rows = $this->model['product']->getProductJson($search, $page);

        echo json_encode($rows);
    }

    public function getReferenceDocumentNos() {
        $purchase_invoice_id = $this->request->get['purchase_invoice_id'];
        $post = $this->request->post;

        if($post['ref_document_type_id'] == 4) {
            //Purchase Order
            $this->model['purchase_order'] = $this->load->model('inventory/purchase_order');
            $where = "company_id=" . $this->session->data['company_id'];
            $where .= " AND company_branch_id='" . $this->session->data['company_branch_id'] . "'";
            $where .= " AND fiscal_year_id=" . $this->session->data['fiscal_year_id'];
            $where .= " AND supplier_id='" . $post['supplier_id'] . "'";
            $where .= " AND document_currency_id='" . $post['document_currency_id'] . "'";
            $where .= " AND is_post=1";

            $purchase_orders = $this->model['purchase_order']->getPurchaseOrders($where,$purchase_invoice_id);
            foreach($purchase_orders as $purchase_order_id => $purchase_order) {
                foreach($purchase_order['products'] as $product_id => $product) {
                    if($product['order_qty'] <= $product['utilized_qty']) {
                        unset($purchase_order['products'][$product_id]);
                    }
                }
                if(empty($purchase_order['products'])) {
                    unset($purchase_orders[$purchase_order_id]);
                }
            }

            $html = "";
            $html .= '<option value="">&nbsp;</option>';
            foreach($purchase_orders as $purchase_order_id => $purchase_order) {
                $html .= '<option value="'.$purchase_order_id.'">'.$purchase_order['document_identity'].' '.'('.$purchase_order['manual_ref_no'].')'. '</option>';
            }
        } elseif($post['ref_document_type_id'] == 17) {
            //Goods Received
            $this->model['goods_received'] = $this->load->model('inventory/goods_received');
            $where = "company_id=" . $this->session->data['company_id'];
            $where .= " AND company_branch_id='" . $this->session->data['company_branch_id'] . "'";
            $where .= " AND fiscal_year_id=" . $this->session->data['fiscal_year_id'];
            $where .= " AND partner_type_id='" . $post['partner_type_id'] . "'";
            $where .= " AND partner_id='" . $post['partner_id'] . "'";
            //$where .= " AND document_currency_id='" . $post['document_currency_id'] . "'";
            //$where .= " AND is_post=1";

            $orders = $this->model['goods_received']->getRows($where);

            $html = "";
            $html .= '<option value="">&nbsp;</option>';
            foreach($orders as $goods_received) {
                $html .= '<option value="'.$goods_received['document_identity'].'">'.$goods_received['document_identity']. '</option>';
            }
        }

        //d($goods_received,true);
        $json = array(
            'success' => true,
            'purchase_invoice_id' => $purchase_invoice_id,
            'post' => $post,
            'where' => $where,
            'orders' => $orders,
            'html' => $html
        );

        echo json_encode($json);
    }

    public function getReferenceDocument() {
        $purchase_invoice_id = $this->request->get['purchase_invoice_id'];
        $post = $this->request->post;

        if($post['ref_document_type_id'] == 4) {
            //Purchase Order
            $this->model['purchase_order'] = $this->load->model('inventory/purchase_order');
            $where = "company_id=" . $this->session->data['company_id'];
            $where .= " AND company_branch_id='" . $this->session->data['company_branch_id'] . "'";
            $where .= " AND fiscal_year_id=" . $this->session->data['fiscal_year_id'];
            $where .= " AND partner_type_id='" . $post['partner_type_id'] . "'";
            $where .= " AND partner_id='" . $post['partner_id'] . "'";
            $where .= " AND document_identity='" . $post['ref_document_identity'] . "'";
//            $where .= " AND document_currency_id='" . $post['document_currency_id'] . "'";
//            $where .= " AND is_post=1";

            $rows = $this->model['goods_received_detail']->getRows($where);
            $html = '';
            $details = array();
            foreach($rows as $row_no => $row) {
                $href = $this->url->link('inventory/goods_received/update', 'token=' . $this->session->data['token'] . '&goods_received_id=' . $row['goods_received_id']);
                $details[$row_no] = $row;
                $details[$row_no]['href'] = $href;
            }
        } elseif($post['ref_document_type_id'] == 17) {
            //Goods Received
            $this->model['goods_received_detail'] = $this->load->model('inventory/goods_received_detail');
            $where = "company_id=" . $this->session->data['company_id'];
            $where .= " AND company_branch_id='" . $this->session->data['company_branch_id'] . "'";
            $where .= " AND fiscal_year_id=" . $this->session->data['fiscal_year_id'];
            $where .= " AND partner_type_id='" . $post['partner_type_id'] . "'";
            $where .= " AND partner_id='" . $post['partner_id'] . "'";
            $where .= " AND document_identity='" . $post['ref_document_identity'] . "'";
//            $where .= " AND document_currency_id='" . $post['document_currency_id'] . "'";
//            $where .= " AND is_post=1";

            $rows = $this->model['goods_received_detail']->getRows($where);
            $html = '';
            $details = array();
            foreach($rows as $row_no => $row) {
                $href = $this->url->link('inventory/goods_received/update', 'token=' . $this->session->data['token'] . '&goods_received_id=' . $row['goods_received_id']);
                $details[$row_no] = $row;
                $details[$row_no]['href'] = $href;
            }
        }

        $json = array(
            'success' => true,
            'purchase_invoice_id' => $purchase_invoice_id,
            'post' => $post,
            'where' => $where,
            'details' => $details);
        echo json_encode($json);
    }

    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;
        $purchase_invoice_id = $this->request->get['purchase_invoice_id'];
        $with_previous_balance = isset($this->request->get['with_previous_balance'])?1:0;
        //d($purchase_invoice_id,true);
        $this->model['partner'] = $this->load->model('common/partner');
        $this->model['purchase_invoice'] = $this->load->model('inventory/purchase_invoice');
        $this->model['purchase_invoice_detail'] = $this->load->model('inventory/purchase_invoice_detail');
        $this->model['purchase_invoice_expense'] = $this->load->model('inventory/purchase_invoice_expense');

        $invoice = $this->model['purchase_invoice']->getRow(array('purchase_invoice_id' => $purchase_invoice_id));
        $rows = $this->model['purchase_invoice_detail']->getRows(array('purchase_invoice_id' => $purchase_invoice_id), array('container_no','product_name'));
        $expenses = $this->model['purchase_invoice_expense']->getRows(array('purchase_invoice_id' => $purchase_invoice_id), array('sort_order'));
        $sales = $this->model['purchase_invoice']->getSales($invoice['manual_ref_no']);
        //d([$invoice['manual_ref_no'], $sales]);
        //d($expenses, true);
        $partner = $this->model['partner']->getRow(array('partner_id' => $invoice['partner_id']));
        $arrWhere = array();
        $arrWhere[] = "l.`partner_id` = '".$invoice['partner_id']."'";
        $arrWhere[] = "l.`document_date` < '".$invoice['document_date']."'";
        //$arrWhere[] = "l.`created_at` < '".$invoice['created_at']."'";
        $where = implode(' AND ', $arrWhere);

        $outstanding = $this->model['partner']->getOutstanding($where);
        //d($outstanding, true);
        $details = array();
        foreach($rows as $row) {
            if(isset($details[$row['container_no'].'-'.$row['product_id'].'-'.$row['rate']])) {
                $details[$row['container_no'].'-'.$row['product_id'].'-'.$row['rate']]['qty'] += $row['qty'];
                $details[$row['container_no'].'-'.$row['product_id'].'-'.$row['rate']]['total_cubic_meter'] += $row['total_cubic_meter'];
                $details[$row['container_no'].'-'.$row['product_id'].'-'.$row['rate']]['total_cubic_feet'] += $row['total_cubic_feet'];
                $details[$row['container_no'].'-'.$row['product_id'].'-'.$row['rate']]['base_total'] += $row['base_total'];
            } else {
                $details[$row['container_no'].'-'.$row['product_id'].'-'.$row['rate']] = array(
                    'product_name' => $row['product_name'],
                    'container_no' => $row['container_no'],
                    'rate' => $row['rate'],
                    'qty' => $row['qty'],
                    'total_cubic_meter' => $row['total_cubic_meter'],
                    'total_cubic_feet' => $row['total_cubic_feet'],
                    'amount' => $row['amount']
                );
            }
        }

        $total_sales = 0;
        foreach($sales as $sale) {
            $total_sales += $sale['amount'];
        }
        //d(array($purchase_invoice_id, $invoice, $details), 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('Purchase Invoice');
        $pdf->SetSubject('Purchase Invoice');

        //Set Header
        $pdf->data = array(
            'company_name' => $session['company_name'],
            //'report_name' => $lang['heading_title'],
            'report_name' => 'Purchase Invoice',
            'company_logo' => $session['company_image']
        );

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

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

        // add a page
        $pdf->AddPage();
        // set font
        $pdf->SetFont('times', 'B', 9);
        $pdf->Cell(20, 7, 'Invoice No: ', 0, false, 'L', 0, '', 0, false, 'M', 'M');
        // set font
        $pdf->SetFont('times', '', 9);
        $pdf->Cell(40, 7, $invoice['document_identity'], 'B', false, 'C', 0, '', 0, false, 'M', 'M');
        // set font
        $pdf->SetFont('times', 'B', 9);
        $pdf->Cell(20, 7, 'Date: ', 0, false, 'R', 0, '', 0, false, 'M', 'M');
        // set font
        $pdf->SetFont('times', '', 9);
        $pdf->Cell(40, 7, stdDate($invoice['document_date']), 'B', false, 'L', 0, '', 0, false, 'M', 'M');
        // set font
        $pdf->SetFont('times', 'B', 9);
        $pdf->Cell(20, 7, 'Phone: ', 0, false, 'R', 0, '', 0, false, 'M', 'M');
        // set font
        $pdf->SetFont('times', '', 9);
        $pdf->Cell(40, 7, $partner['mobile'], 'B', false, 'L', 0, '', 0, false, 'M', 'M');
        $pdf->ln(10);
        // set font
        $pdf->SetFont('times', 'B', 9);
        $pdf->Cell(20, 7, 'M/S: ', 0, false, 'L', 0, '', 0, false, 'M', 'M');
        // set font
        $pdf->SetFont('times', '', 9);
        $pdf->Cell(160, 7, $invoice['partner_name'], 'B', false, 'L', 0, '', 0, false, 'M', 'M');
        $pdf->ln(10);
        // set font
        $pdf->SetFont('times', 'B', 9);
        $pdf->Cell(20, 7, 'Address:', 0, false, 'L', 0, '', 0, false, 'M', 'M');
        // set font
        $pdf->SetFont('times', '', 9);
        $pdf->Cell(160, 7, $partner['address'], 'B', false, 'L', 0, '', 0, false, 'M', 'M');
        $pdf->ln(7);

        // set font
        $pdf->SetFont('times', '', 8);
        $pdf->SetFillColor(215, 215, 215);
        $pdf->SetTextColor(0, 0, 0);
        $pdf->Cell(80, 8, 'Particulars', 1, false, 'C', 1, '', 1);
        $pdf->Cell(35, 8, 'Container No.', 1, false, 'C', 1, '', 1);
        $pdf->Cell(8, 8, 'Pcs.', 1, false, 'C', 1, '', 1);
        $pdf->Cell(13, 8, 'Qty Mtr', 1, false, 'C', 1, '', 1);
        $pdf->Cell(13, 8, 'Qty Fts', 1, false, 'C', 1, '', 1);
        $pdf->Cell(13, 8, 'Rate', 1, false, 'C', 1, '', 1);
        $pdf->Cell(18, 8, 'Amount', 1, false, 'C', 1, '', 1);

        $pdf->SetFillColor(255, 255, 255);
        $pdf->SetTextColor(0, 0, 0);
        $total_qty = 0;
        $total_meter = 0;
        $total_feet = 0;
        $total_amount = 0;
        foreach($details as $detail) {
            //d($detail,true);
            $pdf->ln(8);
            $pdf->Cell(80, 8, $detail['product_name'], 1, false, 'L', 0, '', 1);
            $pdf->Cell(35, 8, $detail['container_no'], 1, false, 'L', 0, '', 1);
            $pdf->Cell(8, 8, number_format($detail['qty'],0), 1, false, 'R', 0, '', 1);
            $pdf->Cell(13, 8, $detail['total_cubic_meter'], 1, false, 'R', 0, '', 1);
            $pdf->Cell(13, 8, $detail['total_cubic_feet'], 1, false, 'R', 0, '', 1);
            $pdf->Cell(13, 8, number_format($detail['rate'],2), 1, false, 'R', 0, '', 1);
            $pdf->Cell(18, 8, number_format($detail['amount'],2), 1, false, 'R', 0, '', 1);

            $total_qty += $detail['qty'];
            $total_meter += $detail['total_cubic_meter'];
            $total_feet += $detail['total_cubic_feet'];
            $total_amount += $detail['amount'];
        }
//        foreach($expenses as $expense) {
//            $pdf->ln(8);
//            $pdf->Cell(85, 8, html_entity_decode($expense['display_name']), 1, false, 'L', 0, '', 1);
//            $pdf->Cell(20, 8, '', 1, false, 'L', 0, '', 1);
//            $pdf->Cell(10, 8, '', 1, false, 'R', 0, '', 1);
//            $pdf->Cell(15, 8, '', 1, false, 'R', 0, '', 1);
//            $pdf->Cell(15, 8, '', 1, false, 'R', 0, '', 1);
//            $pdf->Cell(15, 8, '', 1, false, 'R', 0, '', 1);
//            $pdf->Cell(20, 8, number_format($expense['expense_amount'],2), 1, false, 'R', 0, '', 1);
//            $total_amount += $expense['expense_amount'];
//        }

        $pdf->ln(8);
        $pdf->Cell(115, 8, '', 1, false, 'L', 0, '', 1);
        $pdf->Cell(8, 8, number_format($total_qty,0), 1, false, 'R', 0, '', 1);
        $pdf->Cell(13, 8, $total_meter, 1, false, 'R', 0, '', 1);
        $pdf->Cell(13, 8, $total_feet, 1, false, 'R', 0, '', 1);
        $pdf->Cell(13, 8, '', 1, false, 'R', 0, '', 1);
        $pdf->Cell(18, 8, number_format($total_amount,2), 1, false, 'R', 0, '', 1);

//        $pdf->ln(8);
//        $pdf->Cell(130, 6, '', 0, false, 'L');
//        $pdf->Cell(25, 6, $lang['total_amount'].': ', 'LT', false, 'L');
//        $pdf->Cell(25, 6, number_format($total_amount,2), 'RT', false, 'R');
//
//        $pdf->ln(6);
//        $pdf->Cell(130, 6, '', 0, false, 'L');
//        $pdf->Cell(25, 6, 'Discount Amount: ', 'L', false, 'L');
//        $pdf->Cell(25, 6, number_format($invoice['discount_amount'],2), 'R', false, 'R');
//
//        if($invoice['document_currency_id'] == $invoice['base_currency_id'] || $invoice['conversion_rate'] == 1) {
//            $pdf->ln(6);
//            $pdf->Cell(130, 6, 'IN WORD: ' . Number2Words(round($invoice['net_amount'],2)). ' only', 0, false, 'L', 0, '', 1);
//            if($with_previous_balance==0) {
//                $pdf->Cell(25, 6, $lang['net_amount'].': ', 'LTB', false, 'L');
//                $pdf->Cell(25, 6, number_format($invoice['net_amount'],2), 'RTB', false, 'R');
//            } else {
//                $pdf->Cell(25, 6, $lang['net_amount'].': ', 'LT', false, 'L');
//                $pdf->Cell(25, 6, number_format($invoice['net_amount'],2), 'RT', false, 'R');
//                $pdf->ln(6);
//                $pdf->Cell(130, 6, '', 0, false, 'L', 0, '', 1);
//                $pdf->Cell(25, 6, 'Previous Balance: ', 'L', false, 'L');
//                $pdf->Cell(25, 6, number_format($outstanding['outstanding'],2), 'R', false, 'R');
//                $pdf->ln(6);
//                $pdf->Cell(130, 6, '', 0, false, 'L', 0, '', 1);
//                $pdf->Cell(25, 6, 'Current Balance: ', 'LTB', false, 'L');
//                $pdf->Cell(25, 6, number_format(($outstanding['outstanding']+$invoice['net_amount']),2), 'RTB', false, 'R');
//            }
//        } else {
//            $pdf->ln(6);
//            $pdf->Cell(130, 6, '', 0, false, 'R');
//            $pdf->Cell(25, 6, $lang['total_amount'].': ', 0, false, 'L');
//            $pdf->Cell(25, 6, number_format($invoice['net_amount'],2), 0, false, 'R');
//            $pdf->ln(6);
//            $pdf->Cell(130, 6, '', 0, false, 'R');
//            $pdf->Cell(25, 6, $lang['conversion_rate'].': ', 0, false, 'L');
//            $pdf->Cell(25, 6, number_format($invoice['conversion_rate'],2), 0, false, 'R');
            $pdf->ln(16);
            $pdf->Cell(130, 6, 'IN WORD: ' . Number2Words(round($total_amount,2)). ' only', 0, false, 'L');
//            $pdf->Cell(25, 6, $lang['base_amount'].': ', 'T', false, 'L');
 //           $pdf->Cell(25, 6, number_format($invoice['base_amount'],2), 'T', false, 'R');
//        }
        $pdf->ln(20);
        $html = '';
        $html .= '<table width="100%" cellpadding="0" border="0">';
        $html .= '<tr>';
        // Left side Table
        $html .= '<td width="38%">';
        if(count($expenses)>0) {
            $html .= '<table cellspacing="0" cellpadding="1" border="1">';
            $html .= '  <tr>';
            $html .= '      <td width="70%" align="center"><b>'.$lang['expense_head'].'</b></td>';
            $html .= '      <td width="25%" align="center"><b>'.'Amount'.'</b></td>';
            $html .= '  </tr>';
            $total_expense = 0;
            foreach($expenses as $expense) {
                $html .= '  <tr>';
                $html .= '      <td>'.html_entity_decode($expense['expense_name']).': '.'</td>';
                $html .= '      <td align="right">'.number_format($expense['expense_amount'],2).'</td>';
                $html .= '  </tr>';
                $total_expense += $expense['expense_amount'];
            }
            $html .= '  <tr>';
            $html .= '      <td><b>'.$lang['total_expense'].': '.'</b></td>';
            $html .= '      <td align="right"><b>'.number_format($total_expense,2).'</b></td>';
            $html .= '  </tr>';
            $html .= '</table>';
        }
        $balance = $total_sales - $total_expense;
        $html .= '<table cellspacing="0" cellpadding="1" border="0">';
        $html .= '  <tr>';
        $html .= '      <td width="70%" align="center"><b>&nbsp;</b></td>';
        $html .= '      <td width="25%" align="center"><b>&nbsp;</b></td>';
        $html .= '  </tr>';
        $html .= '  <tr>';
        $html .= '      <td width="70%" align="center"><b>&nbsp;</b></td>';
        $html .= '      <td width="25%" align="center"><b>&nbsp;</b></td>';
        $html .= '  </tr>';
        $html .= '  <tr>';
        $html .= '      <td width="70%" align="center"><b>PROFIT / LOSS</b></td>';
        $html .= '      <td width="25%" align="center"><b>'.($balance<0?'('.number_format((-1*$balance),2).')':number_format($balance,2)).'</b></td>';
        $html .= '  </tr>';
        $html .= '</table>';
        $html .= '</td>';
        $html .= '<td width="5%"></td>';
        $html .= '<td width="57%">';
        if(count($sales)>0) {
            $html .= '<table cellspacing="0" cellpadding="1" border="1">';
            $html .= '  <tr>';
            $html .= '      <td width="15%" align="center"><b>Doc. Date</b></td>';
            $html .= '      <td width="25%" align="center"><b>'.$lang['document_no'].'</b></td>';
            $html .= '      <td width="30%" align="center"><b>'.$lang['partner_name'].'</b></td>';
            $html .= '      <td width="15%" align="center"><b>'.$lang['cubic_feet'].'</b></td>';
            $html .= '      <td width="15%" align="center"><b>'.$lang['amount'].'</b></td>';
            $html .= '  </tr>';
            $total_sale = 0;
            $total_cft = 0;
            foreach($sales as $sale) {
                $html .= '  <tr>';
                $html .= '      <td>'.html_entity_decode(stdDate($sale['document_date'])).'</td>';
                $html .= '      <td>'.html_entity_decode($sale['document_identity']).'</td>';
                $html .= '      <td>'.html_entity_decode($sale['partner_name']).'</td>';
                $html .= '      <td align="right">'.html_entity_decode(number_format($sale['cft'],2)).'</td>';
                $html .= '      <td align="right">'.number_format($sale['amount'],2).'</td>';
                $html .= '  </tr>';
                $total_sale += $sale['amount'];
                $total_cft += $sale['cft'];
            }
            $html .= '  <tr>';
            $html .= '      <td colspan="3"><b>'.$lang['total'].': '.'</b></td>';
            $html .= '      <td align="right"><b>'.number_format($total_cft,2).'</b></td>';
            $html .= '      <td align="right"><b>'.number_format($total_sale,2).'</b></td>';
            $html .= '  </tr>';
            $html .= '</table>';
        }
        $html .= '</td>';
        $html .= '</tr>';
        $html .= '</table>';
        $pdf->writeHTML($html);
        //Close and output PDF document
        $pdf->Output('Purchase Invoice - '.$invoice['document_identity'].'.pdf', 'I');
    }

}

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

    //Page header
    public function Header() {

        // Set font
        $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->Cell(0, 10, $this->data['report_name'], 0, false, 'C', 0, '', 0, false, 'M', 'M');

        // 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 = 150;
            $y = 5;
            $w = 50;
            $h = 0;
            //$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);
        }
    }

    // Page footer
    public function Footer() {
        // Position at 15 mm from bottom
        $this->SetY(-15);
        // Set font
        $this->SetFont('helvetica', 'I', 8);
        // Page number
        $this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
    }
}

?>