<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Aptransaction extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Useraccess');
        $query = $this->Useraccess->useraccess_id_module2('3', 'transaction');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $this->load->library('layouts');
        $this->load->model('menu');
    }
    

// invoice
    public function invoicePosting() {
        $this->lang->load("purchaseinvoiceconfirm", $this->session->userdata('language'));
        $ID = $this->input->post('fldid');
        $effdate = date("Y-m-d", strtotime($this->input->post('effdate')));
		$this->load->model('accountPayable/accountPayable_model');
        $queryDetails = $this->accountPayable_model->purchaseInvoiceDetails_ID($ID);
        $data = array(
            'updateAble' => '0'
        );
        $query = $this->accountPayable_model->purchaseInvoice_post($ID, $data);
        if ($query) {
            $this->load->model('Compfinancialyear');
            $query1 = $this->Compfinancialyear->compfinancialyear_date1($effdate);
            if ($query1) {
                $year = $query1[0]->financialYear;
                $period = $query1[0]->period;
                $formNo = $query[0]->formNo . '[' . sprintf('%08d', $query[0]->ID) . ']';
                $total_amount_dr = $query[0]->totalPaid * $query[0]->exchangeRate;
                $total_amount_cr = $query[0]->totalPaid * $query[0]->exchangeRate;
            } else {
                print json_encode(array("status" => "failed", "message" => $query1));
                return FALSE;
            }
            $this->load->model('Glseq');
            $query2 = $this->Glseq->glSequence_sub('3', 'AP', $year, $period);
            $newData = array(
                'companyID' => element('compID', $this->session->userdata('logged_in')),
                'journalID' => $query2['seqNumber'],
                'formNo' => $formNo,
                'description' => $this->lang->line('message2') . ' [ ' . $formNo . ' ]',
                'module' => '3',
                'effective_date' => $effdate,
                'year' => $year,
                'period' => $period,
                'total_amount_dr' => $total_amount_dr,
                'total_amount_cr' => $total_amount_cr,
                'createdBy' => element('role', $this->session->userdata('logged_in'))
            );
            $data = array(
                'journalNo' => $query2['seqNumber']
            );
            $query5 = $this->accountPayable_model->updateInvoice($ID, $data);
            $this->load->model('Journal');
            $query3 = $this->Journal->journal_insert($newData);
            if ($query3) {
                $query4 = $this->accountPayable_model->purchaseInvoiceDetails_invoiceID($query2['seqNumber'], $query[0], $queryDetails, $year, $period);
                print json_encode(array("status" => "success", "message" => $query));
            } else {
                print json_encode(array("status" => "failed", "message" => $query));
            }
        } else {
            return FALSE;
        }
	}
// Payment
    public function getCompanyInvoiceList() {
        $this->load->model('accountPayable/accountPayable_model');
        echo $this->accountPayable_model->getCompanyInvoiceListBySup($this->input->post('supplierID'));
    }

    public function payment() {
        $ID = isset($_REQUEST['ID']) ? $_REQUEST['ID'] : "";
        $supplierID = $this->uri->segment(3);
//		$supplierID2 = isset($_REQUEST['supplier'])?$_REQUEST['supplier']:"";
        $companyID = element('compID', $this->session->userdata('logged_in'));

        $data['ID'] = $ID;
        $data['supplierID'] = $supplierID;
        $this->lang->load("supplierPaymentForm", $this->session->userdata('language'));
        $this->load->model('supplier/supplierpayment_model');

        $this->load->model('Currency');
        $data['currency'] = $this->Currency->currency_all();

        $this->load->model('supplier/supplier_model');
        $data['supplier'] = $this->supplier_model->suppliermaster_all(); //for combo box
        $rs = $this->supplier_model->suppliermaster_id($supplierID); //for selected supplier
        $data['supplierInfo'] = $rs[0];

        $data['exchangeRate'] = ($supplierID) ? $this->Currency->getConversionRate($rs[0]->currencyID) : '';
        
        $this->load->model('bank/bank_model');
            $data['bankaccount'] = $this->bank_model->bank_all();
            
        $this->load->model('supplier/address_model');
        $data['supplieraddress'] = $this->address_model->address_all();

        $this->load->model('project/project_model');
        $data['project'] = $this->project_model->project_all();

        $this->load->model('master/masterCode_model');
        $filter['masterID'] = 7;
        $data['paymentmethod'] = $this->masterCode_model->get_all($filter);

        $this->load->model('company/formSetup_model');
        $filter['companyID'] = element('compID', $this->session->userdata('logged_in'));
        $filter['formID'] = 44;
        $data['formNo'] = $this->formSetup_model->getFormNo($filter);
        $data['formSerialNo'] = ($ID > 0) ? $this->formSetup_model->getFormSerialNo_zeroLeading($ID) : '';

        $this->load->model('chartofaccount');
        $data['acctNo'] = $this->chartofaccount->chartofaccount_all();

        $this->load->model('accountPayable/AccountPayable_model');
        $rs = $this->AccountPayable_model->get_bySupplierID($data['supplierID'], element('compID', $this->session->userdata('logged_in')));
        //echo $this->db->last_query(); 
        $data['rsPendingInvoice'] = $rs;
        $this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
                ->add_includes('js/validationengine/jquery.validationEngine.js')
                ->add_includes('js/accounting.js');
        $this->layouts->view('ap/transactions/supplierpayment_form', array('latest' => 'sidebar/latest'), $data);
    }

    public function supplierpaymentlist() {
        $this->lang->load("supplierPaymentList", $this->session->userdata('language'));
        $this->load->model('company/FormSetup_model');
        $this->load->model('supplier/SupplierPayment_model');
		$this->load->model('Compfinancialyear');
		$add_year = $this->uri->segment(3);
		$add_period = $this->uri->segment(4);
		if(!$add_year){
			$add_year = date("Y");
			$startDate = date("Y-m-01");
			$endDate = date("Y-m-t");
		}else{
			$query2 = $this->Compfinancialyear->financialYear_yearperiod($add_year, $add_period);
			if($query2){
				$startDate = $query2[0]->startDate;
				$endDate = $query2[0]->endDate;
			}else{
				$startDate = date("Y-m-01");
				$endDate = date("Y-m-t");
			}
		}
		if(!$add_period){
			$add_period = date("m");
		}
		$query = $this->Compfinancialyear->financialYear_year($add_year);
		if($query){
			$data['period'] = $query;
		}else{
			$data['period'] = NULL;
		}
		$data['yrs'] = range(date('Y', strtotime('+2 year')), 1900);
		$data['selyear'] = $add_year;
		$data['selper'] = $add_period;
        $data['datatbls'] = $this->SupplierPayment_model->supplierPaymentDate($startDate,$endDate);

        $this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
        $this->layouts->view('ap/transactions/supplierPaymentList', array('latest' => 'sidebar/latest'), $data);
    }

    public function paymentPosting() {
        $this->lang->load("supplierPaymentList", $this->session->userdata('language'));
        $ID = $this->input->post('fldid');
        $effdate = date("Y-m-d", strtotime($this->input->post('effdate')));
        $this->load->model('supplier/SupplierPayment_model');
        $queryDetails = $this->SupplierPayment_model->supppaymentDetails_ID($ID);
        $data = array(
            'updateAble' => '0'
        );
        $query = $this->SupplierPayment_model->supppaymentDetailspost($ID, $data);
//		var_dump($query);
        if ($query) {
            $this->load->model('Compfinancialyear');
            $query1 = $this->Compfinancialyear->compfinancialyear_date1($effdate);
            if ($query1) {
                $year = $query1[0]->financialYear;
                $period = $query1[0]->period;
                $formNo = $query[0]->formNo . '[' . sprintf('%08d', $query[0]->ID) . ']';
                $total_amount_dr = $query[0]->totalPaid * $query[0]->exchangeRate;
                $total_amount_cr = $query[0]->totalPaid * $query[0]->exchangeRate;
            } else {
                print json_encode(array("status" => "failed", "message" => $query1));
                return FALSE;
            }
            $this->load->model('Glseq');
            $query2 = $this->Glseq->glSequence_sub('3', 'AP', $year, $period);
            $newData = array(
                'companyID' => element('compID', $this->session->userdata('logged_in')),
                'journalID' => $query2['seqNumber'],
                'formNo' => $formNo,
                'description' => $this->lang->line('message2') . ' [ ' . $formNo . ' ]',
                'module' => '3',
                'effective_date' => $effdate,
                'year' => $year,
                'period' => $period,
                'total_amount_dr' => $total_amount_dr,
                'total_amount_cr' => $total_amount_cr,
                'createdBy' => element('role', $this->session->userdata('logged_in'))
            );
            $data = array(
                'journalNo' => $query2['seqNumber']
            );
            $query5 = $this->SupplierPayment_model->supppaymentDetailspost($ID, $data);
            $this->load->model('Journal');
            $query3 = $this->Journal->journal_insert($newData);
            if ($query3) {
                $query4 = $this->SupplierPayment_model->supppaymentDetails_paymentID($query2['seqNumber'], $query[0], $queryDetails, $year, $period);
                print json_encode(array("status" => "success", "message" => $query));
            } else {
                print json_encode(array("status" => "failed", "message" => $query));
            }
        } else {
            return FALSE;
        }
    }

    //Untuk Other Pay With Item Post
    public function otherpaywithItemPost() {
        $this->lang->load("otherspayment", $this->session->userdata('language'));
        $this->load->model('accountPayable/othersPayment_model');
        $this->load->model('company/FormSetup_model');
		$this->load->model('Compfinancialyear');
		$add_year = $this->uri->segment(3);
		$add_period = $this->uri->segment(4);
		if(!$add_year){
			$add_year = date("Y");
			$startDate = date("Y-m-01");
			$endDate = date("Y-m-t");
		}else{
			$query2 = $this->Compfinancialyear->financialYear_yearperiod($add_year, $add_period);
			if($query2){
				$startDate = $query2[0]->startDate;
				$endDate = $query2[0]->endDate;
			}else{
				$startDate = date("Y-m-01");
				$endDate = date("Y-m-t");
			}
		}
		if(!$add_period){
			$add_period = date("m");
		}
		$query = $this->Compfinancialyear->financialYear_year($add_year);
		if($query){
			$data['period'] = $query;
		}else{
			$data['period'] = NULL;
		}
		$data['yrs'] = range(date('Y', strtotime('+2 year')), 1900);
		$data['selyear'] = $add_year;
		$data['selper'] = $add_period;
        $data['datatbls'] = $this->othersPayment_model->otherpaywithitem_unpost($startDate,$endDate);
        $this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
        $this->layouts->view('ap/transactions/otherpaywithItemPost', array('latest' => 'sidebar/latest'), $data);
    }

// Yahaya Abdollah
// Posting and create journal	
    public function otherpaywithItemPosting() {
        $this->lang->load("otherspayment", $this->session->userdata('language'));
        $ID = $this->input->post('fldid');
        $effdate = date("Y-m-d", strtotime($this->input->post('effdate')));
        $this->load->model('accountPayable/othersPayment_model');
        $queryDetails = $this->othersPayment_model->othersPaymentWithItemDetails_ID($ID);
        $data = array(
            'updateAble' => '0'
        );
        $query = $this->othersPayment_model->othersPaymentWithItempost($ID, $data);
        if ($query) {
            $this->load->model('Compfinancialyear');
            $query1 = $this->Compfinancialyear->compfinancialyear_date($effdate);
            echo var_dump($query1);
            if ($query1) {
                $year = $query1[0]->financialYear;
                $period = $query1[0]->period;
                $formNo = $query[0]->formNo . '[' . sprintf('%08d', $query[0]->ID) . ']';
                $total_amount_dr = $query[0]->totalPaid * $query[0]->exchangeRate;
                $total_amount_cr = $query[0]->totalPaid * $query[0]->exchangeRate;
            } else {
                print json_encode(array("status" => "failed", "message" => $query1));
                return FALSE;
            }
            $this->load->model('Glseq');
            $query2 = $this->Glseq->glSequence_sub('3', 'AP', $year, $period);
            $newData = array(
                'companyID' => element('compID', $this->session->userdata('logged_in')),
                'journalID' => $query2['seqNumber'],
                'formNo' => $formNo,
                'description' => $this->lang->line('message2') . ' [ ' . $formNo . ' ]',
                'module' => '3',
                'effective_date' => $effdate,
                'year' => $year,
                'period' => $period,
                'total_amount_dr' => $total_amount_dr,
                'total_amount_cr' => $total_amount_cr,
                'createdBy' => element('role', $this->session->userdata('logged_in'))
            );
            $data = array(
                'journalNo' => $query2['seqNumber']
            );
            $query5 = $this->othersPayment_model->othersPaymentWithItempost($ID, $data);
            $this->load->model('Journal');
            $query3 = $this->Journal->journal_insert($newData);
            if ($query3) {
                $query4 = $this->othersPayment_model->othersPayment_otherPaymentID($query2['seqNumber'], $query[0], $queryDetails, $year, $period);
                print json_encode(array("status" => "success", "message" => $query));
            } else {
                print json_encode(array("status" => "failed", "message" => $query));
            }
        } else {
            return FALSE;
        }
    }

    //Other Pay Without Item Post
    public function otherpaywithoutItemPost() {
        $this->lang->load("otherspayment", $this->session->userdata('language'));
        $this->load->model('accountPayable/othersPayment_model');
        $this->load->model('company/FormSetup_model');
        $dateFrom = date("Y-m-d", strtotime($this->uri->segment(3)));
        $dateTo = date("Y-m-d", strtotime($this->uri->segment(4)));
        if ($this->uri->segment(3) == "") {
            $dateFrom = date("Y-m-01");
        }
        if ($this->uri->segment(4) == "") {
            $dateTo = date("Y-m-t");
        }
        if ($dateFrom > $dateTo) {
            $dateTo = date("Y-m-t", strtotime($dateFrom));
        }
        $data['dateFrom'] = $dateFrom;
        $data['dateTo'] = $dateTo;
        $data['datatbls'] = $this->othersPayment_model->otherpaywithoutitem_unpost($dateFrom, $dateTo);
        $this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
        $this->layouts->view('ap/transactions/otherpaywithoutItemPost', array('latest' => 'sidebar/latest'), $data);
    }

// Debit note start
// Created By Eisa
// Updated By Farhana - Confirm & List


    public function newDebitNote() {
        $this->load->model('company/formSetup_Model');
        $filter['companyID'] = element('compID', $this->session->userdata('logged_in'));
        $filter['formID'] = 41;
        $data['formNo'] = $this->formSetup_Model->getFormNo($filter);
        $this->lang->load("invoices", $this->session->userdata('language'));
        $this->load->model('companyChartAcct');

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();


        $this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
                ->add_includes('js/accounting.js')
                ->add_includes('js/validationengine/jquery.validationEngine.js');

        $this->load->model('Supplier/supplier_model');
        $data['supplier'] = $this->supplier_model->suppliermaster_allopt();

        $this->load->model('Project/project_model');
        $data['project'] = $this->project_model->project_all();

        $this->load->model('Terms/terms_model');
        $data['terms'] = $this->terms_model->terms_all();

        $this->load->model('location');
        $data['location'] = $this->location->location_all();

        $this->load->model('companyChartAcct');
        $data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();

        $this->load->model('taxmaster');
        $data['taxmaster'] = $this->taxmaster->taxmaster_all();

        $this->load->model('item/itemSetup_model');
        $data['items'] = $this->itemSetup_model->get_all();

        $this->load->model('company/formSetup_Model');
        $filter['companyID'] = element('compID', $this->session->userdata('logged_in'));
        $filter['formID'] = 42;
        $data['formNo'] = $this->formSetup_Model->getFormNo($filter);

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();

        $this->layouts->view('ap/transactions/ap_newDebitNote', '', $data);
    }

    public function saveNewCreditChargeDetail() {
        $this->load->model('accountPayable/accountPayable_model');
        $datinsertDetails = array(
            'creditNoteID' => $this->input->post('invoiceId'),
            'lineNo' => $this->input->post('lineNo'),
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'accountNoID' => $this->input->post('accountNoID'),
            'itemdescription' => $this->input->post('itemdescription'),
            'amountExcludedTax' => $this->input->post('amountExcludedTax'),
            'taxID' => $this->input->post('taxID'),
            'taxAmount' => $this->input->post('taxAmount'),
            'amountIncludedTax' => $this->input->post('amountIncludedTax'),
        );
        $detail = $this->accountPayable_model->insert('comp_supplier_creditnote_charges', $datinsertDetails);
       $this->accountPayable_model->updateMaster("comp_supplier_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        /* $dataUp = array("totalPayable" => $this->input->post('totalPayable'),
            "totalTaxAmount" => $this->input->post('totalTaxAmount'),
            "totalAmount" => $this->input->post('totalAmount'));
        $this->accountPayable_model->update_byTname("comp_supplier_creditnote", $this->input->post('invoiceId'), $dataUp);
        */
        echo '{"status":"success","chargeId":"' . $detail . '"}';
    }

    public function saveNewDebitChargeDetail() {
        $this->load->model('accountPayable/accountPayable_model');
        $datinsertDetails = array(
            'debitNoteID' => $this->input->post('invoiceId'),
            'lineNo' => $this->input->post('lineNo'),
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'accountNoID' => $this->input->post('accountNoID'),
            'itemdescription' => $this->input->post('itemdescription'),
            'amountExcludedTax' => $this->input->post('amountExcludedTax'),
            'taxID' => $this->input->post('taxID'),
            'taxAmount' => $this->input->post('taxAmount'),
            'amountIncludedTax' => $this->input->post('amountIncludedTax'),
        );
        $detail = $this->accountPayable_model->insert('comp_supplier_debitnote_charges', $datinsertDetails);
     /*  $dataUp = array("totalPayable" => $this->input->post('totalPayable'),
            "totalTaxAmount" => $this->input->post('totalTaxAmount'),
            "totalAmount" => $this->input->post('totalAmount'));
        $this->accountPayable_model->update_byTname("comp_supplier_debitnote", $this->input->post('invoiceId'), $dataUp);
        */
        $this->accountPayable_model->updateMaster("comp_supplier_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        echo '{"status":"success","chargeId":"' . $detail . '"}';
    }

    public function saveNewParchaseChargeDebit() {
        $this->load->model('accountPayable/accountPayable_model');

        $ID = $this->input->post('ID');
        $companyID = element('compID', $this->session->userdata('logged_in'));
        $datinsert = array(
            'companyID' => $companyID,
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'supplierID' => $this->input->post('supplierID'),
            'formNo' => $this->input->post('formNo'),
            'memo' => $this->input->post('memo'),
            'debitNoteDate' => date('Y-m-d', strtotime($this->input->post('invoiceDate'))),
            'supplierInvoiceID' => $this->input->post('supplierInvoiceID'),
            'projectID' => $this->input->post('projectID'),
            'currencyID' => $this->input->post('currencyID'),
            'exchangeRate' => $this->input->post('exchangeRate'),
            'totalAmount' => $this->input->post('amountExcludedTax'),
            'totalTaxAmount' => $this->input->post('taxAmount'),
            'totalPayable' => $this->input->post('amountIncludedTax')
        );


        $debitNoteID = $this->accountPayable_model->insert("comp_supplier_debitnote", $datinsert);


        if ($debitNoteID > 0) {
            $datinsertDetails = array(
                'debitNoteID' => $debitNoteID,
                'createdBy' => element('role', $this->session->userdata('logged_in')),
                'accountNoID' => $this->input->post('accountNoID'),
                'lineNo' => $this->input->post('lineNo'),
                'itemdescription' => $this->input->post('itemdescription'),
                'amountExcludedTax' => $this->input->post('amountExcludedTax'),
                'taxID' => $this->input->post('taxID'),
                'taxAmount' => $this->input->post('taxAmount'),
                'amountIncludedTax' => $this->input->post('amountIncludedTax'),
            );
            $detail = $this->accountPayable_model->insert('comp_supplier_debitnote_charges', $datinsertDetails);
            $this->accountPayable_model->updateMaster("comp_supplier_debitnote",array("totalTaxAmount","totalAmount"), $debitNoteID);
// $detail = $this->accountPayable_model->getLasIdInsert("comp_supplier_invoice_charges");
            echo '{"status":"success","invoiceID":"' . $debitNoteID . '","chargeId":"' . $detail . '"}';
        } else {
            echo "false";
        }
    }

    function saveNewParchaseDebit() {
        $this->load->model('accountPayable/accountPayable_model');

        $ID = $this->input->post('ID');
        $companyID = element('compID', $this->session->userdata('logged_in'));
        $datinsert = array(
            'companyID' => $companyID,
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'supplierID' => $this->input->post('supplierID'),
            'formNo' => $this->input->post('formNo'),
            'memo' => $this->input->post('memo'),
            'debitNoteDate' => date('Y-m-d', strtotime($this->input->post('invoiceDate'))),
            'supplierInvoiceID' => $this->input->post('supplierInvoiceID'),
            'projectID' => $this->input->post('projectID'),
            'currencyID' => $this->input->post('currencyID'),
            'exchangeRate' => $this->input->post('exchangeRate'),
            'totalAmount' => $this->input->post('amountExcludedTax'),
            'totalTaxAmount' => $this->input->post('taxAmount'),
            'totalPayable' => $this->input->post('amountIncludedTax')
        );


        $invID = $this->accountPayable_model->insert("comp_supplier_debitnote", $datinsert);


        if ($invID > 0) {

            //				$invID=$this->accountPayable_model->getLasIdInsert("comp_supplier_debitnote");
            $datinsertDetails = array(
                'debitnoteID' => $invID,
                'createdBy' => element('role', $this->session->userdata('logged_in')),
                'itemID' => $this->input->post('itemID'),
                'itemdescription' => $this->input->post('itemdescription'),
                'quantity' => $this->input->post('quantity'),
                'unitPrice' => $this->input->post('unitPrice'),
                'amountExcludedTax' => $this->input->post('amountExcludedTax'),
                'amountIncludedTax' => $this->input->post('amountIncludedTax'),
                'taxID' => $this->input->post('taxID'),
                'lineNo' => $this->input->post('lineNo'),
                'taxRate' => $this->input->post('taxRate'),
                'taxAmount' => $this->input->post('taxAmount')
            );
            $detail = $this->accountPayable_model->insert('comp_supplier_debitnote_detail', $datinsertDetails);
            $this->accountPayable_model->updateMaster("comp_supplier_debitnote",array("totalTaxAmount","totalAmount"), $invID);
            
            echo '{"status":"success","invoiceID":"' . $invID . '","detailID":"' . $detail . '"}';
        } else {
            echo "false";
        }
    }

    function saveParchaseDetail() {
        $this->load->model('item/itemSetup_model');
        $default = $this->itemSetup_model->get_byCode($this->input->post('itemCode'));
        $itemId = "0";
        if ($default) {
            foreach ($default as $row)
                $itemId = $row->ID;
        }

        $this->load->model('accountPayable/accountPayable_model');
        $datinsertDetails = array(
            'invoiceID' => $this->input->post('invoiceId'),
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'itemname' => $this->input->post('itemname'),
            'itemID' => $this->input->post('itemID'),
            'itemdescription' => $this->input->post('itemdescription'),
            'quantity' => $this->input->post('quantity'),
            'unitPrice' => $this->input->post('unitPrice'),
            'amountExcludedTax' => $this->input->post('amountExcludedTax'),
            'amountIncludedTax' => $this->input->post('amountIncludedTax'),
            'taxID' => $this->input->post('taxID'),
            'taxRate' => $this->input->post('taxRate'),
            'taxAmount' => $this->input->post('taxAmount')
        );
        $query = $this->accountPayable_model->insert('comp_supplier_invoice_detail', $datinsertDetails);
        $detail = $this->accountPayable_model->getLasIdInsert("comp_supplier_invoice_detail");
        echo '{"status":"success","detailID":"' . $detail . '"}';
    }

    function saveNewDebitDetail() {

        $this->load->model('accountPayable/accountPayable_model');
        $datinsertDetails = array(
            'debitnoteID' => $this->input->post('invoiceId'),
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'itemID' => $this->input->post('itemID'),
            'itemdescription' => $this->input->post('itemdescription'),
            'quantity' => $this->input->post('quantity'),
            'unitPrice' => $this->input->post('unitPrice'),
            'amountExcludedTax' => $this->input->post('amountExcludedTax'),
            'amountIncludedTax' => $this->input->post('amountIncludedTax'),
            'taxID' => $this->input->post('taxID'),
            'lineNo' => $this->input->post('lineNo'),
            'taxRate' => $this->input->post('taxRate'),
            'taxAmount' => $this->input->post('taxAmount')
        );
        $query = $this->accountPayable_model->insert('comp_supplier_debitnote_detail', $datinsertDetails);
      //  $this->accountPayable_model->update_byTname("comp_supplier_debitnote", $this->input->post('invoiceId'), array("totalPayable" => $this->input->post('totalPayable')));
        $this->accountPayable_model->updateMaster("comp_supplier_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        
        echo '{"status":"success","detailID":"' . $query . '"}';
    }

    public function deleteCompanyDetails() {
        $this->load->model('accountPayable/accountPayable_model');
        $this->accountPayable_model->delete($this->input->post('invDetailsId'), 'comp_supplier_invoice_detail');
        $this->accountPayable_model->updateMaster("comp_supplier_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        echo "ok";
    }

    public function deleteDebitNoteDetail() {
        $this->load->model('accountPayable/accountPayable_model');
        $this->accountPayable_model->delete($this->input->post('invDetailsId'), 'comp_supplier_debitnote_detail');
        $this->accountPayable_model->updateMaster("comp_supplier_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        echo "ok";
    }

    function checkformNumber() {
        $this->load->model('accountPayable/accountPayable_model');
        echo $this->accountPayable_model->checkformNumber_model("comp_supplier_debitnote", $this->input->post('code'));
    }

    public function updateRowDetailDebitNote() {

        $this->load->model('accountPayable/accountPayable_model');
        $data = array(
            'updatedBy' => element('role', $this->session->userdata('logged_in')),
            'itemID' => $this->input->post('itemId'),
            'itemdescription' => $this->input->post('itemdescription'),
            'quantity' => $this->input->post('quantity'),
            'unitPrice' => $this->input->post('unitPrice'),
            'amountExcludedTax' => $this->input->post('amountExcludedTax'),
            'taxID' => $this->input->post('taxID'),
            'taxRate' => $this->input->post('taxRate'),
            'taxAmount' => $this->input->post('taxAmount'),
            'amountIncludedTax' => $this->input->post('amountIncludedTax')
        );
        echo $this->accountPayable_model->update_debitNoteDetail($this->input->post('invDetailsId'), $data);
        $this->accountPayable_model->updateMaster("comp_supplier_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
    }

    // edit of debit note
    public function editDebitNote($id) {
        $this->load->model('company/formSetup_Model');
        $filter['companyID'] = element('compID', $this->session->userdata('logged_in'));


        $this->lang->load("invoices", $this->session->userdata('language'));
        $this->load->model('companyChartAcct');

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();
        $this->load->library('layouts');
        $this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
                ->add_includes('js/accounting.js')
                ->add_includes('js/validationengine/jquery.validationEngine.js');

        $this->lang->load("ap_edit", $this->session->userdata('language'));

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();

        $this->load->model('item/itemSetup_model');
        $data['items'] = $this->itemSetup_model->get_all();

        $this->load->model('taxmaster');
        $data['taxmaster'] = $this->taxmaster->taxmaster_all();
        
         $this->load->model('companyChartAcct');
        $data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();


        $this->load->model('accountPayable/accountPayable_model');
        $data['pdetails'] = $this->accountPayable_model->get_DebitNoteDetail_byID($id);

        $data['pInvoice'] = $this->accountPayable_model->get_byID("comp_supplier_debitnote", $id);
        
        $data['charge'] = $this->accountPayable_model->getDebitNoteChargeByid($id);


        $this->layouts->view('ap/transactions/ap_debitNoteEdit', '', $data);
    }

    public function printDebitNote($id) {
        $this->load->model('company/FormSetup_model');
        $filter['companyID'] = element('compID', $this->session->userdata('logged_in'));


        $this->lang->load("debitNotePrint", $this->session->userdata('language'));
        $this->load->model('companyChartAcct');

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();
        $this->load->library('layouts');
        $this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
                ->add_includes('js/validationengine/jquery.validationEngine.js');

        $this->lang->load("ap_edit", $this->session->userdata('language'));

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();

        $data['itemCodes'] = $this->getItemCodes();

        $this->load->model('taxmaster');
        $data['taxmaster'] = $this->taxmaster->taxmaster_all();

        $this->load->model('accountPayable/accountPayable_model');
        $data['pdetails'] = $this->accountPayable_model->get_DebitNoteDetail_byID($id);

        $this->load->model('company/Company_info_model');
        $query = $this->Company_info_model->companymaster_id(element('compID', $this->session->userdata('logged_in')));
        $data['companyInfo'] = $query[0];

        $query2 = $this->accountPayable_model->get_rpt_byID("comp_supplier_debitnote", $id);
        $data['debitNote'] = $query2[0];
        if ($query2) {
            $query3 = $this->accountPayable_model->get_rpt_byID("comp_supplier_invoice", $query2[0]->supplierInvoiceID);
            $data['pInvoice'] = $query3[0];
        } else
            $data['pInvoice'] = '';

        //var_dump($query3);
        $this->load->view('ap/reports/debitnote', $data);
    }

    public function printCreditNote($id) {
        $this->load->model('company/FormSetup_model');
        $filter['companyID'] = element('compID', $this->session->userdata('logged_in'));


        $this->lang->load("creditNotePrint", $this->session->userdata('language'));
        $this->load->model('companyChartAcct');

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();
        $this->load->library('layouts');
        $this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
                ->add_includes('js/validationengine/jquery.validationEngine.js');

        $this->lang->load("ap_edit", $this->session->userdata('language'));

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();

        $data['itemCodes'] = $this->getItemCodes();

        $this->load->model('taxmaster');
        $data['taxmaster'] = $this->taxmaster->taxmaster_all();

        $this->load->model('accountPayable/accountPayable_model');
        $data['pdetails'] = $this->accountPayable_model->getCrditNotDetailById($id);

        $this->load->model('company/Company_info_model');
        $query = $this->Company_info_model->companymaster_id(element('compID', $this->session->userdata('logged_in')));
        $data['companyInfo'] = $query[0];

        $query2 = $this->accountPayable_model->get_rpt_byID("comp_supplier_creditnote", $id);
        $data['creditNote'] = $query2[0];
        if ($query2) {
            $query3 = $this->accountPayable_model->get_rpt_byID("comp_supplier_invoice", $query2[0]->supplierInvoiceID);
            $data['pInvoice'] = $query3[0];
        } else
            $data['pInvoice'] = '';

        //var_dump($query3);
        $this->load->view('ap/reports/creditnote', $data);
    }

    function deleteCompanyDetail() {
        $this->load->model('accountPayable/accountPayable_model');
        echo $this->accountPayable_model->deleteCompanyDetail($this->input->post('detailsId'));
    }
   
    /*
    private function getItemCodes() {
        $JsonRecords = '[';
        $i = 0;
        $this->load->model('item/itemSetup_model');
        //$default = $this->itemSetup_model->get_byCode($this->input->post('itemCode'));
        $default = $this->itemSetup_model->get_all();
        $n = sizeof($default);
        if ($default)
            foreach ($default as $row) {
                $JsonRecords .= '&quot;' . $row->itemCode . '&quot;';
                if ($i < $n - 1)
                    $JsonRecords .= ',';
                $i++;
            }
        $JsonRecords .= ']';
        return $JsonRecords;
    } */

    public function debitnotePost() {
        $this->lang->load("debitNote", $this->session->userdata('language'));
        $this->load->model('debitnote_model');
        $this->load->model('company/FormSetup_model');
		$this->load->model('Compfinancialyear');
		$add_year = $this->uri->segment(3);
		$add_period = $this->uri->segment(4);
		if(!$add_year){
			$add_year = date("Y");
			$startDate = date("Y-m-01");
			$endDate = date("Y-m-t");
		}else{
			$query2 = $this->Compfinancialyear->financialYear_yearperiod($add_year, $add_period);
			if($query2){
				$startDate = $query2[0]->startDate;
				$endDate = $query2[0]->endDate;
			}else{
				$startDate = date("Y-m-01");
				$endDate = date("Y-m-t");
			}
		}
		if(!$add_period){
			$add_period = date("m");
		}
		$query = $this->Compfinancialyear->financialYear_year($add_year);
		if($query){
			$data['period'] = $query;
		}else{
			$data['period'] = NULL;
		}
		$data['yrs'] = range(date('Y', strtotime('+2 year')), 1900);
		$data['selyear'] = $add_year;
		$data['selper'] = $add_period;
        $data['datatbls'] = $this->debitnote_model->debitnote_unpost($startDate,$endDate);
        $this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
        $this->layouts->view('ap/transactions/debitnotePost', array('latest' => 'sidebar/latest'), $data);
    }

    public function debitNotePosting() {
        $this->lang->load("debitNote", $this->session->userdata('language'));
        $ID = $this->input->post('fldid');
        $effdate = date("Y-m-d", strtotime($this->input->post('effdate')));
        $this->load->model('debitnote_model');
        $queryDetails = $this->debitnote_model->debitNoteDetails_ID($ID);
        $data = array(
            'updateAble' => '0'
        );
        $query = $this->debitnote_model->debitNotepost($ID, $data);
//		var_dump($query);
        if ($query) {
            $this->load->model('Compfinancialyear');
            $query1 = $this->Compfinancialyear->compfinancialyear_date1($effdate);
            if ($query1) {
                $year = $query1[0]->financialYear;
                $period = $query1[0]->period;
                $formNo = $query[0]->formNo . '[' . sprintf('%08d', $query[0]->ID) . ']';
                $total_amount_dr = $query[0]->totalAmount * $query[0]->exchangeRate;
                $total_amount_cr = $query[0]->totalAmount * $query[0]->exchangeRate;
            } else {
                print json_encode(array("status" => "failed", "message" => $query1));
                return FALSE;
            }
            $this->load->model('Glseq');
            $query2 = $this->Glseq->glSequence_sub('3', 'AP', $year, $period);
            $newData = array(
                'companyID' => element('compID', $this->session->userdata('logged_in')),
                'journalID' => $query2['seqNumber'],
                'formNo' => $formNo,
                'description' => $this->lang->line('message2') . ' [ ' . $formNo . ' ]',
                'module' => '3',
                'effective_date' => $effdate,
                'year' => $year,
                'period' => $period,
                'total_amount_dr' => $total_amount_dr,
                'total_amount_cr' => $total_amount_cr,
                'createdBy' => element('role', $this->session->userdata('logged_in'))
            );
            $data = array(
                'journalNo' => $query2['seqNumber']
            );
            $query5 = $this->debitnote_model->debitNotepost($ID, $data);
            $this->load->model('Journal');
            $query3 = $this->Journal->journal_insert($newData);
            if ($query3) {
                $query4 = $this->debitnote_model->debitnotedetails_debitnoteID($query2['seqNumber'], $query[0], $queryDetails, $year, $period);
                print json_encode(array("status" => "success", "message" => $query));
            } else {
                print json_encode(array("status" => "failed", "message" => $query));
            }
        } else {
            return FALSE;
        }
    }

// Debit Note List Print/Excel - Farhana

    public function dbnList_print() {
        $mode = $this->uri->segment(3);
        $this->load->library('layouts');
        $this->lang->load("debitNote", $this->session->userdata('language'));
        $this->load->model('debitnote_model');
        $this->load->model('company/FormSetup_model');

        $data['mode'] = $mode;
        $dateFrom = date("Y-m-d", strtotime($this->uri->segment(3)));
        $dateTo = date("Y-m-d", strtotime($this->uri->segment(4)));
        if ($this->uri->segment(3) == "") {
            $dateFrom = date("Y-m-01");
        }
        if ($this->uri->segment(4) == "") {
            $dateTo = date("Y-m-t");
        }
        if ($dateFrom > $dateTo) {
            $dateTo = date("Y-m-t", strtotime($dateFrom));
        }

        $ID = $this->input->post('ID');
        $query = $this->debitnote_model->updatePosting($ID);

        $data['dateFrom'] = $dateFrom;
        $data['dateTo'] = $dateTo;
        $data['datatbls'] = $this->debitnote_model->debitnote_Date($dateFrom, $dateTo);

        //		echo $this->db->last_query();
        $this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
        $this->load->view('ap/transactions/debitnoteList_print', $data);
    }

    public function dbnlist_excel() {
        $this->load->library('parser');
        $mode = $this->uri->segment(3);
        $this->load->library('layouts');
        $this->lang->load("debitNote", $this->session->userdata('language'));
        $this->load->model('debitnote_model');
        $this->load->model('company/FormSetup_model');

        $data['mode'] = $mode;

        $dateFrom = date("Y-m-d", strtotime($this->uri->segment(3)));
        $dateTo = date("Y-m-d", strtotime($this->uri->segment(4)));
        if ($this->uri->segment(3) == "") {
            $dateFrom = date("Y-m-01");
        }
        if ($this->uri->segment(4) == "") {
            $dateTo = date("Y-m-t");
        }
        if ($dateFrom > $dateTo) {
            $dateTo = date("Y-m-t", strtotime($dateFrom));
        }

        $ID = $this->input->post('ID');
        $query = $this->debitnote_model->updatePosting($ID);

        $data['dateFrom'] = $dateFrom;
        $data['dateTo'] = $dateTo;
        $data['datatbls'] = $this->debitnote_model->debitnote_Date($dateFrom, $dateTo);

        $myFile = "Debit_Note_List.xls";

        //pass retrieved data into template and return as a string
        $stringData = $this->parser->parse('ap/transactions/debitnoteList_excel', $data, true);

        //open excel and write string into excel
        $fh = fopen($myFile, 'w') or die("can't open file");
        fwrite($fh, $stringData);

        fclose($fh);
        //download excel file
        $this->downloadExcel($myFile);
    }

// Debit Note end	
// Credit Note start	
// Created By Farhana
    public function creditnotePost() {
        $this->lang->load("creditNote", $this->session->userdata('language'));
        $this->load->model('creditnote_model');
        $this->load->model('company/FormSetup_model');
		$this->load->model('Compfinancialyear');
		$add_year = $this->uri->segment(3);
		$add_period = $this->uri->segment(4);
		if(!$add_year){
			$add_year = date("Y");
			$startDate = date("Y-m-01");
			$endDate = date("Y-m-t");
		}else{
			$query2 = $this->Compfinancialyear->financialYear_yearperiod($add_year, $add_period);
			if($query2){
				$startDate = $query2[0]->startDate;
				$endDate = $query2[0]->endDate;
			}else{
				$startDate = date("Y-m-01");
				$endDate = date("Y-m-t");
			}
		}
		if(!$add_period){
			$add_period = date("m");
		}
		$query = $this->Compfinancialyear->financialYear_year($add_year);
		if($query){
			$data['period'] = $query;
		}else{
			$data['period'] = NULL;
		}
		$data['yrs'] = range(date('Y', strtotime('+2 year')), 1900);
		$data['selyear'] = $add_year;
		$data['selper'] = $add_period;
        $data['datatbls'] = $this->creditnote_model->creditnote_unpost($startDate,$endDate);
        $this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
        $this->layouts->view('ap/transactions/creditnotePost', array('latest' => 'sidebar/latest'), $data);
    }

    public function creditNotePosting() {
        $this->lang->load("creditNote", $this->session->userdata('language'));
        $ID = $this->input->post('fldid');
        $effdate = date("Y-m-d", strtotime($this->input->post('effdate')));
        $this->load->model('creditnote_model');
        $queryDetails = $this->creditnote_model->creditNoteDetails_ID($ID);
        $data = array(
            'updateAble' => '0'
        );
        $query = $this->creditnote_model->creditNotepost($ID, $data);
        if ($query) {
            $this->load->model('Compfinancialyear');
            $query1 = $this->Compfinancialyear->compfinancialyear_date1($effdate);
            if ($query1) {
                $year = $query1[0]->financialYear;
                $period = $query1[0]->period;
                $formNo = $query[0]->formNo . '[' . sprintf('%08d', $query[0]->ID) . ']';
                $total_amount_dr = $query[0]->totalAmount * $query[0]->exchangeRate;
                $total_amount_cr = $query[0]->totalAmount * $query[0]->exchangeRate;
            } else {
                print json_encode(array("status" => "failed", "message" => $query1));
                return FALSE;
            }
            $this->load->model('Glseq');
            $query2 = $this->Glseq->glSequence_sub('3', 'AP', $year, $period);
            $newData = array(
                'companyID' => element('compID', $this->session->userdata('logged_in')),
                'journalID' => $query2['seqNumber'],
                'description' => $this->lang->line('message2') . ' [ ' . $formNo . ' ]',
                'formNo' => $formNo,
                'total_amount_dr' => $total_amount_dr,
                'total_amount_cr' => $total_amount_cr,
                'module' => '3',
                'effective_date' => $effdate,
                'year' => $year,
                'period' => $period,
                'createdBy' => element('role', $this->session->userdata('logged_in'))
            );
            $data = array(
                'journalNo' => $query2['seqNumber']
            );
            $query5 = $this->creditnote_model->creditNotepost($ID, $data);
            $this->load->model('Journal');
            $query3 = $this->Journal->journal_insert($newData);
            if ($query3) {
                $query4 = $this->creditnote_model->creditnotedetails_creditnoteID($query2['seqNumber'], $query[0], $queryDetails, $year, $period);
                print json_encode(array("status" => "success", "message" => $query));
            } else {
                print json_encode(array("status" => "failed", "message" => $query));
            }
        } else {
            return FALSE;
        }
    }

    //Added by Issa

    public function newCreditNote() {
        $this->load->model('company/formSetup_Model');
        $filter['companyID'] = element('compID', $this->session->userdata('logged_in'));
        $filter['formID'] = 41;
        $data['formNo'] = $this->formSetup_Model->getFormNo($filter);
        $this->lang->load("invoices", $this->session->userdata('language'));
        $this->load->model('companyChartAcct');

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();


        $this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
                ->add_includes('js/accounting.js')
                ->add_includes('js/validationengine/jquery.validationEngine.js');

        $this->load->model('Supplier/supplier_model');
        $data['supplier'] = $this->supplier_model->suppliermaster_all();

        $this->load->model('Project/project_model');
        $data['project'] = $this->project_model->project_all();

        $this->load->model('Terms/terms_model');
        $data['terms'] = $this->terms_model->terms_all();

        $this->load->model('location');
        $data['location'] = $this->location->location_all();

        $this->load->model('companyChartAcct');
        $data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();


        $this->load->model('taxmaster');
        $data['taxmaster'] = $this->taxmaster->taxmaster_all();

        $this->load->model('item/itemSetup_model');
        $data['items'] = $this->itemSetup_model->get_all();

        $this->load->model('company/formSetup_Model');
        $filter['companyID'] = element('compID', $this->session->userdata('logged_in'));
        $filter['formID'] = 43;
        $data['formNo'] = $this->formSetup_Model->getFormNo($filter);

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();

        $this->layouts->view('ap/transactions/ap_newCreditNote', '', $data);
    }
    

    public function editCreditNote($id) {
        $this->load->model('company/formSetup_Model');
        $filter['companyID'] = element('compID', $this->session->userdata('logged_in'));

        $this->lang->load("invoices", $this->session->userdata('language'));
        $this->load->model('companyChartAcct');

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();
        $this->load->library('layouts');
        $this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
                ->add_includes('js/validationengine/jquery.validationEngine.js')
                ->add_includes('js/accounting.js');

        $this->lang->load("ap_edit", $this->session->userdata('language'));

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();

        //$data['itemCodes'] = $this->getItemCodes();
        
        $this->load->model('item/itemSetup_model');
        $data['items'] = $this->itemSetup_model->get_all();
        
        $this->load->model('companyChartAcct');
        $data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();

        $this->load->model('taxmaster');
        $data['taxmaster'] = $this->taxmaster->taxmaster_all();

        $this->load->model('accountPayable/accountPayable_model');
        $data['charge'] = $this->accountPayable_model->getCreditNoteChargeByid($id);
        $data['pInvoice'] = $this->accountPayable_model->get_byID("comp_supplier_creditnote", $id);
        $data['pdetails'] = $this->accountPayable_model->getCrditNotDetailById($id);

        $this->layouts->view('ap/transactions/ap_creditNoteEdit', '', $data);
    }

    public function updateRowDetailCreditNote() {
        $this->load->model('accountPayable/accountPayable_model');
        $data = array(
            'itemID' => $this->input->post('itemId'),
            'updatedBy' => element('role', $this->session->userdata('logged_in')),
            'itemdescription' => $this->input->post('itemdescription'),
            'quantity' => $this->input->post('quantity'),
            'unitPrice' => $this->input->post('unitPrice'),
            'amountExcludedTax' => $this->input->post('amountExcludedTax'),
            'taxID' => $this->input->post('taxID'),
            'taxRate' => $this->input->post('taxRate'),
            'taxAmount' => $this->input->post('taxAmount'),
            'amountIncludedTax' => $this->input->post('amountIncludedTax')
        );
        echo $this->accountPayable_model->update_CreditNoteDetail($this->input->post('invDetailsId'), $data);
    }

    function saveNewParchaseChargeCredit() {
        $this->load->model('accountPayable/accountPayable_model');

        $ID = $this->input->post('ID');
        $companyID = element('compID', $this->session->userdata('logged_in'));
        $datinsert = array(
            'companyID' => $companyID,
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'supplierID' => $this->input->post('supplierID'),
            'formNo' => $this->input->post('formNo'),
            'memo' => $this->input->post('memo'),
            'creditNoteDate' => date('Y-m-d', strtotime($this->input->post('invoiceDate'))),
            'supplierInvoiceID' => $this->input->post('supplierInvoiceID'),
            'projectID' => $this->input->post('projectID'),
            'exchangeRate' => $this->input->post('exchangeRate')
        );



        $credNoteID = $this->accountPayable_model->insert("comp_supplier_creditnote", $datinsert);


        if ($credNoteID > 0) {
            $datinsertDetails = array(
                'creditNoteID' => $credNoteID,
                'createdBy' => element('role', $this->session->userdata('logged_in')),
                'accountNoID' => $this->input->post('accountNoID'),
                'lineNo' => $this->input->post('lineNo'),
                'itemdescription' => $this->input->post('itemdescription'),
                'amountExcludedTax' => $this->input->post('amountExcludedTax'),
                'taxID' => $this->input->post('taxID'),
                'taxAmount' => $this->input->post('taxAmount'),
                'amountIncludedTax' => $this->input->post('amountIncludedTax'),
            );
            $detail = $this->accountPayable_model->insert('comp_supplier_creditnote_charges', $datinsertDetails);
            $this->accountPayable_model->updateMaster("comp_supplier_creditnote",array("totalTaxAmount","totalAmount"), $credNoteID);
            // $detail = $this->accountPayable_model->getLasIdInsert("comp_supplier_invoice_charges");
            echo '{"status":"success","invoiceID":"' . $credNoteID . '","chargeId":"' . $detail . '"}';
        } else {
            echo "false";
        }
    }

    function saveNewParchaseCredit() {
        $this->load->model('accountPayable/accountPayable_model');

        $ID = $this->input->post('ID');
        $companyID = element('compID', $this->session->userdata('logged_in'));
        $datinsert = array(
            'companyID' => $companyID,
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'supplierID' => $this->input->post('supplierID'),
            'formNo' => $this->input->post('formNo'),
            'memo' => $this->input->post('memo'),
            'creditNoteDate' => date('Y-m-d', strtotime($this->input->post('invoiceDate'))),
            'supplierInvoiceID' => $this->input->post('supplierInvoiceID'),
            'projectID' => $this->input->post('projectID'),
            'exchangeRate' => $this->input->post('exchangeRate'),
            'totalAmount' => $this->input->post('amountExcludedTax'),
            'totalTaxAmount' => $this->input->post('taxAmount'),
            'totalPayable' => $this->input->post('amountIncludedTax')
        );


        $invID = $this->accountPayable_model->insert("comp_supplier_creditnote", $datinsert);


        if ($invID > 0) {

            $query = $this->accountPayable_model->getLasIdInsert("comp_supplier_creditnote");
            $datinsertDetails = array(
                'creditnoteID' => $invID,
                'createdBy' => element('role', $this->session->userdata('logged_in')),
                'itemId' => $this->input->post('itemId'),
                'itemname' => $this->input->post('itemname'),
                'itemdescription' => $this->input->post('itemdescription'),
                'quantity' => $this->input->post('quantity'),
                'unitPrice' => $this->input->post('unitPrice'),
                'lineNo' => $this->input->post('lineNo'),
                'amountExcludedTax' => $this->input->post('amountExcludedTax'),
                'taxID' => $this->input->post('taxID'),
                'taxRate' => $this->input->post('taxRate'),
                'taxAmount' => $this->input->post('taxAmount'),
                'amountIncludedTax' => $this->input->post('amountIncludedTax')
            );
            $detail = $this->accountPayable_model->insert('comp_supplier_creditnote_detail', $datinsertDetails);
            $this->accountPayable_model->updateMaster("comp_supplier_creditnote",array("totalTaxAmount","totalAmount"), $invID);
            echo '{"status":"success","invoiceID":"' . $invID . '","detailID":"' . $detail . '"}';
        } else {
            echo "false";
        }
    }
    
   function editPayment($id){
        
        
        $this->lang->load("supplierPaymentForm", $this->session->userdata('language'));
        
        $this->load->model('supplier/supplierPayment_model'); 
        $data['master']=$this->supplierPayment_model->supplierPaymentGetMaster($id);
        $data['details']=$this->supplierPayment_model->supplierPaymentGetDetail($id);
        
        $this->layouts->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
                ->add_includes('js/validationengine/jquery.validationEngine.js')
                ->add_includes('js/accounting.js');
        $this->layouts->view('ap/transactions/editPayment', array('latest' => 'sidebar/latest'), $data);
    }

    function deleteCompanyDetailsCreditNote() {
        $this->load->model('accountPayable/accountPayable_model');
        echo $this->accountPayable_model->delete($this->input->post('invDetailsId'),"comp_supplier_creditnote_detail");
       $this->accountPayable_model->updateMaster("comp_supplier_creditnote",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        
    }

    function saveParchaseCreditDetail() {
        $this->load->model('accountPayable/accountPayable_model');
        $datinsertDetails = array(
            'creditnoteID' => $this->input->post('invoiceId'),
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'itemID' => $this->input->post('itemId'),
            'lineNo' => $this->input->post('lineNo'),
            'itemdescription' => $this->input->post('itemdescription'),
            'quantity' => $this->input->post('quantity'),
            'unitPrice' => $this->input->post('unitPrice'),
            'amountExcludedTax' => $this->input->post('amountExcludedTax'),
            'taxID' => $this->input->post('taxID'),
            'taxRate' => $this->input->post('taxRate'),
            'taxAmount' => $this->input->post('taxAmount'),
            'amountIncludedTax' => $this->input->post('amountIncludedTax')
        );
        $query = $this->accountPayable_model->insert('comp_supplier_creditnote_detail', $datinsertDetails);
       /* $data = array (
            'totalPayable' => $this->input->post('totalPayable'),
            'totalTaxAmount' => $this->input->post('totalTaxAmount'),
            'totalAmount' => $this->input->post('totalAmount')
        ); */
        $this->accountPayable_model->updateMaster("comp_supplier_creditnote",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        
       // $detail = $this->accountPayable_model->getLasIdInsert("comp_supplier_creditnote_detail");
        echo '{"status":"success","detailID":"' . $query . '"}';
    }

    /* download created excel file */

    function downloadExcel($myFile) {
        header("Content-Length: " . filesize($myFile));
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename=' . $myFile);

        readfile($myFile);
    }
    
    function updateCreditNoteCharge() {
        $this->load->model('accountPayable/accountPayable_model');
        $data = array(
            'updatedBy' => element('role', $this->session->userdata('logged_in')),
            'accountNoID' => $this->input->post('accountNoID'),
            'itemdescription' => $this->input->post('itemdescription'),
            'amountExcludedTax' => $this->input->post('amountExcludedTax'),
            'taxID' => $this->input->post('taxID'),
            'taxAmount' => $this->input->post('taxAmount'),
            'amountIncludedTax' => $this->input->post('amountIncludedTax'),
        );
        $detail = $this->accountPayable_model->update_byTname('comp_supplier_creditnote_charges',$this->input->post('chargeId'), $data);
       $this->accountPayable_model->updateMaster("comp_supplier_creditnote",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        /* $dataUp = array("totalPayable" => $this->input->post('totalPayable'),
            "totalTaxAmount" => $this->input->post('totalTaxAmount'),
            "totalAmount" => $this->input->post('totalAmount'));
        $this->accountPayable_model->update_byTname("comp_supplier_creditnote", $this->input->post('invoiceId'), $dataUp);
       */ echo '{"status":"success","chargeId":"' . $detail . '"}';
    }
    
    function updDebitNoteCharge() {
        $this->load->model('accountPayable/accountPayable_model');
        $data = array(
            'updatedBy' => element('role', $this->session->userdata('logged_in')),
            'accountNoID' => $this->input->post('accountNoID'),
            'itemdescription' => $this->input->post('itemdescription'),
            'amountExcludedTax' => $this->input->post('amountExcludedTax'),
            'taxID' => $this->input->post('taxID'),
            'taxAmount' => $this->input->post('taxAmount'),
            'amountIncludedTax' => $this->input->post('amountIncludedTax'),
        );
        $detail = $this->accountPayable_model->update_byTname('comp_supplier_debitnote_charges',$this->input->post('chargeId'), $data);
       $this->accountPayable_model->updateMaster("comp_supplier_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        /* $dataUp = array("totalPayable" => $this->input->post('totalPayable'),
            "totalTaxAmount" => $this->input->post('totalTaxAmount'),
            "totalAmount" => $this->input->post('totalAmount'));
        $this->accountPayable_model->update_byTname("comp_supplier_creditnote", $this->input->post('invoiceId'), $dataUp);
       */ echo '{"status":"success","chargeId":"' . $detail . '"}';
    }
    
    public function deletedebitCharge(){
        $this->load->model('accountPayable/accountPayable_model');
        $this->accountPayable_model->delete($this->input->post('chargeID'), 'comp_supplier_debitnote_charges');
        $this->accountPayable_model->updateMaster("comp_supplier_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        echo "ok";
    }
    public function deletePurchaseCreditDetail(){
        $this->load->model('accountPayable/accountPayable_model');
        $this->accountPayable_model->delete($this->input->post('rowId'), 'comp_supplier_creditnote_charges');
        $this->accountPayable_model->updateMaster("comp_supplier_creditnote",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        echo "ok";
    }
    

    
    /********************************************
     ******************SAYEM*********************
     ********************************************/
    
    //Purchase invoice listing
    public function purchaseinvoice(){
    	$this->load->model('company/formSetup_Model');
    	$filter['companyID'] = element('compID', $this->session->userdata('logged_in'));
    	$this->lang->load("invoices", $this->session->userdata('language'));
    	$this->load->model('companyChartAcct');
    	
    	$this->load->model('Usermaster');
    	$data['records'] = $this->Usermaster->usermaster_all();
    	
    	$this->load->model('Supplier/supplier_model');
    	$data['supplier'] = $this->supplier_model->suppliermaster_all();
    	
    	$this->load->model('Project/project_model');
    	$data['project'] = $this->project_model->project_all();
    	
    	$this->load->model('address_model');
    	$data['shipto'] = $this->address_model->getCompanyAdresses();
    	
    	$this->load->model('employee/employee_model');
    	$data['purchaser'] = $this->employee_model->employeemaster_allopt();
    	
    	$this->load->model('master/masterCode_model');
    	$data['shippingmethod'] = $this->masterCode_model->get_all(array('masterID' => 2));
    	
    	$this->load->model('Terms/terms_model');
    	$data['terms'] = $this->terms_model->terms_all();
    	
    	$this->load->model('location');
    	$data['location'] = $this->location->location_all();
    	
    	$this->load->model('companyChartAcct');
    	$data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();
    	
    	
    	$this->load->model('taxmaster');
    	$data['taxmaster'] = $this->taxmaster->taxmaster_all();
    	
    	$this->load->model('item/itemSetup_model');
    	//$default = $this->itemSetup_model->get_byCode($this->input->post('itemCode'));
    	$data['items'] = $this->itemSetup_model->get_all();
    	
    	//			$this->load->model('company/formSetup_Model');
    	$filter['companyID'] = element('compID', $this->session->userdata('logged_in'));
    	$filter['formID'] = 41;
    	$data['formNo'] = $this->formSetup_Model->getFormNo($filter);
    	
    	$this->load->model('Usermaster');
    	$data['records'] = $this->Usermaster->usermaster_all();
    	$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js')
    				->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
			    	->add_includes('js/accounting.js')
			    	->add_includes('js/validationengine/jquery.validationEngine.js');
    	$this->layouts->view('purchase/transactions/purchaseinvoice', '', $data);
    }
    
    //Get Invoice list by customer id
    public function getInvoiceBySupp(){
    	$this->load->model('purchase/purchaseInvoice_model');
    	$invoices = $this->purchaseInvoice_model->getInvoice($this->input->post('supplierID'));
    	echo $invoices;
    	exit();
    }
    
    //Gathering detail information about the invoice.
    public function getInvoiceDetail(){
    	$this->load->model('purchase/purchaseInvoice_model');
    	$invoices = $this->purchaseInvoice_model->getInvoiceByID($this->input->post('invID'));
    	echo json_encode($invoices);
    	exit();
    }
    /******************************************
     *
    *  - Sayem
    *  end
    *
    */
    
    
    	public function saveSupplierPayment() {
		$outOfBalance = $this->input->post('outOfBalance');
		$currentUser = element('role', $this->session->userdata('logged_in'));
		if ($outOfBalance <> 0 || $this->input->post('supplierID') =="0") 
			echo '<script>alert("Update Failed."); history.go(-1);</script>';
//		var_dump($this->input->post());
		$ID		= $this->input->post('ID');
		$paymentDate = substr($this->input->post('paymentDate'),6,4).'-'.substr($this->input->post('paymentDate'),3,2).'-'.substr($this->input->post('paymentDate'),0,2); 
		$newsupppayment = array(
			'companyID' => element('compID', $this->session->userdata('logged_in')),   
			'supplierID'		=> $this->input->post('supplierID'), 
			'projectID'		=> $this->input->post('projectID'),
			'amountPaid'		=> $this->input->post('amountPaid'),
			'paymentMethodID'  => $this->input->post('paymentMethodID'),
			//'supplierAddress' => $this->input->post('supplierAddress'),
			'formNo' => $this->input->post('formNo'),
                        'bankID' => $this->input->post('bank'),
			'currencyID' => $this->input->post('currencyID'),
			'exchangeRate' => $this->input->post('exchangeRate'), 
//			'paymentDate' => 'str_to_date('.$this->input->post('paymentDate').",'%d-%m-%Y')",
			'paymentDate' => $paymentDate,
			'referenceNo' => $this->input->post('referenceNo'),
			'accountDescription' => $this->input->post('accountDescription'),
			'totalDiscount' =>  $this->input->post('totalDiscount'),
			'bankCharges' => $this->input->post('BankCharges'),
			'totalOtherCharge' => $this->input->post('totalOtherCharges'),
			'totalPaid' => $this->input->post('totalPaid'),
			'totalApplied' => $this->input->post('totalApplied'),
			'outOfBalance' => $this->input->post('outOfBalance'),
			'memo' => $this->input->post('memo'),
			'createdBy' => $currentUser					
		   );	//end newsupppayment array
		   
		$this->load->model('supplier/supplierpayment_model');
		$saveMode = 0;
		$paymentID =0;
		if($this->input->post('ID')==NULL){
			$paymentID = $this->supplierpayment_model->suppPayment_insert($newsupppayment);
			$saveMode = 1; //insert
			//echo '<br>insert';
		} else{
			$paymentID = $this->supplierpayment_model->suppPayment_edit($newsupppayment, $ID);
			$saveMode = 2; //update
			//echo '<br>update';
		}
		//save detail payment
		$paymentDetail = array (
			'amountApplied' => $this->input->post('amountApplied'),
			'suppInvoiceID' => $this->input->post('suppInvoiceID'),
			'discount' => $this->input->post('discount'),
			'paymentID' => $paymentID);
		if ($saveMode == 1)
			$success = $this->supplierpayment_model->paymentDetail_insert($paymentDetail);
		else
			$success = $this->supplierpayment_model->paymentDetail_edit($paymentDetail);


		if($success){
			echo '<script>alert("Save Success..");
					window.location.replace("aptransaction/supplierpaymentlist");
					</script>';
		} else {
			echo '<script>alert("Update Failed:'.$success.'"); history.go(-1);</script>';
		}
			
} //end save

    public function loadsupplierPendingInvoices(){
        $this->load->model('accountPayable/AccountPayable_model');
        $rs = $this->AccountPayable_model->get_bySupplierID($this->input->post('supplier'), element('compID', $this->session->userdata('logged_in')));
        //echo $this->db->last_query(); 
        echo json_encode(array("status"=>"success", "recordSet"=>$rs));
    }
    
    public function addpaymentdetailsOnly(){
        
            $this->load->model('supplier/supplierPayment_model');
            
            $masterId =  $this->input->post('masterId');
            $pdetail = $object = get_object_vars( json_decode ( $this->input->post('pDetails') ) );
            $n = sizeof ( $pdetail ['rs'] );
            $lineNo = $this->input->post('lastLine');
            $successN =0;
         //   $pSuccessId=array();
            if ($n>0){
                for($i=0;$i<$n;$i++){
                    $dataInsert = array(
                                    "lineNo" => ++$lineNo,
                                    "paymentID" => $masterId,
                                    "purchaseInvoiceID" =>  $pdetail ['rs'] [$i]->invoiceID, 
                                    "discount" => $pdetail ['rs'] [$i]->discount, 
                                    "amountApplied" => $pdetail ['rs'] [$i]->amountApplied, 
                                    );
                    $idD = $this->supplierPayment_model->insert("comp_payment_detail",$dataInsert);
                    if ($idD>0){
                       // $pSuccessId = $row->invoiceID.'"';
                        $successN++;
                        $newArBalance = array ("totalPayable"=>$pdetail ['rs'] [$i]->arBalance - $pdetail ['rs'] [$i]->amountApplied);
                        $this->supplierPayment_model->update_byID ("comp_supplier_invoice",$pdetail ['rs'] [$i]->invoiceID,$newArBalance );
                    }
                }
            }
            echo $successN;
    }
    
    public function updatePaymentRow(){
         $upd="";
            
            $this->load->model('supplier/supplierPayment_model');
            
            $arrayUpPaymentDetails = array(
                'discount' => $this->input->post('discount'),
                'amountApplied' => $this->input->post('amountApplied')
            );
            $upd = $this->supplierPayment_model->update_byID ("comp_payment_detail",$this->input->post('detaildId'),$arrayUpPaymentDetails );
            
            $arrayUpPaymentMaster = array(
                'memo' => $this->input->post('memo'),
                'amountPaid' => $this->input->post('amountPaid'),
                 'totalDiscount' => $this->input->post('totalDiscount'),
                'totalPaid' => $this->input->post('totalPaid'),
                'totalApplied' => $this->input->post('totalApplied'),
                'outOfBalance' => $this->input->post('outOfBalance'),
                'bankCharges' => $this->input->post('bankCharges'),
                'totalOtherCharge' => $this->input->post('totalOtherCharge')
            );
            $upd = $upd.$this->supplierPayment_model->update_byID ("comp_payment",$this->input->post('masterId'),$arrayUpPaymentMaster );
            
            $arrayUpSaleInvoice = array(
                'totalPayable' => $this->input->post('totalPayable')
            );
            $upd = $upd.$this->supplierPayment_model->update_byID ("comp_supplier_invoice",$this->input->post('invoiceId'),$arrayUpSaleInvoice );
            
            echo $upd;
    }
    
    public function deletePaymentDetailRow(){
        $this->load->model('supplier/supplierPayment_model');
        echo $this->supplierPayment_model->delete_byID("comp_payment_detail",$this->input->post('id'));
    }

}

    

//big end
?>


