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

// purchase invoices	
// created by Eisa

    /*     * ***************** edited by Sayem
      no tax for not GST registered suppliers. default is 0(NR)* */

// 20th may 2014

    public function invoices() {
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APDIRINV');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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();
        //add condition to avoid error when no supplier. 
        if ($data['supplier'][0])
            $data['supplier'][0]->supplierName = '<b style="color:#e74c3c">' . $data['supplier'][0]->supplierName . '</b>';

        $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('Sysum');
        $data['um'] = $this->Sysum->sysum_all();
        
        $this->load->model('taxmaster');
        $data['taxmaster'] = $this->taxmaster->taxmaster_purchaseInput();

        $this->load->model('item/itemSetup_model');
        //$default = $this->itemSetup_model->get_byCode($this->input->post('itemCode'));
        $data['items'] = $this->itemSetup_model->get_all(true);

//			$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/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/newdirectpurchaseinvoice', '', $data);
    }

    public function getPrice() {
        $this->load->model('item/itemSetup_model');
        $umID  =  $this->input->post('umID');
        $currencyID = $this->input->post('currencyID');
        echo $this->itemSetup_model->getItemPrice($this->input->post('option'), $this->input->post('itemID'), $this->input->post('datePrice'), $this->input->post('supplierID'),$umID, $currencyID);
    }

    //Created By sayem (21-10-2014)
    //Gather um List and item price
    public function getUmList(){
        $this->load->model('sysum');
        $data['umConv'] = $this->sysum->umconvAll($this->input->post('itemID'));

        $this->load->model('item/itemSetup_model');
        $this->load->model('Items');
        $items = $this->Items->Items_ID_um_detail($this->input->post('itemID'));
        if($this->input->post('option') == 'sale'){
            $this->load->model('customer/Customer_model');
            $customer = $this->Customer_model->customermaster_id($this->input->post('customerID'));    
            $data['unitPrice'] = $this->itemSetup_model->getItemPriceByDate($this->input->post('option'), $this->input->post('itemID'), $this->input->post('datePrice'), $this->input->post('customerID'),$items[0]->unitOfMeasureID, $customer[0]->currencyID);            
        }else{
            $this->load->model('supplier/Supplier_model');
            $supp = $this->Supplier_model->suppliermaster_id($this->input->post('supplierID'));
            if(empty($supp)){
                $supp = array((object) array('currencyID'=>1));
            }   
            $data['unitPrice'] = $this->itemSetup_model->getItemPriceByDate($this->input->post('option'), $this->input->post('itemID'), $this->input->post('datePrice'), $this->input->post('supplierID'),$items[0]->unitOfMeasureID, $supp[0]->currencyID);
        }        

        
        $data['items'] = $items;
        echo json_encode($data);
    }
    public function getItemPrice() {
        $this->load->model('item/itemSetup_model');
        $umID  =  $this->input->post('umID');
        $currencyID = $this->input->post('currencyID');
        echo $this->itemSetup_model->getItemPrice($this->input->post('option'), $this->input->post('itemID'), $this->input->post('datePrice'), $this->input->post('supplierID'),$umID, $currencyID);
    }

    function savePurchaseRow() {
        $this->load->model('accountPayable/accountPayable_model');
        $ID = $this->input->post('ID');
        $companyID = element('compID', $this->session->userdata('logged_in'));
        $datinsert = array(
            'shippingMethodID' => $this->input->post('shippingMethodID'),
            'purchaserID' => $this->input->post('employeeID'),
            'memo' => $this->input->post('memo'),
            'locationID' => $this->input->post('locationID'),
            'currencyID' => $this->input->post('currencyID'),
            'companyID' => $companyID,
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'purchaseInvoiceCodeID' => 2,
            'supplierID' => $this->input->post('supplierID'),
            'shipToID' => $this->input->post('shipToID'),
            'formNo' => $this->input->post('formNo'),
            'invoiceDate' => date('Y-m-d', strtotime($this->input->post('invoiceDate'))),
            'supplierInvoiceNo' => $this->input->post('supplierInvoiceNo'),
            'projectID' => $this->input->post('projectID'),
            'termsID' => $this->input->post('termsID'),
            'exchangeRate' => $this->input->post('exchangeRate')
        );


        $queryRes = $this->accountPayable_model->insert("comp_supplier_invoice", $datinsert);


       


        if ($queryRes > 0) {

            $datinsertDetails = array(
                'invoiceID' => $queryRes,
                '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'),
                'umID' => $this->input->post('umid'),
                '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('amountIncludeTax')
            );
            $query = $this->accountPayable_model->insert('comp_supplier_invoice_detail', $datinsertDetails);
            $this->accountPayable_model->updateMaster("comp_supplier_invoice", array("totalTaxAmount", "totalAmount"), $queryRes);
            $this->accountPayable_model->setTotalPayable("comp_supplier_invoice", $queryRes);
            
            
             
        
            echo '{"status":"success","invoiceID":"' . $queryRes . '","detailID":"' . $query . '"}';
        } else {
            echo "false";
        }
    }

// purchase invoices confirm 
// created by Sayem
// 24th june 2014
    public function invoicesConfirm() {
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APDRINVC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $this->lang->load("purchaseinvoiceconfirm", $this->session->userdata('language'));
        $this->load->model('company/FormSetup_model');
        $this->load->model('accountPayable/accountPayable_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);
        //change to get financial year based on select disctint financial year
		$data['yrs'] = $this->Compfinancialyear->get_financialYear();
		$data['selyear'] = $add_year;
        $data['selper'] = $add_period;
        $data['datatbls'] = $this->accountPayable_model->getSupplierInvoiceAll($startDate, $endDate);

        $this->layouts->add_includes('js/accounting.js')
                ->add_includes('js/datatables/jquery.dataTables.min.js');
        $this->layouts->view('purchase/transactions/purchaseinvoiceconfirm', '', $data);
    }

// invoice
    public function invoicePosting() {
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APDIRINV');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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) {
            $recieveID = $this->accountPayable_model->saveReceiveItemFromDirect($ID);
            $this->load->model('Compfinancialyear');
            $query1 = $this->Compfinancialyear->compfinancialyear_date1($effdate);
            if ($query1) {
               // var_dump( $query1[0]);
                $year = $query1[0]->financialYear;
                $period = $query1[0]->period;
                $formNo = $query[0]->formNo . '[' . sprintf('%08d', $query[0]->serialNo) . ']';
                $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->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() {
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APSUPPAY');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $ID = isset($_REQUEST['ID']) ? $_REQUEST['ID'] : "";
        $supplierID = ($this->uri->segment(3) != '') ? $this->uri->segment(3) : FALSE;
//		$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['exchangeRate'] = '';
        $data['rsPendingInvoice'] = false;
        $data['supplier'] = $this->supplier_model->suppliermaster_all(); //for combo box
        if ($supplierID) {

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

            $data['exchangeRate'] = ($supplierID) ? $this->Currency->getConversionRate($rs[0]->currencyID) : '1';
            $this->load->model('accountPayable/AccountPayable_model');
            $data['rsPendingInvoice'] = $this->AccountPayable_model->get_bySupplierID($data['supplierID'], element('compID', $this->session->userdata('logged_in')));
            //echo $this->db->last_query(); 
        }
        $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->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->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPAYCFM');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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);
        //change to get financial year based on select disctint financial year
		$data['yrs'] = $this->Compfinancialyear->get_financialYear();
		$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->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPAYCFM');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $this->lang->load("supplierPaymentList", $this->session->userdata('language'));
        $ID = $this->input->post('fldid');
        $this->load->model('supplier/SupplierPayment_model');
        $queryDetails = $this->SupplierPayment_model->supppaymentDetails_ID($ID);
//		echo $this->db->last_query();
        $data = array(
            'updateAble' => '0'
        );

        $query = $this->SupplierPayment_model->supppaymentDetailspost($ID, $data);
        //var_dump($query);
        if ($query) {
            $effdate = date("Y-m-d", strtotime($query[0]->paymentDate));
            $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]->serialNo) . ']';
                $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->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPAYICM');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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);
        //change to get financial year based on select disctint financial year
		$data['yrs'] = $this->Compfinancialyear->get_financialYear();
		$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->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPAYICM');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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);
       // var_dump($queryDetails);
        $data = array(
            'updateAble' => '0'
        );
        $query = $this->othersPayment_model->othersPaymentWithItempost($ID, $data);
        if ($query) {
            $this->load->model('Compfinancialyear');
            $query1 = $this->Compfinancialyear->compfinancialyear_date($effdate);
            if ($query1) {
                $year = $query1[0]->financialYear;
                $period = $query1[0]->period;
                //$formNo = $query[0]->formNo . '[' . sprintf('%08d', $query[0]->ID) . ']';
                $formNo = '[' . $this->lang->line('title2') . ']'.$query[0]->formNo;
				$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' => $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" => $query4));
            } else {
                print json_encode(array("status" => "failed", "message" => $query4));
            }
        } else {
            return FALSE;
        }
    }

// Debit note start
// Created By Eisa
// Updated By Farhana - Confirm & List
    /*     * ***************** edited by Sayem(8-9-2014)
      no tax for not GST registered suppliers. default is 0(NR)* */


    public function newDebitNote() {
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPURDN');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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('Sysum');
        $data['um'] = $this->Sysum->sysum_all();
        
        $this->load->model('taxmaster');
        $data['taxmaster'] = $this->taxmaster->taxmaster_purchaseInput();

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

        $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'),
            'taxRate' => $this->input->post('taxRate'),
            '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"), $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('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPURDN');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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'),
             'taxRate' => $this->input->post('taxRate'),
            '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'),
                'taxRate' => $this->input->post('taxRate'),
                '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'),
                'invoiceDetailID' => $this->input->post('invoiceDetailID'),
                'umID' => $this->input->post('umid'),
                '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'),
            'umID' => $this->input->post('umid'),
            '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('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPURDN');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }

        $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'),
            'invoiceDetailID' => $this->input->post('invoiceDetailID'),
            'itemdescription' => $this->input->post('itemdescription'),
            'quantity' => $this->input->post('quantity'),
            'umID' => $this->input->post('umid'),
            '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'),
            'invoiceDetailID' => $this->input->post('invoiceDetailID'),
            '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('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APDRNOTE');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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('Project/project_model');
        $data['project'] = $this->project_model->project_all();
        
        $this->load->model('item/itemSetup_model');
      //  $data['items'] = $this->itemSetup_model->get_all(true);
        
          $this->load->model('Sysum');
        $data['um'] = $this->Sysum->sysum_all();
        
        $this->load->model('taxmaster');
        $data['taxmaster'] = $this->taxmaster->taxmaster_purchaseInput();

        $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);
        
         if ($data['pInvoice']){
            $data['items'] = $this->accountPayable_model->getSupplierInvoiceItemListDebit($data['pInvoice'][0]->supplierInvoiceID);
        
            //var_dump($data['items']);
        }else{
            $data['items'] = false; 
        }
        

        $data['charge'] = $this->accountPayable_model->getDebitNoteChargeByid($id);


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

    public function printDebitNote($id) {
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APDRNOTE');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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_purchaseInput();

        $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('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APCRNOTE');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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_purchaseInput();

        $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(true);
      $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->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPURDNC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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);
        //change to get financial year based on select disctint financial year
		$data['yrs'] = $this->Compfinancialyear->get_financialYear();
		$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->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPURDNC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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);
        //print_r($queryDetails);
        //exit();
        $data = array(
            'updateAble' => '0'
        );
        $query = $this->debitnote_model->debitNotepost($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) . ']';
                $formNo = $query[0]->formNo ;
                $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);
                $this->load->model('items');
                $query4 = $this->items->itemReducePosting($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() {
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPURDNL');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPURDNL');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPURCNC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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);
        //change to get financial year based on select disctint financial year
		$data['yrs'] = $this->Compfinancialyear->get_financialYear();
		$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->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPURCNC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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
    /*     * ***************** edited by Sayem(8-9-2014)
      no tax for not GST registered suppliers. default is 0(NR)* */
    
    
    public function loadInvoiceItems(){
       $this->load->model('accountPayable/accountPayable_model');
       print json_encode(array("status" => "failed", "message" => $query));
        $data = $this->accountPayable_model->get_Detail_byID($id);
    }

    public function newCreditNote() {
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPURCN');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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('Sysum');
        $data['um'] = $this->Sysum->sysum_all();

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

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

        $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('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APTRETCR');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $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('Sysum');
        $data['um'] = $this->Sysum->sysum_all();
        
        $this->load->model('Project/project_model');
        $data['project'] = $this->project_model->project_all();
        
        $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->itemSetup_model->get_all(true);

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

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

        $this->load->model('accountPayable/accountPayable_model');
         
        $this->load->model('accountPayable/accountPayable_model');
        $data['charge'] = $this->accountPayable_model->getCreditNoteChargeByid($id);
        $data['pInvoice'] = $this->accountPayable_model->get_byID("comp_supplier_creditnote", $id);
        if ($data['pInvoice']){
            $data['items'] = $this->accountPayable_model->getSupplierInvoiceItemList($data['pInvoice'][0]->supplierInvoiceID);
        
            //var_dump($data['items']);
        }
        $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'),
            'invoiceDetailID' => $this->input->post('invoiceDetailID'),
            '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')
        );
      
         $this->accountPayable_model->update_CreditNoteDetail($this->input->post('invDetailsId'), $data);
         echo $this->accountPayable_model->updateMaster("comp_supplier_creditnote", array("totalTaxAmount", "totalAmount"), $this->input->post('invoiceId'));
         
    }

    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'),
            'currencyID' => $this->input->post('currencyID'),
            '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'),
                'taxRate' => $this->input->post('taxRate'),
                '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'),
            'currencyID' => $this->input->post('currencyID'),
            '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'),
                'invoiceDetailID' => $this->input->post('invoiceDetailID'),
                'itemname' => $this->input->post('itemname'),
                'itemdescription' => $this->input->post('itemdescription'),
                'quantity' => $this->input->post('quantity'),
                'umID' => $this->input->post('umid'),
                '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->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APTRETCR');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        
          $this->load->model('Project/project_model');
        $data['project'] = $this->project_model->project_all();

        $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'),
            'invoiceDetailID' => $this->input->post('invoiceDetailID'),
            'lineNo' => $this->input->post('lineNo'),
            'itemdescription' => $this->input->post('itemdescription'),
            'quantity' => $this->input->post('quantity'),
            'umID' => $this->input->post('umid'),
            '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'),
            'taxRate' => $this->input->post('taxRate'),
            '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'),
            'taxRate' => $this->input->post('listTax'),
            '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*********************
     * ******************************************* */

    public function refreshShipto() {
        $this->load->model('address_model');
        echo json_encode($this->address_model->address_company_all(element('compID', $this->session->userdata('logged_in'))));
    }

    //Purchase invoice listing
    public function purchaseinvoice() {
        //load lang file
        $this->lang->load("invoices", $this->session->userdata('language'));

        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APPURINV');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }

        $data = $this->getDefaultRecords();


        $this->load->model('company/formSetup_Model');
        $filter['companyID'] = element('compID', $this->session->userdata('logged_in'));
        //gather company shipto information.
        $this->load->model('address_model');
        $data['compShipto'] = $this->address_model->address_company_all(element('compID', $this->session->userdata('logged_in')));
        //print_r($data['compShipto']);
        $filter['formID'] = 41;
        $data['formNo'] = $this->formSetup_Model->getFormNo($filter);

        $filter['companyID'] = element('compID', $this->session->userdata('logged_in'));

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

    public function getDefaultRecords() {
        //gather system user information.
        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();
        //gather supplier information.
        $this->load->model('Supplier/supplier_model');
        $data['supplier'] = $this->supplier_model->suppliermaster_all();
        //gather project information.
        $this->load->model('Project/project_model');
        $data['project'] = $this->project_model->project_all();
        //gather shipto information.
        $this->load->model('address_model');
        $data['shipto'] = $this->address_model->getCompanyAdresses();
        //gather purchaser information.
        $this->load->model('employee/employee_model');
        $data['purchaser'] = $this->employee_model->employeemaster_allopt();
        //gather shippingmethod information.
        $this->load->model('master/masterCode_model');
        $data['shippingmethod'] = $this->masterCode_model->get_all(array('masterID' => 2));
        //gather terms information.
        $this->load->model('Terms/terms_model');
        $data['terms'] = $this->terms_model->terms_all();
        //gather location information.
        $this->load->model('location');
        $data['location'] = $this->location->location_all();
        //gather chart of account information.
        $this->load->model('companyChartAcct');
        $data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();
        //gather tax information.
        $this->load->model('taxmaster');
        $data['taxmaster'] = $this->taxmaster->taxmaster_purchaseInput();
        //gather item information.
        $this->load->model('item/itemSetup_model');
        $data['items'] = $this->itemSetup_model->get_all(true);
        //Return all records.
        return $data;
    }

    //Load supplier default value
    public function loadSupplierDefaultValue() {
        $this->load->model('accountPayable/accountPayable_model');
        $default = $this->accountPayable_model->loadSupplierDefaultValue($this->input->post('supplier'));
        if ($default[0]->exchangeRate == "")
            $default[0]->exchangeRate = 1;
        echo json_encode($default);
    }

    //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();
    }

    //Check GST Registration status of customer or supplier
    public function getGSTInfo() {
        $this->load->model('purchase/purchaseInvoice_model');
        $gstInfo = $this->purchaseInvoice_model->getGSTInfo($this->input->post('ID'), $this->input->post('type'));
        echo json_encode($gstInfo);
        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' => str_replace(array(' ', ','), '', $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' => str_replace(array(' ', ','), '', $this->input->post('totalDiscount')),
            'bankCharges' => str_replace(array(' ', ','), '', $this->input->post('BankCharges')),
            'totalOtherCharge' => str_replace(array(' ', ','), '', $this->input->post('totalOtherCharges')),
            'totalPaid' => str_replace(array(' ', ','), '', $this->input->post('totalPaid')),
            'totalApplied' => str_replace(array(' ', ','), '', $this->input->post('totalApplied')),
            'outOfBalance' => str_replace(array(' ', ','), '', $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' => str_replace(array(' ', ','), '',$this->input->post('amountApplied')),
            'suppInvoiceID' => $this->input->post('suppInvoiceID'),
            'discount' =>str_replace(array(' ', ','), '', $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>
					window.location.replace("' . base_url() . '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');

        $updMaster = array(
        );

        $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 = $this->supplierPayment_model->update_byID("comp_payment", $this->input->post('masterId'), $arrayUpPaymentMaster);


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

    public function getSupplierInvoiceItemList(){
       $this->load->model('accountPayable/accountPayable_model');
         echo '{"status":"success","recordSet":' . json_encode($this->accountPayable_model->getSupplierInvoiceItemList($this->input->post('invoiceId'))) . '}';
    }
    
    public function getSupplierInvoiceItemListDebit(){
       $this->load->model('accountPayable/accountPayable_model');
         echo '{"status":"success","recordSet":' . json_encode($this->accountPayable_model->getSupplierInvoiceItemListDebit($this->input->post('invoiceId'))) . '}';
    }
    
    
    public function getItemUnitList() {
         $this->load->model('item/ItemSetup_model');
          print json_encode(array("status" => "...", "recordSet" => $this->ItemSetup_model->getItemUnitList($this->input->post('itemID'), $this->input->post('unitFrom'))));
    }
    
    public function update_purchaseDebitNote_header(){
    	$this->load->model('accountPayable/accountPayable_model');
    	$data = array(
    		'projectID' => $this->input->post('project') ,
    		'debitNoteDate' =>date('Y-m-d', strtotime($this->input->post('date'))),
    		 'memo' => $this->input->post('memo')
    	 );
    	$res = $this->accountPayable_model->update_by_tname("comp_supplier_debitnote", $this->input->post('masterId') ,$data);
    	echo '{"status":"success","res":"'.$res.'"}';
    }
    
     public function update_purchaseCreditNote_header(){
    	$this->load->model('accountPayable/accountPayable_model');
    	$data = array(
    		'projectID' => $this->input->post('project') ,
    		'creditNoteDate' =>date('Y-m-d', strtotime($this->input->post('date'))),
    		 'memo' => $this->input->post('memo')
    	 );
    	$res = $this->accountPayable_model->update_by_tname("comp_supplier_creditnote", $this->input->post('purchaseInvoiceId') ,$data);
    	echo '{"status":"success","res":"'.$res.'"}';
    }
    
    
    public function update_payment_header(){
    	$this->load->model('accountPayable/accountPayable_model');
    	$data = array(
    		'projectID' => $this->input->post('project') ,
    		'paymentDate' =>date('Y-m-d', strtotime($this->input->post('date'))),
    		 'memo' => $this->input->post('memo'),
                'referenceNo' => $this->input->post('referenceNo')
    	 );
    	$res = $this->accountPayable_model->update_by_tname("comp_payment", $this->input->post('masterId') ,$data);
    	echo '{"status":"success","res":"'.$res.'"}';
    }
    
}

//big end
?>


