<?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 newDirectSaleInvoice(){
			$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_all();
			
			$data['itemCodes'] = $this->getItemCodes();
			
//			$this->load->model('company/formSetup_Model');
			$filter['companyID']=element('compID', $this->session->userdata('logged_in'));
			$filter['formID']=48;
			$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);
	}
	
	public function salesinvPost(){
		$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('salesinv_model');
		$this->load->model('company/FormSetup_model');
		$this->load->model('Compfinancialyear');
		$data['yrs'] = range(date('Y'), 1900);
		$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->salesinv_model->salesinv_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/salesinvPost', array('latest' => 'sidebar/latest'), $data);
	}

	public function invoicePosting(){
		$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){
			$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->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 directsalesinvPost(){
		$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);
		$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->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){
			$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->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 refreshSupplier(){
		//for ajax call 
		$this->load->model('Supplier/supplier_model');
		$supllier = $this->supplier_model->suppliermaster_all();
		$JsonRecords = '{"records":[';
		
		$n = sizeof($supllier);
		$i= 0;
		if($supllier)
		 foreach($supllier as $row){
			$JsonRecords .= '{';
			$JsonRecords .= '"supplierName":"' . $row->supplierName . '","id":"'.$row->ID.'"';
			$JsonRecords .= '}';
			if ($i < $n - 1)
				$JsonRecords .= ',';
			$i++;
		}
		$JsonRecords .= ']}';
		
		//$resul= '{"supplier":['. json_encode($this->supplier_model->suppliermaster_all()).']}';
		 echo $JsonRecords;
	}
	
	public function getItemCodes(){
		$JsonRecords = '[';
		$i= 0;
		$this->load->model('item/itemSetup_model');
		//$default = $this->itemSetup_model->get_byCode($this->input->post('itemCode'));
		$default = $this->itemSetup_model->get_all();
		$n = sizeof($default);
		if($default){
		 foreach($default as $row){
			$JsonRecords .= '&quot;'.$row->itemCode.'&quot;';
			if ($i < $n - 1)
				$JsonRecords .= ',';
			$i++;
		}
	}
		 $JsonRecords .= ']';
		 return $JsonRecords;
	}
	
	public function refreshTerms(){
		//for ajax call 
		$this->load->model('Terms/terms_model');
			$terms = $this->terms_model->terms_all();
		
		//json_encode ($this->project_model->project_all());
		
		$JsonRecords = '{"records":[';
		$n = sizeof($terms);
		$i= 0;
		if($terms)
		 foreach($terms as $row){
			$JsonRecords .= '{';
			$JsonRecords .= '"termName":"' . $row->termName.'","id":"'.$row->ID.'"';
			$JsonRecords .= '}';
			if ($i < $n - 1)
				$JsonRecords .= ',';
			$i++;
		}
		$JsonRecords .= ']}';

		//$resul= '{"supplier":['. json_encode($this->supplier_model->suppliermaster_all()).']}';
		 echo $JsonRecords;
	}
	
	public function refreshProject(){
		//for ajax call 
		$this->load->model('Project/project_model');
		$project = $this->project_model->project_all();
		
		//json_encode ($this->project_model->project_all());
		
		$JsonRecords = '{"records":[';
		$n = sizeof($project);
		$i= 0;
		if ($project)
		 foreach($project as $row){
			$JsonRecords .= '{';
			$JsonRecords .= '"id":"'.$row->ID.'","projectName":"' . $row->project_name.'"';
			$JsonRecords .= '}';
			if ($i < $n - 1)
				$JsonRecords .= ',';
			$i++;
		}
		$JsonRecords .= ']}';

		//$resul= '{"supplier":['. json_encode($this->supplier_model->suppliermaster_all()).']}';
		 echo $JsonRecords;
	}
	
	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'),
                    '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'))
            );

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


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

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

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

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

            $this->load->model('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'),
            '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 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"), $query);
            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('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_all();
            
             $this->load->model('item/itemSetup_model');
             $data['items'] = $this->itemSetup_model->get_all();
           
            $this->load->model('company/formSetup_Model');
            $filter['companyID']=element('compID', $this->session->userdata('logged_in'));
            
            $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'),
                     'lineNo' => $this->input->post('lineNo'), 
                    'itemdescription' => $this->input->post('itemdescription'),
                    'quantity' => $this->input->post('quantity'),
                    'unitPrice' => $this->input->post('unitPrice'),
                    'amountExcludedTax' => $this->input->post('amountExcludedTax'),
                    'taxID' => $this->input->post('taxID'),
                    'taxRate' => $this->input->post('taxRate'),
                    'taxAmount' => $this->input->post('taxAmount'),
                    'amountIncludedTax' => $this->input->post('amountIncludedTax')
            );
             $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);
             
             
             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'));
             
             //$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.'"}';
        }

        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'), 
                    'lineNo' => $this->input->post('lineNo'), 
                    'itemdescription' => $this->input->post('itemdescription'),
                    'quantity' => $this->input->post('quantity'),
                    'unitPrice' => $this->input->post('unitPrice'),
                    'amountExcludedTax' => $this->input->post('amountExcludedTax'),
                    'taxID' => $this->input->post('taxID'),
                    'taxRate' => $this->input->post('taxRate'),
                    'taxAmount' => $this->input->post('taxAmount'),
                    'amountIncludedTax' => $this->input->post('amountIncludedTax')
            );
             $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(){
		$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);
		$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->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]->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->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);
  				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('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_all();

            $this->load->model('item/itemSetup_model');
             $data['items'] = $this->itemSetup_model->get_all();
             
             $this->load->model('companyChartAcct');
            $data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();
             
            $this->load->model('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'),
                    'lineNo' => $this->input->post('lineNo'), 
                    'itemdescription' => $this->input->post('itemdescription'),
                    'quantity' => $this->input->post('quantity'),
                    'unitPrice' => $this->input->post('unitPrice'),
                    'amountExcludedTax' => $this->input->post('amountExcludedTax'),
                    'taxID' => $this->input->post('taxID'),
                    'taxRate' => $this->input->post('taxRate'),
                    'taxAmount' => $this->input->post('taxAmount'),
                    'amountIncludedTax' => $this->input->post('amountIncludedTax')
            );
             $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'),
                    'lineNo' => $this->input->post('lineNo'), 
                    'itemdescription' => $this->input->post('itemdescription'),
                    'quantity' => $this->input->post('quantity'),
                    'unitPrice' => $this->input->post('unitPrice'),
                    'amountExcludedTax' => $this->input->post('amountExcludedTax'),
                    'taxID' => $this->input->post('taxID'),
                    'taxRate' => $this->input->post('taxRate'),
                    'taxAmount' => $this->input->post('taxAmount'),
                    'amountIncludedTax' => $this->input->post('amountIncludedTax')
            );
             $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(){
		$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);
		$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->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('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');
             $data['items'] = $this->itemSetup_model->get_all();
             
             $this->load->model('companyChartAcct');
            $data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();

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

            $this->load->model('ar/saleInvoice_model');
            
            $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);

            $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'),
                    'itemdescription' => $this->input->post('itemdescription'),
                    'quantity' => $this->input->post('quantity'),
                    'unitPrice' => $this->input->post('unitPrice'),
                    'amountExcludedTax' => $this->input->post('amountExcludedTax'),
                    'taxID' => $this->input->post('taxID'),
                    'taxRate' => $this->input->post('taxRate'),
                    'taxAmount' => $this->input->post('taxAmount'),
                    'amountIncludedTax' => $this->input->post('amountIncludedTax')
            );
             $this->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_debitnote",array("totalTaxAmount","totalAmount"), $this->input->post('masterId'));
            echo '{"status":"'.$res.'"}';
        }
        
         public function editSaleCreditNote($id){
            
            $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'] = $this->itemSetup_model->get_all();
             
             $this->load->model('companyChartAcct');
            $data['chargeAccount'] = $this->companyChartAcct->chartAcct_all();

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

            $this->load->model('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);

            $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'), 
                    'itemdescription' => $this->input->post('itemdescription'),
                    'quantity' => $this->input->post('quantity'),
                    'unitPrice' => $this->input->post('unitPrice'),
                    'amountExcludedTax' => $this->input->post('amountExcludedTax'),
                    'taxID' => $this->input->post('taxID'),
                    'taxRate' => $this->input->post('taxRate'),
                    'taxAmount' => $this->input->post('taxAmount'),
                    'amountIncludedTax' => $this->input->post('amountIncludedTax')
            );
             $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('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("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');
            $filter['companyID']=element('compID', $this->session->userdata('logged_in'));
            $filter['formID']=44;
            $data['formNo']= $this->formSetup_Model->getFormNo($filter); 

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

            $this->layouts->view('ar/receivePayment/newreceivepayment', '', $data);
	}
        
        public function editReceivePayment ($id){
            $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->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'));
            $currency ="";
            $rate = "";
            $cId= "";
            
            $JsonRecords = '{';
            if ($default){
                foreach($default 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(){
		$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(date('Y'), 1900);
		$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->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]->ID) . ']';
				$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'),
                  '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(){
		//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('taxmaster');
		$data['taxmaster'] = $this->taxmaster->taxmaster_all();
			
		$data['itemCodes'] = $this->getItemCodes();
			
		//			$this->load->model('company/formSetup_Model');
		$filter['companyID']=element('compID', $this->session->userdata('logged_in'));
		$filter['formID']=48;
		$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();
	}
	
	//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')),
		
				'totalTaxAmount' => $this->input->post('totalTaxAmount'),
				'totalReceivable' => $this->input->post('amountIncludedTax'),
				'totalamount' => $this->input->post('amountIncludedTax')
		);
		
		
		$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')
		);
		
		$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("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')),
	
				'totalTaxAmount' => $this->input->post('totalTaxAmount'),
				'totalReceivable' => $this->input->post('amountIncludedTax'),
				'totalamount' => $this->input->post('amountIncludedTax')
		);
	
	
		$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'),
					'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'),
																	));
	}
	/******************************************
	 *
	*  - Sayem
	*  end
	*
	*/ 
} //big end
