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

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

	public function index(){
		
	}
        
        public function jsonToArray($json) {
            $object = json_decode ( $this->input->post('pdetail') );
            if (is_object ( $object )) {
                    foreach ( $object as $key => $value ) {
                            $array [$key] = $value;
                    }
            } else {
                    $array = $object;
            }
            return $array;
	}
        
        public function getPrice(){
            $this->load->model('item/itemSetup_model');
            echo $this->itemSetup_model->getItemPrice($this->input->post('option'), $this->input->post('itemID'),$this->input->post('datePrice'), $this->input->post('customerID'), $this->input->post('umID'), $this->input->post('currencyID'));
        }


        public function newDirectSaleInvoice(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARDSLINV');
        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("saleInvoice",$this->session->userdata('language'));
			$this->load->model('companyChartAcct');
		
			$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('address_model');
			$data['shipto'] = '';//$this->address_model->getCompanyAdresses();
			
			$this->load->model('employee/employee_model');
			$data['saler'] = $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('customer/Customer_model');
			$data['customer'] = $this->Customer_model->customermaster_all();
			
			$this->load->model('SaleAgent/Agent_model');
			$data['agent'] = $this->Agent_model->agent_all();
			
			$this->load->model('companyChartAcct');
			$data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();
			
			
			$this->load->model('taxmaster');
			$data['taxmaster'] = $this->taxmaster->taxmaster_saleOutput();
			
			$data['itemCodes'] = $this->getItemCodes();
			
//			$this->load->model('company/formSetup_Model');
			$filter['companyID']=element('compID', $this->session->userdata('logged_in'));
			$filter['formID']=50;
			$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('ar/transaction/newDirectSaleInvoice', '', $data);
	}
        
        /////// cash pay
        
        
        public function newcashsale(){
             $this->load->model('UseraccessDetails');
                $query = $this->UseraccessDetails->UseraccessDetails_id_code('APOPWI');
        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("cashsale",$this->session->userdata('language'));
			$this->load->model('companyChartAcct');
		
			$this->load->model('Usermaster');
			$data['records'] = $this->Usermaster->usermaster_all();
			
			$this->load->model('master/masterCode_model');
			$filter['masterID']=7;
			$data['paymentmethod'] = $this->masterCode_model->get_all($filter);
			
			
			$this->load->model('Project/project_model');
			$data['project'] = $this->project_model->project_all();
			
			$this->load->model('location');
			$data['location'] = $this->location->location_all();
			
			
			$this->load->model('taxmaster');
			$data['taxmaster'] = $this->taxmaster->taxmaster_saleOutput();
			
			$this->load->model('item/itemSetup_model');
                        $data['items'] = $this->itemSetup_model->get_all(true);
			
			$this->load->model('bank/bank_model');
			$data['bankaccount'] = $this->bank_model->bank_all();
			
//			$this->load->model('company/formSetup_Model');
			$filter['companyID']=element('compID', $this->session->userdata('logged_in'));
			$filter['formID']=121;
			$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('ar/transaction/newcashsale', '', $data);
        }
        
       public function savenewcashpay(){
            
         $this->load->model('ar/saleInvoice_model');

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

            $datainsert = array (
                    'bankID' => $this->input->post('bankID'),
                    'paymentFrom' => $this->input->post('paymentFrom'),
                    'formNo' => $this->input->post('formNo'),
                    'salesInvoiceDate' => date('Y-m-d', strtotime($this->input->post('salesInvoiceDate'))),
                    'projectID' => $this->input->post('projectID'),
                    'amountReceived' => $this->input->post('amountReceived'),
                    'referenceNo' => $this->input->post('referenceNo'),
                    'paymentMethodID' => $this->input->post('paymentMethodID'), 
                    'locationID' => $this->input->post('locationID'), 
                    'outOfBalance' => $this->input->post('outOfBalance'),
                    'totalAmountIncludeTax' => $this->input->post('amountIncludedTax'),
                    'totalTaxAmount' => $this->input->post('taxAmount'),
                    'memo' => $this->input->post('memo'),
                    'companyID' => $companyID,
                    'createdBy' => element('role', $this->session->userdata('logged_in'))
            );

             $invID = $this->saleInvoice_model->insert("comp_cash_sales",$datainsert);

            if($invID){

                    $datinsertDetails = array (
                    'invoiceID' =>  $invID,
                    'createdBy' => element('role', $this->session->userdata('logged_in')),
                    'itemID' => $this->input->post('itemID'),
                    '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')
            );
             $detail = $this->saleInvoice_model->insert('comp_cash_sales_detail',$datinsertDetails);
             //$this->saleInvoice_model->updateMaster("comp_sales_invoice",array("totalTaxAmount","totalAmount"), $invID);
             
             echo '{"status":"success","invoiceID":"'.$invID.'","detailID":"'.$detail.'"}';
            }else{
                    echo "false";
            }
	}
        
       
        
        public function savenewcashpayDetailOnly(){
            $this->load->model('ar/saleInvoice_model');
            $datinsertDetails = array (
                    'invoiceID' =>  $this->input->post('paymentId'),
                    'createdBy' => element('role', $this->session->userdata('logged_in')),
                    'itemID' => $this->input->post('itemID'),
                    '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')
            );
             $detail = $this->saleInvoice_model->insert('comp_cash_sales_detail',$datinsertDetails);
            
            $de = $this->saleInvoice_model->updateCashSaleTotal($this->input->post('paymentId'));
             echo '{"status":"success","detailID":"'.$detail.'"}';
        }
        
        
        public function editcashsale($id){
            $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APTRPYIE');
        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->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("cashsale",$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('taxmaster');
			$data['taxmaster'] = $this->taxmaster->taxmaster_saleOutput();
			
			$this->load->model('accountPayable/othersPayment_model');
                        $data['master'] = $this->saleInvoice_model->getDataByTname("cashpayMaster",$id);
                        $this->load->model('item/itemSetup_model');
                        
                        if($data['master']){
                             $data['items'] = $this->itemSetup_model->getItemListByLocation($data['master'][0]->locationID);
                             //var_dump($data['items']);
			$data['pdetails'] = $this->saleInvoice_model->getDataByTname("cashpayDetail",$id);
                        }
			$this->layouts->view('ar/transaction/editcashsale', '', $data);
	}
	
        public function updatecashsale(){
            $this->load->model('ar/saleInvoice_model');
            $datinsertDetails = array (
                    'updatedBy' => element('role', $this->session->userdata('logged_in')),
                    'itemID' => $this->input->post('itemID'),
                    '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')
            );
              $success = $this->saleInvoice_model->update_byID("comp_cash_sales_detail",$this->input->post('rowID'),$datinsertDetails);
              $de = $this->saleInvoice_model->updateCashSaleTotal($this->input->post('paymentId'));
              echo '{"status":"success","detailID":"'.$success.'"}';  
        }
        
        
         /// 11-5-2014
     function updatecashSaleMaster(){
           $this->load->model('ar/saleInvoice_model');
			$data = array (
			'updatedBy' => element('role', $this->session->userdata('logged_in')),
			'amountReceived' => $this->input->post('amount'), 
                        'memo' => $this->input->post('memo'), 
			'referenceNo' => $this->input->post('refNo'),
                         'projectID' => $this->input->post('project'),
                         'salesInvoiceDate' => date("Y-m-d",strtotime($this->input->post('date')))   
		);
		echo $query = $this->saleInvoice_model->update_byID('comp_cash_sales',$this->input->post('masterID'), $data);
        }
        
        public function deletecashsaleRow(){
            $this->load->model('ar/saleInvoice_model');
            $detail = $this->saleInvoice_model->delete_byID("comp_cash_sales_detail",$this->input->post('rowID'));
             $de = $this->saleInvoice_model->updateCashSaleTotal($this->input->post('paymentId'));
            echo '{"status":"'.$detail.'"}';
       
        }
		
		public function cashsalePost(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARCASHSC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
			$add_year = $this->uri->segment(3);
			$add_period = $this->uri->segment(4);
			if(!$add_year){
				$add_year = date("Y");
			}
			if(!$add_period){
				$add_period = date("m");
			}
			$this->lang->load("cashsale",$this->session->userdata('language'));
			$this->load->model('ar/cashsale_model');
			$this->load->model('company/FormSetup_model');
			$this->load->model('Compfinancialyear');
			//$data['yrs'] = range(date('Y'), 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;
			$query = $this->Compfinancialyear->financialYear_year($add_year);
			if($query){
				$data['period'] = $query;
			}else{
				$data['period'] = NULL;
			}
			$queryCal = $this->Compfinancialyear->financialYear_yearperiod($add_year, $add_period);
			
			if($queryCal){
				$data['datatbls'] = $this->cashsale_model->cashsaleview_all($queryCal[0]->startDate, $queryCal[0]->endDate);
				//echo $this->db->last_query();
				//return;
			}else{
				$data['datatbls'] = NULL;
			}
			$this->load->library('layouts');
			$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
			$this->layouts->view('ar/transaction/cashsalepostlist', array('latest' => 'sidebar/latest'), $data);
		}
        
		//Update Updateable to 0
		//Post to table journal
		public function cashsalelistPosting(){
			$this->load->model('UseraccessDetails');
        	$query = $this->UseraccessDetails->UseraccessDetails_id_code('ARCASHSC');
        	if (!$query) {
            	echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        	}
			$this->lang->load("cashsale",$this->session->userdata('language'));
			$ID = $this->input->post('fldid');
			$effdate = date("Y-m-d", strtotime($this->input->post('effdate')));
			$this->load->model('ar/cashsale_model');

//			$queryDetails = $this->cashsale_model->directsalesinvDetails_ID($ID); //structure must same as controller/sotransaction.php/doposting 
			$queryDetails = $this->cashsale_model->cashsale_getDetail_for_post($ID);
                        //var_dump($queryDetails);
			$query = $this->cashsale_model->cashsale_post($ID);
                       //  var_dump($query);
			//echo '<br>query='.$this->db->last_query();
			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;
					$total_amount_dr = ($query[0]->totalamount + $query[0]->totalTaxAmount) * $query[0]->exchangeRate;
					$total_amount_cr = ($query[0]->totalamount + $query[0]->totalTaxAmount) * $query[0]->exchangeRate;
				}else{
   					print json_encode(array("status"=>"failed", "message"=>$query1));
					return FALSE;
				}
 				$this->load->model('Glseq');
				$query2 = $this->Glseq->glSequence_sub('2', 'AR', $year, $period);
				$newData = array(
					'companyID' => element('compID', $this->session->userdata('logged_in')),
					'journalID' => $query2['seqNumber'],
					'formNo' => $formNo,
					'description' => $this->lang->line('title') . ' [ ' . $formNo . ' ]',
					'module' => '2',
					'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'],
					'updateAble' => '0'
				);
				$query5 = $this->cashsale_model->cashSalesposting_Update($ID, $data);
				$this->load->model('Journal');
				$query3 = $this->Journal->journal_insert($newData);
				if($query3){
//					$query4 = $this->directsalesinv_model->directsalesinv_invoiceID($query2['seqNumber'], $query[0], $queryDetails, $year, $period);
//will reuse do method during posting created by sayem -akmal 20141107
//copy from controller/sotransaction.php		$this->SalesDeliveryOrder->SalesDeliveryOrderdetails_deliveryID($query2['seqNumber'], $query[0], $queryDetails, $year, $period);
//					$this->load->model('SalesDeliveryOrder');
//					$query[0]->type = 'cashSale';
//					$query4 = $this->SalesDeliveryOrder->SalesDeliveryOrderdetails_deliveryID($query2['seqNumber'], $query[0], $queryDetails, $year, $period);
					$this->load->model('items');
					$query[0]->type = 'cashSale';
					$query4 = $this->items->itemReducePosting($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;
			}
		}
		
		/*public function cashsalelistPosting(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARSCNC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
		$this->lang->load("cashsale",$this->session->userdata('language'));
		$ID = $this->input->post('fldid');
		$effdate = date("Y-m-d", strtotime($this->input->post('effdate')));
		$this->load->model('ar/cashsale_model');
		$queryDetails = $this->cashsale_model->cashsaleDetails_ID($ID);
		$data = array(
			'updateAble'=>'0'
		);
		$query = $this->cashsale_model->cashsale_post($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) . ']';
				$total_amount_dr = ($query[0]->totalAmount + $query[0]->totalTaxAmount) * $query[0]->exchangeRate;
				$total_amount_cr = ($query[0]->totalAmount + $query[0]->totalTaxAmount) * $query[0]->exchangeRate;
			}else{
   				print json_encode(array("status"=>"failed", "message"=>$query1));
				return FALSE;
			}
 			$this->load->model('Glseq');
			$query2 = $this->Glseq->glSequence_sub('2', 'AR', $year, $period);
			$newData = array(
				'companyID' => element('compID', $this->session->userdata('logged_in')),
				'journalID' => $query2['seqNumber'],
				'formNo' => $formNo,
				'description' => $this->lang->line('message2') . ' [ ' . $formNo . ' ]',
				'module' => '2',
				'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->salescreditnote_model->salescreditnote_Update($ID, $data);
			$this->load->model('Journal');
			$query3 = $this->Journal->journal_insert($newData);
			if($query3){
				$query4 = $this->salescreditnote_model->salescreditnoteDetails_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;
		}
	}
		*/
        /// cash pay
	

	public function directsalesinvPost(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARDRSINV');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
		$add_year = $this->uri->segment(3);
		$add_period = $this->uri->segment(4);
		if(!$add_year){
			$add_year = date("Y");
		}
		if(!$add_period){
			$add_period = date("m");
		}
		$this->lang->load("salesNDI",$this->session->userdata('language'));
		$this->load->model('directsalesinv_model');
		$this->load->model('company/FormSetup_model');
		$this->load->model('Compfinancialyear');
		//$data['yrs'] = range(date('Y'), 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;
		$query = $this->Compfinancialyear->financialYear_year($add_year);
		if($query){
			$data['period'] = $query;
		}else{
			$data['period'] = NULL;
		}
		$queryCal = $this->Compfinancialyear->financialYear_yearperiod($add_year, $add_period);
		if($queryCal){
			$data['datatbls'] = $this->directsalesinv_model->directsalesinv_unpost($queryCal[0]->startDate, $queryCal[0]->endDate);
		}else{
			$data['datatbls'] = NULL;
		}
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('ar/transaction/directsaleinvPost', array('latest' => 'sidebar/latest'), $data);
	}
	public function directInvoicePosting(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARDRSINV');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
		$this->lang->load("salesNDI",$this->session->userdata('language'));
		$ID = $this->input->post('fldid');
		$effdate = date("Y-m-d", strtotime($this->input->post('effdate')));
		$this->load->model('directsalesinv_model');
		$queryDetails = $this->directsalesinv_model->directsalesinvDetails_ID($ID);
		$data = array(
			'updateAble'=>'0'
		);
		$query = $this->directsalesinv_model->directsalesinv_post($ID, $data);
		if($query){
		//problem in the direct sale invoice. akmal 20141127
		//delay the updateAble later. 
		//1. create auto do
		//2. reselect $queryDetails
		//3. set updateAble = 0

//		if ($queryDetails) {
		//auto create do for direct sale invoice. 
		$journalTitle = '';
            if ($query[0]->invoiceCodeID == 2) {
				$journalTitle = $this->lang->line('message2');
				$soID = $this->directsalesinv_model->saveDeleveryOrderFromDirect($ID);
				$query = $this->directsalesinv_model->directsalesinv_post($ID, $data);
			} else 
				$journalTitle = $this->lang->line('message3');

			$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) . ']';
				$total_amount_dr = ($query[0]->totalamount + $query[0]->totalTaxAmount) * $query[0]->exchangeRate;
				$total_amount_cr = ($query[0]->totalamount + $query[0]->totalTaxAmount) * $query[0]->exchangeRate;
			}else{
   				print json_encode(array("status"=>"failed", "message"=>$query1));
				return FALSE;
			}
 			$this->load->model('Glseq');
			$query2 = $this->Glseq->glSequence_sub('2', 'AR', $year, $period);
			$newData = array(
				'companyID' => element('compID', $this->session->userdata('logged_in')),
				'journalID' => $query2['seqNumber'],
				'formNo' => $formNo,
				'description' => $journalTitle . ' [ ' . $formNo . ' ]',
				'module' => '2',
				'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'],
				'updateAble'=>'0'
			);
			$queryDetails = $this->directsalesinv_model->directsalesinvDetails_ID($ID);
			$query5 = $this->directsalesinv_model->directsalesinv_Update($ID, $data);
			$this->load->model('Journal');
			$query3 = $this->Journal->journal_insert($newData);
			if($query3){
				$query4 = $this->directsalesinv_model->directsalesinv_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;
		}
	}
        
        public function createSaleDo(){
            
        }
	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(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 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 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->desc . '"';
                $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;
	}
	
	public function saveNewDirectSaleInvoice(){
            $this->load->model('ar/saleInvoice_model');

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

            $datainsert = array (
                    'invoiceCodeID' => 2,
                    'customerID' => $this->input->post('customerID'),
                'currencyID' => $this->input->post('currencyID'),
                    'formNo' => $this->input->post('formNo'),
                    'salesInvoiceDate' => date('Y-m-d', strtotime($this->input->post('invoiceDate'))),
                    'customerPoNo' => $this->input->post('customerPoNo'),
                    'projectID' => $this->input->post('projectID'),
                    'agentID' => $this->input->post('agentID'),
                    'termsID' => $this->input->post('termsID'),
                    'shipToID' => $this->input->post('shipToID'), 
                    'customerID' => $this->input->post('customerID'),
                    'exchangeRate' => $this->input->post('exchangeRate'), 
                    'locationID' => $this->input->post('locationID'), 
                    'exchangeRate' => $this->input->post('exchangeRate'),
                    'totalTaxAmount' => $this->input->post('totalTaxAmount'),
                 'totalReceivable' => $this->input->post('amountIncludedTax'),
                'totalamount' => $this->input->post('amountIncludedTax'),
                    'memo' => $this->input->post('memo'),
                    'locationID' => $this->input->post('locationID'), 
                    'employeeID' => $this->input->post('employeeID'),
                    'shippingMethodID' => $this->input->post('shippingMethodID'),
                    'companyID' => $companyID,
                    'createdBy' => element('role', $this->session->userdata('logged_in')),
                
                     "showSaleAgent" => $this->input->post('showinInvoice')
            );

             $invID = $this->saleInvoice_model->insert("comp_sales_invoice",$datainsert);

            if($invID){

                    $datinsertDetails = array (
                    'invoiceID' =>  $invID,
                    'lineNo' => $this->input->post('lineNo'),
                    'createdBy' => element('role', $this->session->userdata('logged_in')),
                    'itemID' => $this->input->post('itemID'),
                    'quantity' => $this->input->post('quantity'),
                        'umID' => $this->input->post('umid'),
                        'itemdescription' => $this->input->post('itemdescription'),
                    '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')
            );
             $detail = $this->saleInvoice_model->insert('comp_sales_invoice_detail',$datinsertDetails);
             $this->saleInvoice_model->updateMaster("comp_sales_invoice",array("totalTaxAmount","totalAmount"), $invID);
             
             echo '{"status":"success","invoiceID":"'.$invID.'","detailID":"'.$detail.'"}';
            }else{
                    echo "false";
            }
	}
        
        public function saveNewSaleDetailOnly(){
            $this->load->model('ar/saleInvoice_model');
            $datinsertDetails = array (
            'invoiceID' =>  $this->input->post('invoiceId'),
             'lineNo' => $this->input->post('lineNo'),
            'createdBy' => element('role', $this->session->userdata('logged_in')),
            'itemID' => $this->input->post('itemID'),
            'quantity' => $this->input->post('quantity'),
                'umID' => $this->input->post('umid'),
                'itemdescription' => $this->input->post('itemdescription'),
            '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')
            );
             $detail = $this->saleInvoice_model->insert('comp_sales_invoice_detail',$datinsertDetails);
            
             $tota = $this->input->post('amountIncludedTax') + $this->input->post('currentTotalInvoice');
             $totaUpdate = array ("totalReceivable" => $tota, "totalamount" => $tota);
             $this->saleInvoice_model->update_byID("comp_sales_invoice", $this->input->post('invoiceId'),$totaUpdate );
             $this->saleInvoice_model->updateMaster("comp_sales_invoice",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'));   
             echo '{"status":"success","detailID":"'.$detail.'"}';
        }
        
        public function saveNewDirectSaleInvoiceCharges(){
            $this->load->model('ar/saleInvoice_model');

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

            $datainsert = array (
                    'invoiceCodeID' => 2,
                    'customerID' => $this->input->post('customerID'),
                    'formNo' => $this->input->post('formNo'),
                    'salesInvoiceDate' => date('Y-m-d', strtotime($this->input->post('invoiceDate'))),
                    'customerPoNo' => $this->input->post('customerPoNo'),
                    'projectID' => $this->input->post('projectID'),
                    'agentID' => $this->input->post('agentID'),
                    'termsID' => $this->input->post('termsID'),
                    'shipToID' => $this->input->post('shipToID'), 
                    'customerID' => $this->input->post('customerID'),
                    'exchangeRate' => $this->input->post('exchangeRate'), 
                    'locationID' => $this->input->post('locationID'),
                     "currencyID" => $this->input->post('currencyID'),
                
                    'exchangeRate' => $this->input->post('exchangeRate'),
                    'memo' => $this->input->post('memo'),
                    'locationID' => $this->input->post('locationID'), 
                    'employeeID' => $this->input->post('employeeID'),
                    'shippingMethodID' => $this->input->post('shippingMethodID'),
                    'companyID' => $companyID,
                    'createdBy' => element('role', $this->session->userdata('logged_in')),
                
                    'totalTaxAmount' => $this->input->post('totalTaxAmount'),
                    'totalReceivable' => $this->input->post('amountIncludedTax'),
                    'totalamount' => $this->input->post('amountIncludedTax'),
                
                     "showSaleAgent" => $this->input->post('showinInvoice')
            );


             $invID = $this->saleInvoice_model->insert("comp_sales_invoice",$datainsert);

            if($invID){

                    $datinsertDetails = array (
                    'invoiceID' =>  $invID,
                    'lineNo' => $this->input->post('lineNo'),
                    'createdBy' => element('role', $this->session->userdata('logged_in')),
                    'accountNoID' => $this->input->post('accountNoID'),
                    'chargeDescription' => $this->input->post('chargeDescription'),
                    '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->saleInvoice_model->insert('comp_sales_invoice_charges',$datinsertDetails);
             $this->saleInvoice_model->updateMaster("comp_sales_invoice",array("totalTaxAmount","totalAmount"), $invID);
             echo '{"status":"success","invoiceID":"'.$invID.'","detailID":"'.$detail.'"}';
            }else{
                    echo "false";
            }
	}
        
        public function saveNewSaleDetailOnlyCharges(){
            $this->load->model('ar/saleInvoice_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('chargeDescription'),
                    '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->saleInvoice_model->insert('comp_sales_invoice_charges',$datinsertDetails);
           /* first way to up master  
             $tota = $this->input->post('amountIncludedTax') + $this->input->post('currentTotalInvoice');
             $tax = $this->input->post('taxAmount') + $this->input->post('currentTaxAmount');
            $totaUpdate = array (
                 "totalTaxAmount" =>$tax,
                 "totalReceivable" => $tota, 
                 "totalamount" => $tota);
             $this->saleInvoice_model->update_byID("comp_sales_invoice", $this->input->post('invoiceId'),$totaUpdate );
             */
             $this->saleInvoice_model->updateMaster("comp_sales_invoice",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'),true);
             
             echo '{"status":"success","detailID":"'.$detail.'"}';
        }
        
        public function getItemList(){
            $this->load->model('item/ItemSetup_model');
            $itemList = $this->ItemSetup_model->getItemListByLocation($this->input->post('idLocation'));
            if($itemList){
                echo json_encode(array("status"=>"success", "recordSet"=>$itemList));
            }
            else{
                echo json_encode(array("status"=>"false", "message"=>$itemList,));
            }
        }
                
	public 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";
	}
        
        public function editDirectSaleInvoice($id){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARTRINED');
        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("saleInvoice",$this->session->userdata('language'));
            
            $this->load->model('companyChartAcct');

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

            $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(true);

            $this->load->model('companyChartAcct');
            $data['chargeAccount'] = $this->companyChartAcct->chartAcct_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('customer/Customer_model');
			$data['customer'] = $this->Customer_model->customermaster_all();

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

            $this->load->model('ar/saleInvoice_model');
            
            $data['invoice']=$this->saleInvoice_model->getDataByTname("comp_sales_invoice",$id);
            
            $data['items']=$this->saleInvoice_model->getDataByTname("comp_sales_invoice_detail",$id);
            $data['charges']=$this->saleInvoice_model->getDataByTname("comp_sales_invoice_charges",$id);

            $this->layouts->view('ar/transaction/editDirectSaleInvoice', '', $data);
        }
        
        public function updateRowDetail(){
            $this->load->model('ar/saleInvoice_model');
            $rowArray = array (
            'updatedBy' => 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'),
            'unitPrice' => $this->input->post('unitPrice'),
            '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')
            );
             $success = $this->saleInvoice_model->update_byID("comp_sales_invoice_detail",$this->input->post('rowID'),$rowArray);
            
             $this->saleInvoice_model->updateMaster("comp_sales_invoice",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'), true);
             echo '{"status":"'.$success.'"}';
        }
        
        public function updateCharge(){
             $this->load->model('ar/saleInvoice_model');
             $rowArray = array (
                    'updatedBy' => element('role', $this->session->userdata('logged_in')),
                    'accountNoID' => $this->input->post('accountNoID'),
                    'chargeDescription' => $this->input->post('chargeDescription'),
                    '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->saleInvoice_model->update_byID("comp_sales_invoice_charges",$this->input->post('rowID'),$rowArray);
             $this->saleInvoice_model->updateMaster("comp_sales_invoice",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'), true);
             
             echo '{"status":"'.$detail.'"}';
        }
        
        
         public function updateDebitNoteCharge(){
             $this->load->model('ar/saleInvoice_model');
             $rowArray = array (
                    'updatedBy' => element('role', $this->session->userdata('logged_in')),
                    'accountNoID' => $this->input->post('accountNoID'),
                    'chargeDescription' => $this->input->post('chargeDescription'),
                    '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->saleInvoice_model->update_byID("comp_sales_debitnote_charges",$this->input->post('rowID'),$rowArray);
             $this->saleInvoice_model->updateMaster("comp_sales_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('masterId'));
             echo '{"status":"'.$detail.'"}';
        }
        
        
         public function updateCreditNoteCharge(){
             $this->load->model('ar/saleInvoice_model');
             $rowArray = array (
                    'updatedBy' => element('role', $this->session->userdata('logged_in')),
                    'accountNoID' => $this->input->post('accountNoID'),
                    'chargeDescription' => $this->input->post('chargeDescription'),
                    '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->saleInvoice_model->update_byID("comp_sales_creditnote_charges",$this->input->post('rowID'),$rowArray);
             $this->saleInvoice_model->updateMaster("comp_sales_creditnote",array("totalTaxAmount","totalAmount"), $this->input->post('masterID'));
             
             echo '{"status":"'.$detail.'"}';
        }
        
        public function deleteSaleItemRow(){
            $this->load->model('ar/saleInvoice_model');
            $detail = $this->saleInvoice_model->delete_byID("comp_sales_invoice_detail",$this->input->post('rowID'));
             $this->saleInvoice_model->updateMaster("comp_sales_invoice",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'), true);
            echo '{"status":"'.$detail.'"}';
        }
        
        
         public function deleteNormalSaleItemRow(){
            $this->load->model('ar/saleInvoice_model');
            $detail = $this->saleInvoice_model->delete_byID("comp_sales_invoice_detail",$this->input->post('rowID'));
             $this->saleInvoice_model->updateMaster("comp_sales_invoice",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'), true);
           // $detail = $this->saleInvoice_model->updateDeleveriDetailAfterdelete($this->input->post('deliveryID'),$this->input->post('itemID'),array("invoiceID"=>0));
             $detail = $this->saleInvoice_model->update_byID('comp_delivery_detail',$this->input->post('deliveryID'),array("invoiceID"=>0));
             echo '{"status":"'.$detail.'"}';
        }
        
         public function deleteSaleDebitCharge(){
            $this->load->model('ar/saleInvoice_model');
            $detail = $this->saleInvoice_model->delete_byID("comp_sales_debitnote_charges",$this->input->post('rowID'));
            $this->saleInvoice_model->updateMaster("comp_sales_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('masterId'));
            echo '{"status":"'.$detail.'"}';
        }
        
         public function deleteSaleCreditCharge(){
            $this->load->model('ar/saleInvoice_model');
            $detail = $this->saleInvoice_model->delete_byID("comp_sales_creditnote_charges",$this->input->post('rowID'));
            $this->saleInvoice_model->updateMaster("comp_sales_creditnote",array("totalTaxAmount","totalAmount"),$this->input->post('masterId') );
            echo '{"status":"'.$detail.'"}';
        }
        
        public function deleteSaleCharge(){
            $this->load->model('ar/saleInvoice_model');
            $detail = $this->saleInvoice_model->delete_byID("comp_sales_invoice_charges",$this->input->post('rowID'));

            $this->saleInvoice_model->updateMaster("comp_sales_invoice",array("totalTaxAmount","totalAmount"), $this->input->post('invoiceId'), true);
            echo '{"status":"'.$detail.'"}';
        }
        
        public function newSaleDebitNote(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARSDBN');
        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']=51;
            $data['formNo']= $this->formSetup_Model->getFormNo($filter); 
            $this->lang->load("saleDebitNote",$this->session->userdata('language'));
            
            $this->load->model('companyChartAcct');
            $this->load->model('Usermaster');
            $data['records'] = $this->Usermaster->usermaster_all();
            
            $this->load->model('companyChartAcct');
            $data['chargeAccount'] = $this->companyChartAcct->chartAcct_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('customer/Customer_model');
            $data['customer'] = $this->Customer_model->customermaster_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('taxmaster');
            $data['taxmaster'] = $this->taxmaster->taxmaster_saleOutput();
            
             //$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'));
            
            $this->load->model('Usermaster');
            $data['records'] = $this->Usermaster->usermaster_all();

            $this->layouts->view('ar/transaction/newSaleDebitNote', '', $data);
        }
        
        public function getCompanyInvoiceList(){
            $this->load->model('ar/saleInvoice_model');
            echo $this->saleInvoice_model->getCompanyInvoiceListByCust($this->input->post('customerID'));
        }
        
        
        public function saveSaleDebitNoteItem(){
            $this->load->model('ar/saleInvoice_model');
            $ID = $this->input->post('ID');
            $companyID =  element('compID', $this->session->userdata('logged_in')) ;
            $datinsert = array (
                
                  'customerID'  => $this->input->post('customerID'), 
                  'formNo' => $this->input->post('formNo'), 
                  'salesInvoiceID' => $this->input->post('salesInvoiceID'), 
                  'debitNoteDate' => date('Y-m-d', strtotime($this->input->post('debitNoteDate'))),
                  'projectID'  => $this->input->post('projectID'), 
                  'exchangeRate'  => $this->input->post('exchangeRate'),
                  'memo' => $this->input->post('memo'),
                  'companyID' => $companyID,
                  'createdBy' => element('role', $this->session->userdata('logged_in'))
            );

              
             $query = $this->saleInvoice_model->insert("comp_sales_debitnote",$datinsert);
             
            if($query){
                    
                    $datinsertDetails = array (
                    'debitnoteID' =>  $query,
                    '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'),
                    'unitPrice' => $this->input->post('unitPrice'),
                        'umID' => $this->input->post('umid'), 
                    '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->saleInvoice_model->insert('comp_sales_debitnote_detail',$datinsertDetails);
           
             $this->saleInvoice_model->updateMaster("comp_sales_debitnote",array("totalTaxAmount","totalAmount"), $query);
             echo '{"status":"success","debitNoteID":"'.$query.'","detailID":"'.$detail.'"}';
            }else{
                    echo "false";
            }
        }
        
        public function saveSaleDebitNoteCharge(){
            $this->load->model('ar/saleInvoice_model');
            $ID = $this->input->post('ID');
            $companyID =  element('compID', $this->session->userdata('logged_in')) ;
            $datinsert = array (
                
                  'customerID'  => $this->input->post('customerID'), 
                  'formNo' => $this->input->post('formNo'), 
                  'salesInvoiceID' => $this->input->post('salesInvoiceID'), 
                  'debitNoteDate' => date('Y-m-d', strtotime($this->input->post('debitNoteDate'))),
                  'projectID'  => $this->input->post('projectID'), 
                  'exchangeRate'  => $this->input->post('exchangeRate'),
                  'memo' => $this->input->post('memo'),
                  'companyID' => $companyID,
                  'createdBy' => element('role', $this->session->userdata('logged_in'))
            );

              
             $query = $this->saleInvoice_model->insert("comp_sales_debitnote",$datinsert);
             
             if($query){
                   

                    $datinsertDetails = array (
                    'debitNoteID' =>  $query,
                    'lineNo' => $this->input->post('lineNo'),
                    'createdBy' => element('role', $this->session->userdata('logged_in')),
                    'accountNoID' => $this->input->post('accountNoID'),
                    'chargeDescription' => $this->input->post('chargeDescription'),
                    '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->saleInvoice_model->insert('comp_sales_debitnote_charges',$datinsertDetails);
              $this->saleInvoice_model->updateMaster("comp_sales_debitnote",array("totalTaxAmount","totalAmount"), $query);
             
             echo '{"status":"success","debitNoteID":"'.$query.'","detailID":"'.$detail.'"}';
            }else{
                    echo "false";
            }
        }
        
        public function saveSaleDebitNoteChargeDetailOnly(){
             $this->load->model('ar/saleInvoice_model');
             $datinsertDetails = array (
                    'debitNoteID' =>  $this->input->post('masterId'),
                    'lineNo' => $this->input->post('lineNo'),
                    'createdBy' => element('role', $this->session->userdata('logged_in')),
                    'accountNoID' => $this->input->post('accountNoID'),
                    'chargeDescription' => $this->input->post('chargeDescription'),
                    '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->saleInvoice_model->insert('comp_sales_debitnote_charges',$datinsertDetails);
             $this->saleInvoice_model->updateMaster("comp_sales_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('masterId'));
             echo '{"status":"success","detailID":"'.$detail.'"}';
        }

        public function saveSaleDebitNoteItemDetailOnly(){
            $this->load->model('ar/saleInvoice_model');
            
            $datinsertDetails = array (
                    'debitnoteID' =>  $this->input->post('debitNoteID'),
                    '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')
            );
             $detail = $this->saleInvoice_model->insert('comp_sales_debitnote_detail',$datinsertDetails);
             $this->saleInvoice_model->updateMaster("comp_sales_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('debitNoteID'));
             echo '{"status":"success","detailID":"'.$detail.'"}';
            
        }

// debite note
// yahaya abdollah	
	public function salesdebitnotePost(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARDBNC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
		$add_year = $this->uri->segment(3);
		$add_period = $this->uri->segment(4);
		if(!$add_year){
			$add_year = date("Y");
		}
		if(!$add_period){
			$add_period = date("m");
		}
		$this->lang->load("salesDN",$this->session->userdata('language'));
		$this->load->model('salesdebitnote_model');
		$this->load->model('company/FormSetup_model');
		$this->load->model('Compfinancialyear');
		//$data['yrs'] = range(date('Y'), 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;
		$query = $this->Compfinancialyear->financialYear_year($add_year);
		if($query){
			$data['period'] = $query;
		}else{
			$data['period'] = NULL;
		}
		$queryCal = $this->Compfinancialyear->financialYear_yearperiod($add_year, $add_period);
		if($queryCal){
			$data['datatbls'] = $this->salesdebitnote_model->salesdebitnote_unpost($queryCal[0]->startDate, $queryCal[0]->endDate);
		}else{
			$data['datatbls'] = NULL;
		}
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('ar/transaction/salesdebitnotePost', array('latest' => 'sidebar/latest'), $data);
	}
	
	public function debitNotePosting(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARDBNC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
		$this->lang->load("salesDN",$this->session->userdata('language'));
		$ID = $this->input->post('fldid');
		$effdate = date("Y-m-d", strtotime($this->input->post('effdate')));
		$this->load->model('salesdebitnote_model');
		$queryDetails = $this->salesdebitnote_model->salesdebitNoteDetails_ID($ID);
		$data = array(
			'updateAble'=>'0'
		);
		$query = $this->salesdebitnote_model->salesdebitNotepost($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]->serialNo) . ']';
				$total_amount_dr = ($query[0]->totalAmount + $query[0]->totalTaxAmount) * $query[0]->exchangeRate;
				$total_amount_cr = ($query[0]->totalAmount + $query[0]->totalTaxAmount) * $query[0]->exchangeRate;
			}else{
   				print json_encode(array("status"=>"failed", "message"=>$query1));
				return FALSE;
			}
 			$this->load->model('Glseq');
			$query2 = $this->Glseq->glSequence_sub('2', 'AR', $year, $period);
			$newData = array(
				'companyID' => element('compID', $this->session->userdata('logged_in')),
				'journalID' => $query2['seqNumber'],
				'formNo' => $formNo,
				'description' => $this->lang->line('message2') . ' [ ' . $formNo . ' ]',
				'module' => '2',
				'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->salesdebitnote_model->salesdebitnote_Update($ID, $data);
			$this->load->model('Journal');
			$query3 = $this->Journal->journal_insert($newData);

			if($query3){
				//$query4 = $this->salesdebitnote_model->salesdebitNoteDetails_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;
		}
	}
// credit Note        
        public function newSaleCreditNote(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARSCN');
        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']=52;
            $data['formNo']= $this->formSetup_Model->getFormNo($filter); 
            $this->lang->load("saleCreditNote",$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('customer/Customer_model');
            $data['customer'] = $this->Customer_model->customermaster_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('taxmaster');
            $data['taxmaster'] = $this->taxmaster->taxmaster_saleOutput();

           // $this->load->model('item/itemSetup_model');
           //  $data['items'] = $this->itemSetup_model->get_all(true);
             
             $this->load->model('companyChartAcct');
            $data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();
             
            $this->load->model('company/formSetup_Model');
            $filter['companyID']=element('compID', $this->session->userdata('logged_in'));
           
            $this->load->model('Usermaster');
            $data['records'] = $this->Usermaster->usermaster_all();

            $this->layouts->view('ar/transaction/newSaleCreditNote', '', $data);
        }
        
         public function saveSaleCreditNoteItem(){
            $this->load->model('ar/saleInvoice_model');
            $ID = $this->input->post('ID');
            $companyID =  element('compID', $this->session->userdata('logged_in')) ;
            $datinsert = array (
                
                  'customerID'  => $this->input->post('customerID'), 
                  'formNo' => $this->input->post('formNo'), 
                  'salesInvoiceID' => $this->input->post('salesInvoiceID'), 
                  'creditNoteDate' => date('Y-m-d', strtotime($this->input->post('creditNoteDate'))),
                  'projectID'  => $this->input->post('projectID'), 
                  'exchangeRate'  => $this->input->post('exchangeRate'),
                  'memo' => $this->input->post('memo'),
                  'companyID' => $companyID,
                  'createdBy' => element('role', $this->session->userdata('logged_in'))
            );

              
             $query = $this->saleInvoice_model->insert("comp_sales_creditnote",$datinsert);
             
            if($query){
                   

                    $datinsertDetails = array (
                    'creditnoteID' =>  $query,
                    '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')
            );
             $detail = $this->saleInvoice_model->insert('comp_sales_creditnote_detail',$datinsertDetails);
             $this->saleInvoice_model->updateMaster("comp_sales_creditnote",array("totalTaxAmount","totalAmount"), $query);
             echo '{"status":"success","creditNoteID":"'.$query.'","detailID":"'.$detail.'"}';
            }else{
                    echo "false";
            }
        }
        
        
        public function saveSaleCreditNoteItemDetailOnly(){
            $this->load->model('ar/saleInvoice_model');
            
            $datinsertDetails = array (
                    'creditnoteID' =>  $this->input->post('creditNoteID'),
                    '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')
            );
             $detail = $this->saleInvoice_model->insert('comp_sales_creditnote_detail',$datinsertDetails);
             $this->saleInvoice_model->updateMaster("comp_sales_creditnote",array("totalTaxAmount","totalAmount"), $this->input->post('creditNoteID'));
             echo '{"status":"success","detailID":"'.$detail.'"}';
            
        }
        
	public function salescreditnotePost(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARSCNC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
		$add_year = $this->uri->segment(3);
		$add_period = $this->uri->segment(4);
		if(!$add_year){
			$add_year = date("Y");
		}
		if(!$add_period){
			$add_period = date("m");
		}
		$this->lang->load("salesCN",$this->session->userdata('language'));
		$this->load->model('salescreditnote_model');
		$this->load->model('company/FormSetup_model');
		$this->load->model('Compfinancialyear');
		//$data['yrs'] = range(date('Y'), 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;
		$query = $this->Compfinancialyear->financialYear_year($add_year);
		if($query){
			$data['period'] = $query;
		}else{
			$data['period'] = NULL;
		}
		$queryCal = $this->Compfinancialyear->financialYear_yearperiod($add_year, $add_period);
		if($queryCal){
			$data['datatbls'] = $this->salescreditnote_model->salescreditnote_unpost($queryCal[0]->startDate, $queryCal[0]->endDate);
		}else{
			$data['datatbls'] = NULL;
		}
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('ar/transaction/salescreditnotePost', array('latest' => 'sidebar/latest'), $data);
	}

	public function creditNotePosting(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARSCNC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
		$this->lang->load("salesCN",$this->session->userdata('language'));
		$ID = $this->input->post('fldid');
		$effdate = date("Y-m-d", strtotime($this->input->post('effdate')));
		$this->load->model('salescreditnote_model');
		$queryDetails = $this->salescreditnote_model->salescreditnoteDetails_ID($ID);
		$data = array(
			'updateAble'=>'0'
		);
		$query = $this->salescreditnote_model->salescreditnote_post($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) . ']';
				$total_amount_dr = ($query[0]->totalAmount + $query[0]->totalTaxAmount) * $query[0]->exchangeRate;
				$total_amount_cr = ($query[0]->totalAmount + $query[0]->totalTaxAmount) * $query[0]->exchangeRate;
			}else{
   				print json_encode(array("status"=>"failed", "message"=>$query1));
				return FALSE;
			}
 			$this->load->model('Glseq');
			$query2 = $this->Glseq->glSequence_sub('2', 'AR', $year, $period);
			$newData = array(
				'companyID' => element('compID', $this->session->userdata('logged_in')),
				'journalID' => $query2['seqNumber'],
				'formNo' => $formNo,
				'description' => $this->lang->line('message2') . ' [ ' . $formNo . ' ]',
				'module' => '2',
				'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->salescreditnote_model->salescreditnote_Update($ID, $data);
			$this->load->model('Journal');
			$query3 = $this->Journal->journal_insert($newData);
			if($query3){
				$query4 = $this->salescreditnote_model->salescreditnoteDetails_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;
		}
	}

        public function editSaleDebitNote($id){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('AREDSLDR');
        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("saleDebitNote",$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');

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

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

            $this->load->model('ar/saleInvoice_model');
            
            $this->load->model('Project/project_model');
			$data['project'] = $this->project_model->project_all();
            
             
            $data['pdetails']= $this->saleInvoice_model->getDataByTname("comp_sales_debitnote_detail",$id);
            
            $data['charges']=$this->saleInvoice_model->getDataByTname("comp_sales_debitnote_charges",$id);
             
            $data['pInvoice']=$this->saleInvoice_model->getDataByTname("comp_sales_debitnote",$id);
           
            if ($data['pInvoice']){
                 $data['items'] = $this->saleInvoice_model->getDataByTname("invoiceItemListForDebitNote",$data['pInvoice'][0]->salesInvoiceID); 
            }

            $this->layouts->view('ar/transaction/editSaleDebitNote', '', $data);
        }
        
        public function updateRowDetailDebitNote(){
            
            $datinsertDetails = 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'),
                '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')
            );
             $this->load->model('ar/saleInvoice_model');
             $detail = $this->saleInvoice_model->update_byID('comp_sales_debitnote_detail',$this->input->post('rowID'),$datinsertDetails);
             $this->saleInvoice_model->updateMaster("comp_sales_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('masterId'));
             echo '{"status":"success","detailID":"'.$detail.'"}';
        }
        
        public function deleteDebitNoteDetail(){
            $this->load->model('ar/saleInvoice_model');
            $res = $this->saleInvoice_model->delete_byID ("comp_sales_debitnote_detail",$this->input->post('rowID'));
             $this->saleInvoice_model->updateMaster("comp_sales_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('masterId'));
            echo '{"status":"'.$res.'"}';
        }
        
          public function deleteCreditNoteDetail(){
            $this->load->model('ar/saleInvoice_model');
            $res = $this->saleInvoice_model->delete_byID ("comp_sales_creditnote_detail",$this->input->post('rowID'));
             $this->saleInvoice_model->updateMaster("comp_sales_creditnote",array("totalTaxAmount","totalAmount"), $this->input->post('masterId'));
            echo '{"status":"'.$res.'"}';
         //   echo $this->input->post('masterId')
        }
        
         public function editSaleCreditNote($id){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('AREDCR');
        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->load->model('company/formSetup_Model');
            $filter['companyID']=element('compID', $this->session->userdata('logged_in'));

            $this->lang->load("saleCreditNote",$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'] =false;
             
             $this->load->model('companyChartAcct');
            $data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();

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

            $this->load->model('ar/saleInvoice_model');
            
            $data['pdetails']= $this->saleInvoice_model->getDataByTname("comp_sales_creditnote_detail",$id);
            
            $data['charges']=$this->saleInvoice_model->getDataByTname("comp_sales_creditnote_charges",$id);

            $data['pInvoice']=$this->saleInvoice_model->getDataByTname("comp_sales_creditnote",$id);
             if ($data['pInvoice']){
                 $data['items'] = $this->saleInvoice_model->getDataByTname("invoiceItemListForCreditNote",$data['pInvoice'][0]->salesInvoiceID); 
            }

            $this->layouts->view('ar/transaction/editSaleCreditNote', '', $data);
            
        }
        
        
        public function updateRowDetailCreditNote(){
             $this->load->model('ar/saleInvoice_model');
            
            $datinsertDetails = 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'),
                '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')
            );
             $detail = $this->saleInvoice_model->update_byID('comp_sales_creditnote_detail',$this->input->post('rowID'),$datinsertDetails);
              $this->saleInvoice_model->updateMaster("comp_sales_creditnote",array("totalTaxAmount","totalAmount"), $this->input->post('masterID'));
             echo '{"status":"success","detailID":"'.$detail.'"}';
        }
        
        public function newReceivePayment(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARRCVP');
        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']=53;
            $data['formNo']= $this->formSetup_Model->getFormNo($filter); 
            $this->lang->load("newreceivepayment",$this->session->userdata('language'));
            $this->load->model('companyChartAcct');

            $this->load->model('Usermaster');
            $data['records'] = $this->Usermaster->usermaster_all();
            
            
            $this->load->model('bank/bank_model');
            $data['bankaccount'] = $this->bank_model->bank_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('customer/Customer_model');
            $data['customer'] = $this->Customer_model->customermaster_all();

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

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

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

            $this->layouts->view('ar/receivePayment/newreceivepayment', '', $data);
	}
        
        public function editReceivePayment ($id){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARPAYEDT');
        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("newreceivepayment",$this->session->userdata('language'));
            $this->load->model('companyChartAcct');

            $this->load->model('Usermaster');
            $data['records'] = $this->Usermaster->usermaster_all();
            
            $this->load->model('Project/project_model');
            $data['project'] = $this->project_model->project_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('ar/receivepayment_model');
            $data['master']=$this->receivepayment_model->getDataByFvalue("getReceivePaymentMaster",$id);
            $data['details']=$this->receivepayment_model->getDataByFvalue("getReceivePaymentDetails",$id);
           
            $this->layouts->view('ar/receivePayment/editreceivepayment', '', $data);
	}
        
        public function loadPayerDetailsValue(){
            $this->load->model('customer/Customer_model');
            $this->load->model('ar/receivepayment_model');
            $default = $this->Customer_model->loadCustomerDefaultValue($this->input->post('payer'),true);
            

            $currency ="";
            $rate = "";
            $cId= "";
            
            $JsonRecords = '{';
            if ($default){
                foreach($default['info'] as $row){
                    $currency = $row->currencyWord;
                    $rate = $row->exchangeRate;
                    $cId = $row->currencyID;
                }
            }
            $JsonRecords .= '"currency":"' .$currency.'",'.'"exchangeRate":"'.$rate.'","currencyID":"'.$cId.'"';
            $ob = "0";
            $OBalance =$this->receivepayment_model->getDataByFvalue("getLastOutOfBalance",$this->input->post('payer'));
            $JsonRecords = $JsonRecords. ',"outOfBalance":"';
            if ($OBalance){
                foreach ($OBalance as $row) {
                    $ob = $row->totalOtherCharge;
                }
            }
            $JsonRecords = $JsonRecords.$ob. '"';
            $tojson = json_encode($this->receivepayment_model->getDataByFvalue("getPayerPendingInvoices",$this->input->post('payer')));
            $JsonRecords .= ',"recordSet":'.$tojson.'}';  
        
            echo $JsonRecords;
        }
        
        
        public function saveNewReceivePayment(){
            
            $dataInsert= array(
                            "currencyID" => $this->input->post('currencyID'),
                            'companyID' => element('compID', $this->session->userdata('logged_in')),
                            "createdBy" => element('role', $this->session->userdata('logged_in')),
                            "exchangeRate" => $this->input->post('exchangeRate'),
                            "customerID" => $this->input->post('customerID'),
                            "projectID" => $this->input->post('projectID'),
                            "memo" => $this->input->post('memo'),
                            "formNo" => $this->input->post('formNo'),
                            "receivePaymentDate" => date('Y-m-d', strtotime($this->input->post('receivePaymentDate'))),               "currencyID" => $this->input->post('currencyID'),
                            "bankId" => $this->input->post('bankID'),
                            "outOfBalance" => $this->input->post('outOfBalance'),
                            "totalApplied" => $this->input->post('totalApplied'),
                            "paymentMethodID" => $this->input->post('paymentMethodID'),
                            "referenceNo" => $this->input->post('referenceNo'),
                            "bankCharges" => $this->input->post('bankCharges'),
                            "totalDiscount" => $this->input->post('totalDiscount'),
                            "totalOtherCharge" => $this->input->post('totalOtherCharge'),
                            "totalReceived" => $this->input->post('amountReceived')
            );
            
            $this->load->model('ar/receivepayment_model');
            $idInvoice = $this->receivepayment_model->insert("comp_receive_payment",$dataInsert);
            $pdetail = $this->jsonToArray( $this->input->post('pdetail') );
            $n = sizeof ( $pdetail ['rs'] );
           $successN =0;
         //   $pSuccessId=array();
            if ($idInvoice>0){
                
                for($i=0;$i<$n;$i++){
                    $dataInsert = array(
                                    "lineNo" => $i + 1,
                                    "receivePaymentID" => $idInvoice,
                                    "invoiceID" =>  $pdetail ['rs'] [$i]->invoiceID, 
                                    "discount" => $pdetail ['rs'] [$i]->discount, 
                                    "amountApplied" => $pdetail ['rs'] [$i]->amountApplied, 
                                    );
                    $idD = $this->receivepayment_model->insert("comp_receive_payment_detail",$dataInsert);
                    if ($idD>0){
                       // $pSuccessId = $row->invoiceID.'"';
                        $successN++;
                        $newArBalance = array ("totalReceivable"=>$pdetail ['rs'] [$i]->arBalance - $pdetail ['rs'] [$i]->amountApplied);
                        $this->receivepayment_model->update_byID ("comp_sales_invoice",$pdetail ['rs'] [$i]->invoiceID,$newArBalance );
                    }
                }
            }
            echo $successN;
        }
        
	public function compRecPaymentPost() {
		//$ID = isset($_REQUEST['ID'])?$_REQUEST['ID']:"";
		$mode = $this->uri->segment(3);
		$this->lang->load("compRecPaymentList1",$this->session->userdata('language'));
		$this->load->model('company/FormSetup_model');
		$this->load->model('company/company_info_model');
		
		
//		$dateFrom = $this->input->post('selDateFrom');
//		$dateTo = $this->input->post('selDateTo');

		$data['mode'] = $mode; 
		
		$dateFrom = date("Y-m-d",strtotime($this->uri->segment(4)));
		$dateTo = date("Y-m-d",strtotime($this->uri->segment(5)));
		
		if ($this->uri->segment(4) == ""){
			$dateFrom = date("Y-m-01");
		}
		if($this->uri->segment(5) == ""){
			$dateTo = date("Y-m-t");
		}
		if($dateFrom > $dateTo){
			$dateTo = date("Y-m-t", strtotime($dateFrom));
		}
		
		$data['dateFrom'] = $dateFrom;
		$data['dateTo'] = $dateTo;
		$data['datatbls'] = $this->company_info_model->compRecPaymentDate($dateFrom, $dateTo);
		
//		echo $this->db->last_query();
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('company/compRecPaymentList', array('latest' => 'sidebar/latest'), $data);
	}
        
	public function receivedPaymentPost(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARRCVPC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
		$add_year = $this->uri->segment(3);
		$add_period = $this->uri->segment(4);
		if(!$add_year){
			$add_year = date("Y");
		}
		if(!$add_period){
			$add_period = date("m");
		}
		$this->lang->load("salesPayment",$this->session->userdata('language'));
		$this->load->model('SalesPayment');
		$this->load->model('company/FormSetup_model');
		$this->load->model('Compfinancialyear');
		//$data['yrs'] = range(2025, 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;
		$query = $this->Compfinancialyear->financialYear_year($add_year);
              
		if($query){
			$data['period'] = $query;
		}else{
			$data['period'] = NULL;
		}
		$queryCal = $this->Compfinancialyear->financialYear_yearperiod($add_year, $add_period);
               
		if($queryCal){
			$data['datatbls'] = $this->SalesPayment->SalesPayment_unpost($queryCal[0]->startDate, $queryCal[0]->endDate);
		 
                }else{
			$data['datatbls'] = NULL;
		}
                
                
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js');
		$this->layouts->view('ar/transaction/receivedPaymentPost', array('latest' => 'sidebar/latest'), $data);
	}
	
	public function paymentPosting(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARRCVPC');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
		$this->lang->load("salesPayment",$this->session->userdata('language'));
		$ID = $this->input->post('fldid');
		$effdate = date("Y-m-d", strtotime($this->input->post('effdate')));
		$this->load->model('SalesPayment');
		$queryDetails = $this->SalesPayment->SalesPaymentDetails_ID($ID);
		$data = array(
			'updateAble'=>'0'
		);
		$query = $this->SalesPayment->SalesPaymentDetailsPost($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]->serialNo) . ']';
				$total_amount_dr = $query[0]->totalReceived * $query[0]->exchangeRate;
				$total_amount_cr = $query[0]->totalReceived * $query[0]->exchangeRate;
			}else{
 				$data = array(
					'updateAble'=>'1'
				);
				$query = $this->SalesPayment->SalesPaymentDetailsPost($ID, $data);
  				print json_encode(array("status"=>"failed", "message"=>$query1));
				return FALSE;
			}
 			$this->load->model('Glseq');
			$query2 = $this->Glseq->glSequence_sub('2', 'AR', $year, $period);
			$newData = array(
				'companyID' => element('compID', $this->session->userdata('logged_in')),
				'journalID' => $query2['seqNumber'],
				'formNo' => $formNo,
				'description' => $this->lang->line('message2') . ' [ ' . $formNo . ' ]',
				'module' => '2',
				'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->SalesPayment->SalesPayment_Update($ID, $data);
			$this->load->model('Journal');
			$query3 = $this->Journal->journal_insert($newData);
			if($query3){
				$query4 = $this->SalesPayment->SalesPaymentDetails_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;
		}
	}
        
        public function deletePaymentDetailRow(){
            $this->load->model('ar/receivepayment_model');
            echo $this->receivepayment_model->delete_byID("comp_receive_payment_detail",$this->input->post('id'));
        }
        
        
        public function updatePaymentRow(){
            $upd="";
            
            $this->load->model('ar/receivepayment_model');
            
            $arrayUpPaymentDetails = array(
                'discount' => $this->input->post('discount'),
                'amountApplied' => $this->input->post('amountApplied')
            );
            $upd = $this->receivepayment_model->update_byID ("comp_receive_payment_detail",$this->input->post('detaildId'),$arrayUpPaymentDetails );
            
            $arrayUpPaymentMaster = array(
                'memo' => $this->input->post('memo'),
                'totalDiscount' => $this->input->post('totalDiscount'),
                'totalReceived' => $this->input->post('totalReceived'),
                'totalApplied' => $this->input->post('totalApplied'),
                'outOfBalance' => $this->input->post('outOfBalance'),
                'bankCharges' => $this->input->post('bankCharges'),
                'totalOtherCharge' => $this->input->post('totalOtherCharge')
            );
            $upd = $upd.$this->receivepayment_model->update_byID ("comp_receive_payment",$this->input->post('masterId'),$arrayUpPaymentMaster );
            
            $arrayUpSaleInvoice = array(
                'totalReceivable' => $this->input->post('totalReceivable')
            );
            $upd = $upd.$this->receivepayment_model->update_byID ("comp_sales_invoice",$this->input->post('invoiceId'),$arrayUpSaleInvoice );
            
            echo $upd;
            
        }
        
        public function addpaymentdetailsOnly(){
            $this->load->model('ar/receivepayment_model');
            $masterId =  $this->input->post('masterId');
            $pdetail = $this->jsonToArray( $this->input->post('pdetail') );
            $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,
                                    "receivePaymentID" => $masterId,
                                    "invoiceID" =>  $pdetail ['rs'] [$i]->invoiceID, 
                                    "discount" => $pdetail ['rs'] [$i]->discount, 
                                    "amountApplied" => $pdetail ['rs'] [$i]->amountApplied, 
                                    );
                    $idD = $this->receivepayment_model->insert("comp_receive_payment_detail",$dataInsert);
                    if ($idD>0){
                       // $pSuccessId = $row->invoiceID.'"';
                        $successN++;
                        $newArBalance = array ("totalReceivable"=>$pdetail ['rs'] [$i]->arBalance - $pdetail ['rs'] [$i]->amountApplied);
                        $this->receivepayment_model->update_byID ("comp_sales_invoice",$pdetail ['rs'] [$i]->invoiceID,$newArBalance );
                    }
                }
            }
            echo $successN;
        }
        
        public function saveSaleCreditNoteCharge(){
              $this->load->model('ar/saleInvoice_model');
            $ID = $this->input->post('ID');
            $companyID =  element('compID', $this->session->userdata('logged_in')) ;
            $datinsert = array (
                
                  'customerID'  => $this->input->post('customerID'), 
                  'formNo' => $this->input->post('formNo'), 
                  'salesInvoiceID' => $this->input->post('salesInvoiceID'), 
                  'creditNoteDate' => date('Y-m-d', strtotime($this->input->post('creditNoteDate'))),
                  'projectID'  => $this->input->post('projectID'), 
                  'exchangeRate'  => $this->input->post('exchangeRate'),
                 'currencyID' => $this->input->post('currencyID'),
                  'memo' => $this->input->post('memo'),
                  'companyID' => $companyID,
                  'createdBy' => element('role', $this->session->userdata('logged_in'))
            );

              
             $query = $this->saleInvoice_model->insert("comp_sales_creditnote",$datinsert);
             
            if($query){
                   

                    $datinsertDetails = array (
                    'creditNoteID' =>  $query,
                    'lineNo' => $this->input->post('lineNo'),
                    'createdBy' => element('role', $this->session->userdata('logged_in')),
                    'accountNoID' => $this->input->post('accountNoID'),
                    'chargeDescription' => $this->input->post('chargeDescription'),
                    '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->saleInvoice_model->insert('comp_sales_creditnote_charges',$datinsertDetails);
             $this->saleInvoice_model->updateMaster("comp_sales_creditnote",array("totalTaxAmount","totalAmount"), $query);
             echo '{"status":"success","creditNoteID":"'.$query.'","detailID":"'.$detail.'"}';
            }else{
                    echo "false";
            }
        }
        
        public function saveSaleCreditNoteChargeDetailOnly(){
             $this->load->model('ar/saleInvoice_model');
             $datinsertDetails = array (
                    'creditNoteID' =>  $this->input->post('masterID'),
                    'lineNo' => $this->input->post('lineNo'),
                    'createdBy' => element('role', $this->session->userdata('logged_in')),
                    'accountNoID' => $this->input->post('accountNoID'),
                    'chargeDescription' => $this->input->post('chargeDescription'),
                    '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->saleInvoice_model->insert('comp_sales_creditnote_charges',$datinsertDetails);
              $this->saleInvoice_model->updateMaster("comp_sales_creditnote",array("totalTaxAmount","totalAmount"), $this->input->post('masterID'));
             //$tota = $this->input->post('amountIncludedTax') + $this->input->post('currentTotalInvoice');
             //$tax = $this->input->post('taxAmount') + $this->input->post('currentTaxAmount');
             //$totaUpdate = array (
               //  "totalTaxAmount" =>$tax,
                 //"totalReceivable" => $tota, 
                 //"totalamount" => $tota);
             //$this->saleInvoice_model->update_byID("comp_sales_invoice", $this->input->post('invoiceId'),$totaUpdate );
             

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

	/******************************************
    *
    *  - Sayem
    *  start
    *
    */
	//Sales invoice
	public function salesInvoice(){
        $this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('ARSALINV');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
		//Gather sales invoice list
		$this->load->model('ar/saleInvoice_model');
		$data['salesInvoice'] = $this->saleInvoice_model->getSalesInvoice();
		
		/****************************/
		$this->load->model('company/formSetup_Model');
		$filter['companyID']=element('compID', $this->session->userdata('logged_in'));
		
		$this->lang->load("saleInvoiceNew",$this->session->userdata('language'));
		$this->load->model('companyChartAcct');
		
		$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('address_model');
		$data['shipto'] = '';//$this->address_model->getCompanyAdresses();
			
		$this->load->model('employee/employee_model');
		$data['saler'] = $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('customer/Customer_model');
		$data['customer'] = $this->Customer_model->customermaster_all();
			
		$this->load->model('SaleAgent/Agent_model');
		$data['agent'] = $this->Agent_model->agent_all();
			
		$this->load->model('companyChartAcct');
		$data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();
		
		$this->load->model('Sysum');
		$data['umlist'] = $this->Sysum->sysum_all();	
			
		$this->load->model('taxmaster');
		$data['taxmaster'] = $this->taxmaster->taxmaster_saleOutput();
			
		$data['itemCodes'] = $this->getItemCodes();
			
		//			$this->load->model('company/formSetup_Model');
		$filter['companyID']=element('compID', $this->session->userdata('logged_in'));
		$filter['formID']=50;
		$data['formNo']= $this->formSetup_Model->getFormNo($filter);
		
		$this->load->model('Usermaster');
		$data['records'] = $this->Usermaster->usermaster_all();
		/****************************/
		
		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js')
					->add_includes('js/validationengine/languages/jquery.validationEngine-'.$this->session->userdata('language').'.js')
					->add_includes('js/accounting.js')
					->add_includes('js/validationengine/jquery.validationEngine.js');
		$this->layouts->view('ar/transaction/saleInvoice', '', $data);
	} 
	
	//Get order items according to customer and date.
	public function getOrderItemsCust(){
		$this->load->model('ar/saleInvoice_model');
		$invoices = $this->saleInvoice_model->getAllOrderByID($this->input->post('customerID'),date('Y-m-d',strtotime($this->input->post('date'))));
		echo json_encode($invoices);
		exit();
	}
	//Get Customer information regarding currency, and terms
	public function getCurrencyInfo(){
		$this->load->model('ar/saleInvoice_model');
		$invoices = $this->saleInvoice_model->getCustomerInfo($this->input->post('customerID'),date('Y-m-d',strtotime($this->input->post('date'))));
		echo json_encode($invoices);
		exit();	
	}
	
	//Gathering detail information about the order
	public function getOrderDetail(){
		$this->load->model('ar/saleInvoice_model');
		$invoices = $this->saleInvoice_model->getAllOrderByID($this->input->post('customerID'),date('Y-m-d',strtotime($this->input->post('date'))));
		echo json_encode($invoices);
		exit();
	}
	//Gathering detail information about the invoice.
	public function getInvoiceDetail(){
		$this->load->model('ar/saleInvoice_model');
		$invoices = $this->saleInvoice_model->getInvoiceByID($this->input->post('invID'));
		echo json_encode($invoices);
		exit();
	}
	
	//Saving item outputTax information
	public function savetax(){
		$this->load->model('ar/saleInvoice_model');
		echo $this->saleInvoice_model->saveTax($this->input->post('taxInfo'));
		exit();		
	}
	
	//Save sales order as invoice
	public function saveSaleInvoice(){
		$this->load->model('ar/saleInvoice_model');
		
		$companyID =  element('compID', $this->session->userdata('logged_in')) ;
		$datainsert = array (
		
				'customerID' => $this->input->post('customerID'),
				'invoiceCodeID' => $this->input->post('invoiceCodeID'),
				'formNo' => $this->input->post('formNo'),
				'salesInvoiceDate' => date('Y-m-d', strtotime($this->input->post('invoiceDate'))),
				'customerPoNo' => $this->input->post('customerPoNo'),
				'projectID' => $this->input->post('projectID'),
				'agentID' => $this->input->post('agentID'),
				'termsID' => $this->input->post('termsID'),
				'shipToID' => $this->input->post('shipToID'),
				'customerID' => $this->input->post('customerID'),
				'exchangeRate' => $this->input->post('exchangeRate'),
				'locationID' => $this->input->post('locationID'),
				'memo' => $this->input->post('memo'),
				'locationID' => $this->input->post('locationID'),
				'employeeID' => $this->input->post('employeeID'),
				'shippingMethodID' => $this->input->post('shippingMethodID'),
				'companyID' => $companyID,
				'createdBy' => element('role', $this->session->userdata('logged_in')),
                                 'currencyID' => $this->input->post('currencyID'),
				'totalTaxAmount' => $this->input->post('totalTaxAmount'),
				'totalReceivable' => $this->input->post('amountIncludedTax'),
				'totalamount' => $this->input->post('amountIncludedTax'),
				"showSaleAgent" => $this->input->post('showinInvoice')
		);
		
		
		$invID = $this->saleInvoice_model->insert("comp_sales_invoice",$datainsert);
		$this->saleInvoice_model->updateSaleInvDet($invID,$this->input->post('salesDetail'));
		//$this->saleInvoice_model->updateSalOrd($this->input->post('salesOrderID'),$invID);
		if($invID){
			echo '{"status":"success","invoiceID":"'.$invID.'"}';
		}else{
			echo false;
		}
	}
	
	//Update Sales invoice
	public function updateSaleInvoice(){
		$this->load->model('ar/saleInvoice_model');
		
		$companyID =  element('compID', $this->session->userdata('logged_in')) ;
		$datainsert = array (
				'customerID' => $this->input->post('customerID'),
				'invoiceCodeID' => $this->input->post('invoiceCodeID'),
				'formNo' => $this->input->post('formNo'),
				'salesInvoiceDate' => date('Y-m-d', strtotime($this->input->post('invoiceDate'))),
				'customerPoNo' => $this->input->post('customerPoNo'),
				'projectID' => $this->input->post('projectID'),
				'agentID' => $this->input->post('agentID'),
				'termsID' => $this->input->post('termsID'),
				'shipToID' => $this->input->post('shipToID'),
				'customerID' => $this->input->post('customerID'),
				'exchangeRate' => $this->input->post('exchangeRate'),
				'locationID' => $this->input->post('locationID'),
				'memo' => $this->input->post('memo'),
				'locationID' => $this->input->post('locationID'),
				'employeeID' => $this->input->post('employeeID'),
				'shippingMethodID' => $this->input->post('shippingMethodID'),
				'companyID' => $companyID,
				'createdBy' => element('role', $this->session->userdata('logged_in')),
		
				'totalTaxAmount' => $this->input->post('totalTaxAmount'),
				'totalReceivable' => $this->input->post('amountIncludedTax'),
				'totalamount' => $this->input->post('amountIncludedTax'),
				"showSaleAgent" => $this->input->post('showinInvoice')
		);
		
		$this->saleInvoice_model->update("comp_sales_invoice",array('ID'=>$this->input->post('invoiceID')),$datainsert);
		//$this->saleInvoice_model->update($invID,$this->input->post('salesDetail'));
		$invID = $this->input->post('invoiceID');
		$arr = json_decode($this->input->post('salesDetail'));
		foreach($arr as $v){
			if(!$this->saleInvoice_model->itemExist('comp_sales_invoice_detail',array('invoiceID'=>$invID,'itemID'=>$v->itemID))){
				$data = array(
						"invoiceID"=>$invID,
						"doID"=>$v->doID,
						"lineNo"=>$v->lineNo,
						"itemID"=>$v->itemID,
						"quantity"=>$v->quantity,
						"unitPrice"=>$v->unitPrice,
						"amountExcludedTax"=>$v->amountExcludedTax,
						"taxID"=>$v->taxID,
						"taxAmount"=>$v->taxAmount,
						"amountIncludedTax"=>$v->amountIncludedTax,
						"createdBy"=>element('role', $this->session->userdata('logged_in'))
				);
				$this->saleInvoice_model->insert('comp_sales_invoice_detail', $data);
			
				//Update Delivery order
				$this->saleInvoice_model->update_byID("comp_delivery_detail",$v->doID,array('invoiceID'=>$invID));
                              //  $this->saleInvoice_model->update("comp_delivery_detail",array('deliveryID'=>$v->doID,'itemID'=>$v->itemID),array('invoiceID'=>$invID));
			}else{
				
			}
		}
		echo '{"status":"success","invoiceID":"'.$invID.'"}';
	}
	
	//Save Sales order while saving charges
	public function saveSaleInvoiceCharges(){
		$this->load->model('ar/saleInvoice_model');
	
		$companyID =  element('compID', $this->session->userdata('logged_in')) ;
		$datainsert = array (
				'customerID' => $this->input->post('customerID'),
				'invoiceCodeID' => $this->input->post('invoiceCodeID'),
				'formNo' => $this->input->post('formNo'),
				'salesInvoiceDate' => date('Y-m-d', strtotime($this->input->post('invoiceDate'))),
				'customerPoNo' => $this->input->post('customerPoNo'),
				'projectID' => $this->input->post('projectID'),
				'agentID' => $this->input->post('agentID'),
				'termsID' => $this->input->post('termsID'),
				'shipToID' => $this->input->post('shipToID'),
				'customerID' => $this->input->post('customerID'),
				'exchangeRate' => $this->input->post('exchangeRate'),
				'locationID' => $this->input->post('locationID'),
				'memo' => $this->input->post('memo'),
				'locationID' => $this->input->post('locationID'),
				'employeeID' => $this->input->post('employeeID'),
				'shippingMethodID' => $this->input->post('shippingMethodID'),
				'companyID' => $companyID,
				'createdBy' => element('role', $this->session->userdata('logged_in')),
                                'currencyID' => $this->input->post('currencyID'),
				'totalTaxAmount' => $this->input->post('totalTaxAmount'),
				'totalReceivable' => $this->input->post('totalPayable'),
				'totalamount' => $this->input->post('totalamount'),
				"showSaleAgent" => $this->input->post('showinInvoice')
		);
	
	
		$invID = $this->saleInvoice_model->insert("comp_sales_invoice",$datainsert);
		$this->saleInvoice_model->updateSaleInvDet($invID,$this->input->post('salesDetail'));
		//$this->saleInvoice_model->updateSalOrd($this->input->post('salesOrderID'),$invID);
	
		if($invID){
	
			$datinsertDetails = array (
					'invoiceID' =>  $invID,
					'lineNo' => $this->input->post('lineNo'),
					'createdBy' => element('role', $this->session->userdata('logged_in')),
					'accountNoID' => $this->input->post('accountNoID'),
					'chargeDescription' => $this->input->post('chargeDescription'),
					'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'),
			);
			$detail = $this->saleInvoice_model->insert('comp_sales_invoice_charges',$datinsertDetails);
	
			echo '{"status":"success","invoiceID":"'.$invID.'","detailID":"'.$detail.'"}';
		}else{
			echo "false";
		}
	}
	
	//Delete Charge
	public function deleteChargeOnly(){
		$this->saleInvoice_model->delete_byID("comp_sales_invoice_charges",$this->input->post('chargeID'));
	}
	
	public function updateInvoice(){
		$this->$this->saleInvoice_model->update("comp_sales_invoice",array('ID'=>$this->input->post('invoiceID'))
																	,array(
																			'totalamount'=>$this->input->post('totalPayable'),
																			'totalReceivable'=>$this->input->post('totalPayable'),
																			'totalTaxAmount'=>$this->input->post('totalTaxAmount'),
																	));
	}
	
	//Refresh customer shipment address
	public function refreshShip(){
		//Gather sales invoice list
		$this->load->model('ar/saleInvoice_model');
		$this->saleInvoice_model->getShipAddress($this->input->post('custID'));		
	}

	public function loadCustomerDefaultValue(){
		$this->load->model('customer/Customer_model');
		$data = $this->Customer_model->loadCustomerDefaultValue($this->input->post('customer'),true);
		$sendData['records'] = $data['info'];	
		$sendData['shipto'] = $data['shipto'];
		echo json_encode($sendData);

	}

	/******************************************
	 *
	*  - Sayem
	*  end
	*
	*/ 
        
         public function getSaleInvoiceItemListCredit(){
       $this->load->model('ar/saleInvoice_model');
         echo '{"status":"success","recordSet":' . json_encode($this->saleInvoice_model->getDataByTname("invoiceItemListForCreditNote",$this->input->post('invoiceId'))) . '}';
    }
    
    public function getSaleInvoiceItemListDebit(){
       $this->load->model('ar/saleInvoice_model');
         echo '{"status":"success","recordSet":' . json_encode($this->saleInvoice_model->getDataByTname("invoiceItemListForDebitNote",$this->input->post('invoiceId'))) . '}';
    }

    public function update_saleInvoice_header(){
    	$this->load->model('ar/saleInvoice_model');
    	$data = array(
    		'customerPoNo' => $this->input->post('custumerpono') ,
    		'termsID' => $this->input->post('termsID') ,
    		'projectID' => $this->input->post('project') ,
    		'salesInvoiceDate' =>date('Y-m-d', strtotime($this->input->post('dateInvoice'))),
    		 'memo' => $this->input->post('memo'),
    		  'customerID' => $this->input->post('customer'),
    		  'shipToID' => $this->input->post('shipToID')
    	 );
    	$res = $this->saleInvoice_model->update_byID("comp_sales_invoice", $this->input->post('invoiceId') ,$data);
    	echo '{"status":"success","res":"'.$res.'"}';
    }

    public function update_saleDebitNote_header(){
    	$this->load->model('ar/saleInvoice_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->saleInvoice_model->update_byID("comp_sales_debitnote", $this->input->post('debitNoteID') ,$data);
    	echo '{"status":"success","res":"'.$res.'"}';
    }

      public function update_saleCreditNote_header(){
    	$this->load->model('ar/saleInvoice_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->saleInvoice_model->update_byID("comp_sales_creditnote", $this->input->post('creditNoteID') ,$data);
    	echo '{"status":"success","res":"'.$res.'"}';
    }

     public function update_receivePayment_header(){
    	$this->load->model('ar/saleInvoice_model');
    	$data = array(
    		'projectID' => $this->input->post('project') ,
    		'referenceNo' => $this->input->post('referenceNo') ,
    		'receivePaymentDate' =>date('Y-m-d', strtotime($this->input->post('date'))),
    		 'memo' => $this->input->post('memo')
    	 );
    	$res = $this->saleInvoice_model->update_byID("comp_receive_payment", $this->input->post('masterId') ,$data);
    	echo '{"status":"success","res":"'.$res.'"}';
    }

} //big end
