<?php

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

class Purchasetransaction extends CI_Controller {

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

    public function index() {
        
    }
    
	public function purchaseInvoiceList() {
        $this->lang->load("purchaseInvoice", $this->session->userdata('language'));
        $this->load->model('purchaseInvoice_list');
        $this->load->model('company/FormSetup_model');

//		$dateFrom = $this->input->post('selDateFrom');
//		$dateTo = $this->input->post('selDateTo');
        $dateFrom = date("Y-m-d",strtotime($this->uri->segment(3)));
		$dateTo = date("Y-m-d",strtotime($this->uri->segment(4)));
		$totalPayable = $this->uri->segment(5);
		
		if ($this->uri->segment(3) == ""){
			$dateFrom = date("Y-m-01");
		}
		if($this->uri->segment(4) == ""){
			$dateTo = date("Y-m-t");
		}
		if($dateFrom > $dateTo){
			$dateTo = date("Y-m-t", strtotime($dateFrom));
		}
		
		$data['dateFrom'] = $dateFrom;
		$data['dateTo'] = $dateTo;
		$data['totalPayable'] = $totalPayable;
        //if (($dateFrom == "") || ($dateTo == "")) {
            //$data['datatbls'] = $this->purchaseInvoice_list->purchaseInvoice_all();
        //} else {
		
		$data['datatbls'] = $this->purchaseInvoice_list->purchaseInvoiceDate_totalPayable($dateFrom, $dateTo, $totalPayable);
		
        //}
//		echo $this->db->last_query();
        $this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
        $this->layouts->view('purchase/transactions/purchaseInvoiceList', array('latest' => 'sidebar/latest'), $data);
    }
	
    /***************************

        purchaseInvoiceDetail
        Created by sayem
        17th july, 2014

    ***********Start************/
    public function purchaseInvoiceDetail($id,$mode = false){
        $this->lang->load("purchaseInvoice", $this->session->userdata('language'));
        $this->load->model('purchaseInvoice_list');
        $this->load->model('company/FormSetup_model');
        $this->load->model('company/company_info_model');   
        
        //Gather Information
        $data['datatbls'] = $this->purchaseInvoice_list->purchaseInvoiceDetail($id);      
        if($data['datatbls']){
            //$headerData['rightContentHeader'] = "Name supplier/ ot";
            $headerData['rptTitle'] = $this->lang->line('purchaseInvoiceDetail');
            $headerData['leftContentHeader'] = $data['datatbls']['info'][0]->supplierName;
            $headerData['leftContent'] = array(
                                            $data['datatbls']['info'][0]->supplierCompanyNo,
                                            $data['datatbls']['info'][0]->line1,
                                            $data['datatbls']['info'][0]->line2,
                                            $data['datatbls']['info'][0]->line3,
                                            $data['datatbls']['info'][0]->supplierPostCode.$data['datatbls']['info'][0]->city                                        
                                        );
            
            $headerData['rightContentHeader'] = "Invoide No: ".$data['datatbls']['info'][0]->invNo;
            $headerData['rightContent'] = array(
                                            "Date: ".$data['datatbls']['info'][0]->invoiceDate,
                                        );
             
            //   $headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
              
            $bodyData['rptDataDetail'] = $data['datatbls']['detail'];
            $bodyData['tableHeader'] = array($this->lang->line("itemName"),$this->lang->line("itemDescription"), $this->lang->line("quantity"), $this->lang->line("unitPrice"), $this->lang->line("amountExcludeTax"), $this->lang->line("tax"), $this->lang->line("amountIncludeTax"), $this->lang->line("taxAmount")); 
            $bodyData['selectFields'] = array("itemCodeName","description","quantity","unitPrice","amountExcludedTax","taxPercentage","amountIncludedTax","taxAmount");
            $bodyData ['tdAmount'] = array("quantity","unitPrice","amountExcludedTax","taxPercentage","amountIncludedTax","taxAmount");
            //$bodyData['tableFooter'] = array ("footer : value");
            $bodyData['excelTitle'] = $this->lang->line('purchaseInvoiceDetail');
                    
            if(!$mode){
                //print
                $this->load->view('layouts/report/header', $headerData);
                $this->load->view('layouts/report/body', $bodyData);
                $this->load->view('layouts/report/footer','');
            }else{
                //download excell
                $this->load->helper('excel');
                excel($bodyData);
            }   
        }else{
            $this->session->set_flashdata('msg', 'Invoice Detail not found');
            echo '<script type="text/javascript">window.location = document.referrer;</script>';
        }

    }
    /***********End*************/
	public function purchaseInvoiceListprint() {
        $this->lang->load("purchaseInvoice", $this->session->userdata('language'));
        $this->load->model('purchaseInvoice_list');
        $this->load->model('company/FormSetup_model');
		$this->load->model('company/company_info_model');

//		$dateFrom = $this->input->post('selDateFrom');
//		$dateTo = $this->input->post('selDateTo');

        $dateFrom = date("Y-m-d",strtotime($this->uri->segment(3)));
		$dateTo = date("Y-m-d",strtotime($this->uri->segment(4)));
		$totalPayable = $this->uri->segment(5);
		
		if ($this->uri->segment(3) == ""){
			$dateFrom = date("Y-m-01");
		}
		if($this->uri->segment(4) == ""){
			$dateTo = date("Y-m-t");
		}
		if($dateFrom > $dateTo){
			$dateTo = date("Y-m-t", strtotime($dateFrom));
		}
		
		$data['dateFrom'] = $dateFrom;
		$data['dateTo'] = $dateTo;
		$data['totalPayable'] = $totalPayable;
        //if (($dateFrom == "") || ($dateTo == "")) {
            //$data['datatbls'] = $this->purchaseInvoice_list->purchaseInvoice_all();
        //} else {
		
		$data['datatbls'] = $this->purchaseInvoice_list->purchaseInvoiceDate_totalPayable($dateFrom, $dateTo, $totalPayable);
		
        
		
		if ($totalPayable == ""){
			//$headerData['rightContentHeader'] = "Name supplier/ ot";
        	$headerData['rptTitle'] = $this->lang->line('title2');
        	$headerData['rightContent'] = array($this->lang->line('from')." ".date('d-m-Y',strtotime($dateFrom))." ".$this->lang->line('to')." ".date('d-m-Y',strtotime($dateTo)));
			//$headerData['leftContent'] = array("Left : value", "Left: value");
			$headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
			$bodyData['rptDataDetail'] = $this->purchaseInvoice_list->purchaseInvoiceDate_totalPayable($dateFrom, $dateTo, $totalPayable);
        	$bodyData['tableHeader'] = array($this->lang->line('suppinvoiceno'), $this->lang->line('suppname'), $this->lang->line('formNo'), $this->lang->line('date')); 
        	$bodyData['selectFields'] = array(
				"supplierInvoiceNo",
				"supplierName", 
				"suppNo", 
				"InvDate");
        	//$bodyData ['tdAmount'] = array("invoiceDate");
        	//$bodyData['tableFooter'] = array ("footer : value");
		}
		else if( $totalPayable == 1){
			//$headerData['rightContentHeader'] = "Name supplier/ ot";
			$headerData['rptTitle'] = $this->lang->line('title2');
        	$headerData['rightContent'] = array($this->lang->line('from')." ".date('d-m-Y',strtotime($dateFrom))." ".$this->lang->line('to')." ".date('d-m-Y',strtotime($dateTo)), $this->lang->line('statOpen'));
			//$headerData['leftContent'] = array("Left : value", "Left: value");
			$headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
			$bodyData['rptDataDetail'] = $this->purchaseInvoice_list->purchaseInvoiceDate_totalPayable($dateFrom, $dateTo, $totalPayable);
        	$bodyData['tableHeader'] = array($this->lang->line('suppinvoiceno'), $this->lang->line('suppname'), $this->lang->line('formNo'), $this->lang->line('date')); 
        	$bodyData['selectFields'] = array(
				"supplierInvoiceNo",
				"supplierName", 
				"suppNo", 
				"InvDate");
        	//$bodyData ['tdAmount'] = array("invoiceDate");
        	//$bodyData['tableFooter'] = array ("footer : value");
		}
		else if( $totalPayable == 2){
			//$headerData['rightContentHeader'] = "Name supplier/ ot";
        	$headerData['rptTitle'] = $this->lang->line('title2');
			$headerData['rightContent'] = array($this->lang->line('from')." ".date('d-m-Y',strtotime($dateFrom))." ".$this->lang->line('to')." ".date('d-m-Y',strtotime($dateTo)), $this->lang->line('statClose'));
			//$headerData['leftContent'] = array("Left : value", "Left: value");
			$headerData['company'] = $this->company_info_model->companyById(element('compID', $this->session->userdata('logged_in')));
			$bodyData['rptDataDetail'] = $this->purchaseInvoice_list->purchaseInvoiceDate_totalPayable($dateFrom, $dateTo, $totalPayable);
        	$bodyData['tableHeader'] = array($this->lang->line('suppinvoiceno'), $this->lang->line('suppname'), $this->lang->line('formNo'), $this->lang->line('date')); 
        	$bodyData['selectFields'] = array(
				"supplierInvoiceNo",
				"supplierName", 
				"suppNo", 
				"InvDate");
        	//$bodyData ['tdAmount'] = array("invoiceDate");
        	//$bodyData['tableFooter'] = array ("footer : value");
		}
            
        $this->load->view('layouts/report/header', $headerData);
        $this->load->view('layouts/report/body', $bodyData);
        $this->load->view('layouts/report/footer','');
    }

// purchase invoices	
// created by Eisa
// 20th may 2014

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

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

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

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

        $this->load->model('address_model');
        $data['shipto'] = $this->address_model->getCompanyAdresses();

        $this->load->model('employee/employee_model');
        $data['purchaser'] = $this->employee_model->employeemaster_allopt();

        $this->load->model('master/masterCode_model');
        $data['shippingmethod'] = $this->masterCode_model->get_all(array('masterID' => 2));

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

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

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


        $this->load->model('taxmaster');
        $data['taxmaster'] = $this->taxmaster->taxmaster_all();
        
        $this->load->model('item/itemSetup_model');
        //$default = $this->itemSetup_model->get_byCode($this->input->post('itemCode'));
        $data['items'] = $this->itemSetup_model->get_all();
        
//			$this->load->model('company/formSetup_Model');
        $filter['companyID'] = element('compID', $this->session->userdata('logged_in'));
        $filter['formID'] = 41;
        $data['formNo'] = $this->formSetup_Model->getFormNo($filter);

        $this->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();
        $this->layouts->add_includes('js/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);
    }

// purchase invoices confirm 
// created by Sayem
// 24th june 2014
	public function invoicesConfirm(){
		$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);
		$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);
	}

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

        $JsonRecords = '{"records":[';

        $i = 0;
        $default = $this->accountPayable_model->loadSupplierDefaultValue($this->input->post('supplier'));
        $n = sizeof($default);
        foreach ($default as $row) {
            $JsonRecords .= '{';
            $JsonRecords .= '"currency":"' . $row->currencyWord . '",' . '"exchangeRate":"' . $row->exchangeRate . '","currencyID":"' . $row->currencyID . '"';
            $JsonRecords .= '}';
            if ($i < $n - 1)
                $JsonRecords .= ',';
            $i++;
        }
        $JsonRecords .= ']}';
        echo $JsonRecords;
    }

    public function refreshSupplier() {
        //for ajax call 
        $this->load->model('Supplier/supplier_model');
        $supllier = $this->supplier_model->suppliermaster_all();
        $JsonRecords = '{"records":[';

        $n = sizeof($supllier);
        $i = 0;
        if ($supllier)
            foreach ($supllier as $row) {
                $JsonRecords .= '{';
                $JsonRecords .= '"supplierName":"' . $row->supplierName . '","id":"' . $row->ID . '"';
                $JsonRecords .= '}';
                if ($i < $n - 1)
                    $JsonRecords .= ',';
                $i++;
            }
        $JsonRecords .= ']}';

        //$resul= '{"supplier":['. json_encode($this->supplier_model->suppliermaster_all()).']}';
        echo $JsonRecords;
    }

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

    public function refreshTerms() {
        //for ajax call 
        $this->load->model('Terms/terms_model');
        $terms = $this->terms_model->terms_all();

        //json_encode ($this->project_model->project_all());

        $JsonRecords = '{"records":[';
        $n = sizeof($terms);
        $i = 0;
        if ($terms)
            foreach ($terms as $row) {
                $JsonRecords .= '{';
                $JsonRecords .= '"termName":"' . $row->termName . '","id":"' . $row->ID . '"';
                $JsonRecords .= '}';
                if ($i < $n - 1)
                    $JsonRecords .= ',';
                $i++;
            }
        $JsonRecords .= ']}';

        //$resul= '{"supplier":['. json_encode($this->supplier_model->suppliermaster_all()).']}';
        echo $JsonRecords;
    }

    public function refreshProject() {
        //for ajax call 
        $this->load->model('Project/project_model');
        $project = $this->project_model->project_all();

        //json_encode ($this->project_model->project_all());

        $JsonRecords = '{"records":[';
        $n = sizeof($project);
        $i = 0;
        if ($project)
            foreach ($project as $row) {
                $JsonRecords .= '{';
                $JsonRecords .= '"id":"' . $row->ID . '","projectName":"' . $row->project_name . '"';
                $JsonRecords .= '}';
                if ($i < $n - 1)
                    $JsonRecords .= ',';
                $i++;
            }
        $JsonRecords .= ']}';

        //$resul= '{"supplier":['. json_encode($this->supplier_model->suppliermaster_all()).']}';
        echo $JsonRecords;
    }

    function getTermDescription() {
        $this->load->model('terms/terms_model');
        $JsonRecords = '';
        $default = $this->terms_model->terms_id($this->input->post('term'));
        if ($default != false) {
            foreach ($default as $row)
                $JsonRecords = $row->termDescription;
            echo $JsonRecords;
        } else
            echo "Term not found";
    }

    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'),
                '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);
            
            echo '{"status":"success","invoiceID":"' . $queryRes . '","detailID":"' . $query . '"}';
        } else {
            echo "false";
        }
    }

    public function updateInvoice() {
        $this->load->model('accountPayable/accountPayable_model');
        $invoiceUpdate = array(
            'updatedBy' => element('role', $this->session->userdata('logged_in')),
            'totalTaxAmount' => $this->input->post('totalamount'),
            'totalPayable' => $this->input->post('totalPayable'),
        );
        $this->accountPayable_model->updateInvoice($this->input->post('invoiceId'), $invoiceUpdate);
    }

    function saveParchaseDetail() {
       
        $this->load->model('accountPayable/accountPayable_model');
        $datinsertDetails = array(
            'invoiceID' => $this->input->post('invoiceId'),
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'itemID' => $this->input->post('itemID'),
            'lineNo' => $this->input->post('lineNo'),
            'itemdescription' => $this->input->post('itemdescription'),
            'quantity' => $this->input->post('quantity'),
            'unitPrice' => $this->input->post('unitPrice'),
            'amountExcludedTax' => $this->input->post('amountExcludedTax'),
            'taxID' => $this->input->post('taxID'),
            'taxRate' => $this->input->post('taxRate'),
            'taxAmount' => $this->input->post('taxAmount'),
            'amountIncludedTax' => $this->input->post('amountIncludeTax')
        );
        $query = $this->accountPayable_model->insert('comp_supplier_invoice_detail', $datinsertDetails);
        $detail = $this->accountPayable_model->getLasIdInsert("comp_supplier_invoice_detail");
        
        $this->accountPayable_model->updateMaster("comp_supplier_invoice",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));

        echo '{"status":"success","detailID":"' . $detail . '"}';
    }

    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_invoice",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_invoice", $this->input->post('code'));
    }

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

    public function saveCharge() {
        $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')),
            'currencyID' => $this->input->post('currencyID'),
            'purchaseInvoiceCodeID' => 2,
            'supplierID' => $this->input->post('supplierID'),
            'formNo' => $this->input->post('formNo'),
            'shipToID' => $this->input->post('shipToID'),
            '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'),
            'shippingMethodID' => $this->input->post('shippingMethodID'),
            'purchaserID' => $this->input->post('employeeID'),
            'memo' => $this->input->post('memo')
        );


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


        if ($query>0) {

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

    function deleteCharge() {
        $this->load->model('accountPayable/accountPayable_model');
        echo $this->accountPayable_model->delete($this->input->post('chargeID'), "comp_supplier_invoice_charges");
        $this->accountPayable_model->updateMaster("comp_supplier_invoice",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        
    }

    function deleteChargeOnly() {
    	$this->load->model('accountPayable/accountPayable_model');
    	echo $this->accountPayable_model->delete($this->input->post('chargeID'), "comp_supplier_invoice_charges");
    
    }
    
    public function saveChargeDetailOnly() {

        $this->load->model('accountPayable/accountPayable_model');
        $datinsertDetails = array(
            'invoiceID' => $this->input->post('invoiceId'),
            'lineNo' => $this->input->post('lineNo'),
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'accountNoID' => $this->input->post('accountNoID'),
            'chargeDescription' => $this->input->post('itemdescription'),
            'amountExcludedTax' => $this->input->post('amountExcludedTax'),
            'taxID' => $this->input->post('taxID'),
            'taxAmount' => $this->input->post('taxAmount'),
            'amountIncludedTax' => $this->input->post('amountIncludedTax'),
        );
        $detail = $this->accountPayable_model->insert('comp_supplier_invoice_charges', $datinsertDetails);
        $this->accountPayable_model->updateMaster("comp_supplier_invoice",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));
        echo '{"status":"success","chargeId":"' . $detail . '"}';
    }

    public function refreshLocation() {
        //for ajax call 
        $this->load->model('location');
        $location = $this->location->location_all();

        //json_encode ($this->project_model->project_all());

        $JsonRecords = '{"records":[';
        $n = sizeof($location);
        $i = 0;
        if ($location)
            foreach ($location as $row) {
                $JsonRecords .= '{';
                $JsonRecords .= '"id":"' . $row->fldid . '","location":"' . $row->code . ' | ' . $row->address . ' | ' . $row->city . '"';
                $JsonRecords .= '}';
                if ($i < $n - 1)
                    $JsonRecords .= ',';
                $i++;
            }
        $JsonRecords .= ']}';

        //$resul= '{"supplier":['. json_encode($this->supplier_model->suppliermaster_all()).']}';
        echo $JsonRecords;
    }

    public function updateCharge() {
        $update = array(
            'updatedBy' => element('role', $this->session->userdata('logged_in')),
            'accountNoID' => $this->input->post('accountNoID'),
            'chargeDescription' => $this->input->post('itemdescription'),
            'amountExcludedTax' => $this->input->post('amountExcludedTax'),
            'taxID' => $this->input->post('taxID'),
            'taxAmount' => $this->input->post('taxAmount'),
            'amountIncludedTax' => $this->input->post('amountIncludedTax'),
        );
        $this->load->model('accountPayable/accountPayable_model');
        echo $this->accountPayable_model->update_charge($this->input->post('chargeId'), $update);
        $this->accountPayable_model->updateMaster("comp_supplier_invoice",array("totalTaxAmount","totalAmount"), $this->input->post('masterId'));
    }

    function getItemDetails() {
        $JsonRecords = '{';
        $i = 0;
        $this->load->model('item/itemSetup_model');
        $default = $this->itemSetup_model->get_byCode($this->input->post('code'));
        //$default = $this->itemSetup_model->get_all();
        $n = sizeof($default);
        //print json_encode(array("status"=>"success", "message"=>$query));
        if ($default) {
            foreach ($default as $row) {

                $tax = "0";
                $taxcode = "...";
                $this->load->model('taxmaster');
                $taxObj = $this->taxmaster->taxmaster_id($row->inputTaxID);
                if ($taxObj) {
                    foreach ($taxObj as $taxrow) {
                        $tax = $taxrow->taxPercentage;
                        $taxcode = $taxrow->code;
                    }
                }
                $JsonRecords .= '"taxcode":"' . $taxcode . '","name":"' . $row->itemCode . '","description":"' . $row->description . '", "tax":"' . $tax . '", "taxID":"' . $row->inputTaxID . '"';
                if ($i < $n - 1)
                    $JsonRecords .= ',';
                $i++;
            }
            $JsonRecords .= '}';
            echo $JsonRecords;
        }else {
            echo "item Not found";
        }
    }

    public function __reset() {
        $data = array('ID' => 0, 'itemName' => '');
    }

    //// Edit purchase invoice

    function editInvoices($id) {

        $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->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->load->model('Usermaster');
        $data['records'] = $this->Usermaster->usermaster_all();
        
        $this->load->model('item/itemSetup_model');
        $data['items'] = $this->itemSetup_model->get_all();

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

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

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

        $this->layouts->view('purchase/transactions/editdirectpurchaseinvoice', '', $data);
    }

// purchase invoice end
// purchase received
// Yahaya Abdollah

	public function receiveItemPosting() {
		//$ID = isset($_REQUEST['ID'])?$_REQUEST['ID']:"";
		$mode = $this->uri->segment(5);
		$this->load->library('layouts');
		$this->lang->load("receiveItem",$this->session->userdata('language'));
		$this->load->model('company/FormSetup_model');
		$this->load->model('purchase/purchase_model');
		$this->load->model('Compfinancialyear');
		$this->load->model('company/FormSetup_model');
		$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('+7 year')), 1900);
		$data['selyear'] = $add_year;
		$data['selper'] = $add_period;
		$data['datatbls'] = $this->purchase_model->receiveItemDate_unpost($startDate, $endDate);
		
//		echo $this->db->last_query();
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('purchase/transactions/receiveItemPost', array('latest' => 'sidebar/latest'), $data);
	}
	public function receiveItemPost(){
		$this->lang->load("receiveItem",$this->session->userdata('language'));
		$ID = $this->input->post('fldid');
		$effdate = date("Y-m-d", strtotime($this->input->post('effdate')));
		$this->load->model('purchase/purchase_model');
		$queryDetails = $this->purchase_model->purchaseReceiveDetails_ID($ID);
//		echo var_dump($queryDetails);
		$data = array(
			'updateAble'=>'0'
		);
		$query = $this->purchase_model->purchaseReceivePost($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) . ']';
			}else{
   				print json_encode(array("status"=>"failed", "message"=>$query1));
				return FALSE;
			}
 			$this->load->model('Glseq');
			$query2 = $this->Glseq->glSequence_sub('8', 'PO', $year, $period);
			$newData = array(
				'companyID' => element('compID', $this->session->userdata('logged_in')),
				'journalID' => $query2['seqNumber'],
				'formNo' => $formNo,
				'description' => $this->lang->line('message2') . ' [ ' . $formNo . ' ]',
				'module' => '8',
				'effective_date' => $effdate,
				'year' => $year,
				'period' => $period,
				'createdBy' => element('role', $this->session->userdata('logged_in'))
			);
			$data = array(
				'journalNo'=>$query2['seqNumber']
			);
			$query5 = $this->purchase_model->purchaseReceive_Update($ID, $data);
			$this->load->model('Journal');
			$query3 = $this->Journal->journal_insert($newData); 
			if($query3){
				$query4 = $this->purchase_model->purchaseReceiveDetails_receiveID($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{
  				print json_encode(array("status"=>"failed", "message"=>$query));
			return FALSE;
		} 
	}
	
}

/* End of file purchasetransaction.php */
/* Location: ./application/controller/purchasetransaction.php */
