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

class gstReport extends CI_Controller {
	
	public function __construct(){
		parent::__construct();
		$this->load->model('Useraccess');
		$query = $this->Useraccess->useraccess_id_module2('6', 'reports');
		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(){
		
		$this->lang->load("gst",$this->session->userdata('language'));
		$this->load->model('company/FormSetup_model');
		$this->load->model('Compfinancialyear');
        $this->load->model('UseraccessDetails');
        $this->load->model('taxgroup');
        $this->load->model('taxtype');
        $this->load->model('gst');
		
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('GSTRPT01');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
		
		//Financial calendar
		$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");
		}
		//$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);
		
		//Gather Tax group
		$data['tax_group'] = $this->taxgroup->taxgroup_all();
		
		//Gather Tax Types
		$data['tax_type'] = $this->taxtype->taxtype_all();
		
		//Gather Tax Code
		$data['tax_code'] = $this->gst->getCodebyType();
		
		//data collection
		if($queryCal){
			$post= array(
						"date"=>$this->getDate($data['selyear'],$data['selper'],$data['selper']),
						"gstGroup"=>'all',
						"gstType"=>'all'
					);
			$data['datatbls'] = $this->gst->gst_all($post);
		}else{
			$data['datatbls'] = NULL;
		}
		//Configuration for table header
		$data['tbHdr'] = array(
			"transType" =>"transType",
			"ref" =>"ref",
			"effective_date" =>"effective_date",
			"customerName" =>"customerName",
			"itemName" =>"itemName",
			"amountExcludedTax" =>"amountExcludedTax",
			"taxRate" =>"taxRate",
			"taxAmount" =>"taxAmount",
			"amountIncludedTax" =>"amountIncludedTax",
			"gst" => "gst"
		);
		
		//right aligned columns
		$data['alignRight'] = array('amountExcludedTax','taxRate','taxAmount','amountIncludedTax');
		
		$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/validationengine/jquery.validationEngine.js');
		$this->layouts->view('gst/report/gstReport', array('latest' => 'sidebar/latest'), $data);
	}
	
	//Print GST Report
	public function gstPrint($year,$periodFrom,$periodTo,$gstGroup,$gstType,$gstCode,$mode = false){
		$this->lang->load("gst",$this->session->userdata('language'));
		$this->load->model('gst');	
		$date = $this->getDate($year,$periodFrom,$periodTo);
		if($gstGroup != 'all')	$gstGrpName = $this->gst->getGroupbyID($gstGroup);	
		else					$gstGrpName = 'All';
		$post= array(
					"date"=>$date,
					"gstGroup"=>$gstGroup,
					"gstType"=>$gstType,
					"gstCode"=>$gstCode
				);
		$data['datatbls'] = $this->gst->gst_all($post);	

        $data['grpByType'] = array();
        $i = 0;
        $type = 0;

		$amountExcludedTax = 0;
		$taxAmount = 0;
		$total = 0;
        $__amountExcludedTax = 0;
		$__taxAmount = 0;
		$__total = 0;
        foreach($data['datatbls'] as $v){
            if(!$type){
                $type = $v->taxType;
                $data['grpByType'][str_replace(' ','_',$this->gst->getTypebyID($v->taxType))]['data'][] = $v;
				$amountExcludedTax += $v->amountExcludedTax;
				$taxAmount += $v->taxAmount;
				$total += $v->amountIncludedTax;
            }elseif($type == $v->taxType){
                $data['grpByType'][str_replace(' ','_',$this->gst->getTypebyID($v->taxType))]['data'][] = $v;
				$amountExcludedTax += $v->amountExcludedTax;
				$taxAmount += $v->taxAmount;
				$total += $v->amountIncludedTax;
            }else{
                $i++;
				$data['grpByType'][str_replace(' ','_',$this->gst->getTypebyID($type))]['amountExcludedTax'] = $amountExcludedTax;
				$data['grpByType'][str_replace(' ','_',$this->gst->getTypebyID($type))]['taxAmount'] = $taxAmount;
				$data['grpByType'][str_replace(' ','_',$this->gst->getTypebyID($type))]['total'] = $total;

				$__amountExcludedTax += $amountExcludedTax;
				$__taxAmount += $taxAmount;
				$__total += $total;

                $amountExcludedTax = $v->amountExcludedTax;
				$taxAmount = $v->taxAmount;
				$total = $v->amountIncludedTax;
                $type = $v->taxType;
                $data['grpByType'][str_replace(' ','_',$this->gst->getTypebyID($v->taxType))]['data'][] = $v;
            }
        }
		$data['grpByType'][str_replace(' ','_',$this->gst->getTypebyID($type))]['amountExcludedTax'] = $amountExcludedTax;
		$data['grpByType'][str_replace(' ','_',$this->gst->getTypebyID($type))]['taxAmount'] = $taxAmount;
		$data['grpByType'][str_replace(' ','_',$this->gst->getTypebyID($type))]['total'] = $total;

        $__amountExcludedTax += $amountExcludedTax;
        $__taxAmount += $taxAmount;
        $__total += $total;

		//$headerData['rightContentHeader'] = "Name supplier/ ot";
		$headerData['rptTitle'] = $this->lang->line("GSTReport");
		$headerData['leftContentHeader'] = "Taxable Period: ".date("d-m-Y",strtotime($date['startDate'])).' To '.date("d-m-Y",strtotime($date['endDate']));
		$headerData['leftContent'] = array("Tax Group: ".$gstGrpName);
		$headerData['rightContent'] = array("As at: ".date("d-m-Y"));
	

		$bodyData['excelTitle'] = $this->lang->line("GSTReport");    
		
		if(!$mode){
			//print 
			$this->load->view('layouts/report/header', $headerData);
            $count = 1;
			foreach($data['grpByType'] as $key=>$v){
				$bodyData['headerLeft'] = str_replace('_',' ',$key);
				$bodyData['rptDataDetail'] = $v['data'];
				$bodyData['tableHeader'] = array($this->lang->line('transType'),$this->lang->line('ref'),$this->lang->line('effective_date'),$this->lang->line('customerName'),$this->lang->line('itemName'),$this->lang->line('amountExcludedTax'),$this->lang->line('taxRate'),$this->lang->line('taxAmount'),$this->lang->line('amountIncludedTax'),$this->lang->line('gst')); 
				$bodyData['selectFields'] = array("transType", "ref", "effective_date","customerName",'itemName','amountExcludedTax','taxRate','taxAmount','amountIncludedTax','gst');
				$bodyData['tdAmount'] = array('amountExcludedTax','taxRate','taxAmount','amountIncludedTax');
				$bodyData['tableFooter'] = array (
                                                "Sub Total ",
                                                number_format($v['amountExcludedTax'],2,".",","),
                                                "",
                                                number_format($v['taxAmount'],2,".",","),
                                                number_format($v['total'],2,".",","),
                                                ""
                                            );
                if(sizeof($data['grpByType']) == $count){
                    $bodyData['grandTotal'] = array (
                        "Grand Total ",
                        number_format($__amountExcludedTax,2,".",","),
                        "",
                        number_format($__taxAmount,2,".",","),
                        number_format($__total,2,".",","),
                        ""
                    );
                }
				$this->load->view('layouts/report/body-gst', $bodyData);
                $count++;
			}
						
			$this->load->view('layouts/report/footer','');
		}else{
			$body = array();
			$count = 1;
			foreach($data['grpByType'] as $key=>$v){
				$bodyData['headerLeft'] = str_replace('_',' ',$key);
				$bodyData['rptDataDetail'] = $v['data'];
				$bodyData['tableHeader'] = array($this->lang->line('transType'),$this->lang->line('ref'),$this->lang->line('effective_date'),$this->lang->line('customerName'),$this->lang->line('itemName'),$this->lang->line('amountExcludedTax'),$this->lang->line('taxRate'),$this->lang->line('taxAmount'),$this->lang->line('amountIncludedTax'),$this->lang->line('gst')); 
				$bodyData['selectFields'] = array("transType", "ref", "effective_date","customerName",'itemName','amountExcludedTax','taxRate','taxAmount','amountIncludedTax','gst');
				$bodyData['tdAmount'] = array('amountExcludedTax','taxRate','taxAmount','amountIncludedTax');
				$bodyData['tableFooter'] = array (
                                                "Sub Total ",
                                                number_format($v['amountExcludedTax'],2,".",","),
                                                "",
                                                number_format($v['taxAmount'],2,".",","),
                                                number_format($v['total'],2,".",","),
                                                ""
                                            );
                if(sizeof($data['grpByType']) == $count){
                    $bodyData['grandTotal'] = array (
                        "Grand Total ",
                        number_format($__amountExcludedTax,2,".",","),
                        "",
                        number_format($__taxAmount,2,".",","),
                        number_format($__total,2,".",","),
                        ""
                    );
                }
				//$this->load->view('layouts/report/body-gst', $bodyData);
				$body[] = $bodyData;
                $count++;
			}
			//download excell
			$this->load->helper('excel');			
			excelgst($headerData,array($body),'');
		}
	}
	
	//Gather GST report based on filters
	public function getReport(){
        $this->load->model('gst');
		
		//Post data
		$post = $this->input->post();
		$post['date'] = $this->getDate($post['year'],$post['periodFrom'],$post['periodTo']);
		//gather data
		$data['data'] = $this->gst->gst_all($post);
		echo json_encode($data);
		exit();	
	}
	
	//Gather GST types
	public function getType(){
		$this->lang->load("gst",$this->session->userdata('language'));
		$this->load->model("gst");
		$data = $this->gst->getTypebyGroup($this->input->post('taxGroup'));
		$str = '';
		$str .= '<option value="all">'.$this->lang->line('all').'</option>';
		foreach($data as $v){
			$str .= '<option value="'.$v->ID.'">['.$v->code.'] '.$v->description.'</option>';
		}
		$data['type'] = $str;
		
		$code = $this->gst->getCodebyType($this->input->post('taxGroup'),$this->input->post('taxType'));
		$str = '';
		$str .= '<option value="all">'.$this->lang->line('all').'</option>';
		if(isset($code) && !empty($code)){
			foreach($code as $v){
				$str .= '<option value="'.$v->code.'"><b>['.$v->code.']</b> '.$v->name.'</option>';
			}
		}
		$data['code'] = $str;
		
		echo json_encode($data);
		exit();
	}
	
	//Get start and end date according to the period
	public function getDate($year,$pFrom,$pTo){
		$this->load->model('Compfinancialyear');
		$date['start'] = $this->Compfinancialyear->financialYear_yearperiod($year,$pFrom);
		$date['end'] = $this->Compfinancialyear->financialYear_yearperiod($year,$pTo);
		return array('startDate'=>$date['start'][0]->startDate,'endDate'=>$date['end'][0]->endDate);
	}

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

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

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

        //Configuration for table header
        $data['tbHdr'] = array(
            "invoiceNo",
            "invDate",
            "dueDays",
            "totalAmnt",
            "gstAmnt",
            "outAmnt",
            "badDebtsAmnt",
            "taxCode"
        );

        //right aligned columns
        $data['alignRight'] = array('totalAmnt','gstAmnt','outAmnt','badDebtsAmnt');

        //Customer List
        $this->load->model('customer/Customer_model');
        $data['customer'] = $this->Customer_model->customermaster_all();

        $data['datatbls'] = "";//$this->gst->getBadDebt(date('Y-m-d'));

        $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/validationengine/jquery.validationEngine.js')
					->add_includes('js/accounting.js');
        $this->layouts->view('gst/transaction/gstOutputRelief', array('latest' => 'sidebar/latest'), $data);
    }

    //Gather Bad Debt customers
    public function getBadCust(){
        $this->load->model('gst');
        echo json_encode($this->gst->getBadDebt($this->input->post('date'),$this->input->post('customerID')));
    }

    //Save bad debt information
    public function saveBadCust(){
        $this->load->model('gst');
    	$data = array(
    			"companyID" 	=> element('compID', $this->session->userdata('logged_in')),
    			"custID"		=> $this->input->post("custID"),
    			"valueBadDebt"	=> $this->input->post("valueBadDebt"),
    			"gstBadDebt"	=> $this->input->post("gstBadDebt"),
    			"transDate"		=> date("Y-m-d",strtotime($this->input->post("transDate"))),
    			//"badDebtIncGST"	=> $this->input->post("badDebtIncGST"),
    			"createdBy"		=> element('role', $this->session->userdata('logged_in')),
    		);
    	$badDebtID = $this->gst->saveBadDebt($data);
    	if($badDebtID){
    		if($this->gst->updateBadDebtDetail($badDebtID,$this->input->post("invID"))){
    			echo json_encode('true');
    		}
    	}
    }
    //Update bad debt information
    public function updateBadCust(){
        $this->load->model('gst');
    	$data = array(
    			"valueBadDebt"	=> $this->input->post("valueBadDebt"),
    			"gstBadDebt"	=> $this->input->post("gstBadDebt"),
    			"updatedBy"		=> element('role', $this->session->userdata('logged_in')),
    		);
    	$badDebtID = $this->gst->updateBadDebt($data,$this->input->post("ID"));
    	if($badDebtID){
    		if($this->gst->updateBadDebtDetail($this->input->post("ID"),$this->input->post("invID"),true)){
    			echo json_encode('true');
    		}
    	}else{
    		echo json_encode("false");
    	}
    }

    //bad debt relief confirm list
    public function badDebtReliefConfirm($startDate = '',$endDate = ''){
    	$this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APBANKRE');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }

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

        $data['startDate'] = $startDate = ($startDate == '')?date('Y-m-01'):date('Y-m-d',strtotime($startDate));
        $data['endDate'] = $endDate = ($endDate == '')?date('Y-m-d'):date('Y-m-d',strtotime($endDate));
		
		//Customer List
        /*$this->load->model('customer/Customer_model');
        $data['customer'] = $this->Customer_model->customermaster_all();*/

        $data['datatbls'] = $this->gst->badDebtList($startDate,$endDate);
        //print_r($data['datatbls']);
        //exit();
        //Configuration for table header
        $data['tbHdr'] = array(
            "transDate",
            "customerName",
            "valueBadDebt",
            "gstBadDebt",
        );

        //right aligned columns
        $data['alignRight'] = array('valueBadDebt','gstBadDebt');

        $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/validationengine/jquery.validationEngine.js')
					->add_includes('js/accounting.js');
        $this->layouts->view('gst/transaction/badDebtConfirm', array('latest' => 'sidebar/latest'), $data);
    }

    //Bad Debt Relief edit
    public function editBadDebt($ID){
    	$this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APBANKRE');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $this->load->model('gst');
        $data['datatbls'] = $this->gst->getBadDebtEntry($ID);
        //print_r($data['datatbls']);
        $this->lang->load("gst",$this->session->userdata('language'));
        $this->load->model('gst');

        //Configuration for table header
        $data['tbHdr'] = array(
            "invoiceNo",
            "invDate",
            "dueDays",
            "totalAmnt",
            "gstAmnt",
            "outAmnt",
            "badDebtsAmnt",
            "taxCode"
        );

        //right aligned columns
        $data['alignRight'] = array('totalAmnt','gstAmnt','outAmnt','badDebtsAmnt');

        //Customer List
        $this->load->model('customer/Customer_model');
        $data['customer'] = $this->Customer_model->customermaster_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/validationengine/jquery.validationEngine.js')
					->add_includes('js/accounting.js');
        $this->layouts->view('gst/transaction/edit', array('latest' => 'sidebar/latest'), $data);
    }

    public function badDebtPosting(){
    	$this->lang->load("gst",$this->session->userdata('language'));
    	$this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APBANKRE');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $this->load->model('gst');
        //get bad debt detail
        $badDebtIDs = explode(',',$this->input->post('badDebtID'));
        foreach($badDebtIDs as $row){
        	$query = $this->gst->getBadDebtEntry($row);
        	if($query){
			$this->load->model('Compfinancialyear');
			$query1 = $this->Compfinancialyear->compfinancialyear_date1($query[0]->transDate);
			if($query1){
				$year = $query1[0]->financialYear;
				$period = $query1[0]->period;
				$formNo = "BD[001]";
			}else{
   				print json_encode(array("status"=>"failed", "message"=>"Financial Year not found"));
				return FALSE;
			}
 			$this->load->model('Glseq');
			$query2 = $this->Glseq->glSequence_sub('5', 'BD', $year, $period);
			$newData = array(
				'companyID' => element('compID', $this->session->userdata('logged_in')),
				'journalID' => $query2['seqNumber'],
				'formNo' => $formNo,
				'description' => $query[0]->customerName.' ['.$this->lang->line('journalMsg') . ']',
				'module' => '5',
				'effective_date' => $query[0]->transDate,
				'year' => $year,
				'period' => $period,
				'createdBy' => element('role', $this->session->userdata('logged_in'))
			);
			$data = array(
				'journalNo'	=>$query2['seqNumber'],
				'updateAble'=>0
			);
			$query5 = $this->gst->update('comp_sales_bad_debt', $query[0]->badID, $data);
			$this->load->model('Journal');
			$query3 = $this->Journal->journal_insert($newData); 
			if($query3){
				$query4 = $this->gst->journalDetailEntry($query2['seqNumber'], $query[0], $query, $year, $period);
//				$query4 = $this->SalesDeliveryOrder->SalesDeliveryOrderdetails_deliveryID($queryDetails);
  				print json_encode(array("status"=>"success", "message"=>$query));
				return;
			}else{
  				print json_encode(array("status"=>"failed", "message"=>$query));
				return;
			}
		}else{
  				print json_encode(array("status"=>"failed", "message"=>$query));
			return FALSE;
		} 
        }

    }

    //Printing output relief
    public function gstOutputReliefPrint($date = '', $custID = 'all',$mode = false){
        if($date == '') $date = date('Y-m-d');
        $this->lang->load("gst",$this->session->userdata('language'));
        $this->load->model('gst');
        $data['datatbls'] = $this->gst->getBadDebt($date,$custID);

        //$headerData['rightContentHeader'] = "Name supplier/ ot";
        $headerData['rptTitle'] = $this->lang->line('outDebtHdr');
        $headerData['rightContent'] = array("As at: ".date('d-m-Y', strtotime($date)));

        $bodyData['rptDataDetail'] = $data['datatbls'];
        $bodyData['tableHeader'] = array($this->lang->line("invoiceNo"),
                                            $this->lang->line("invDate"),
                                            $this->lang->line("dueDays"),
                                            $this->lang->line("totalAmnt"),
                                            $this->lang->line("gstAmnt"),
                                            $this->lang->line("outAmnt"),
                                            $this->lang->line("badDebtsAmnt"),
                                            $this->lang->line("taxCode")
                                        );
        $bodyData['selectFields'] = array("invoiceNo", "invDate", "dueDays","totalAmnt","gstAmnt","outAmnt","badDebtsAmnt","taxCode");
        $bodyData ['tdAmount'] = array("dueDays","totalAmnt","gstAmnt","outAmnt","badDebtsAmnt");
        $bodyData['tableFooter'] = array ("");
        $bodyData['excelTitle'] = $this->lang->line('outDebtHdr');

        if(!$mode){
            //print
            $this->load->view('layouts/report/header', $headerData);
            $this->load->view('layouts/report/body', $bodyData);
            $this->load->view('layouts/report/footer','');
        }else{
            //download excell
            $this->load->helper('excel');
            excel($headerData,array($bodyData),$footerData);
        }
    }


    //bad debt recovery report
    public function badDebtPrint($dateFrom = '',$dateTo = ''){
    	$this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('INVMOVRP');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }		

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

		if($dateFrom == '')  $dateFrom= date('Y-m-d', strtotime(date('Y-m-1')));
		if($dateTo == '')	 $dateTo= date('Y-m-d', time());
		
		$data['dateFrom'] = $dateFrom;
		$data['dateTo'] = $dateTo;
		if($dateFrom != '' && $dateTo != '')
			$data['datatbls'] = $this->gst->badDebtList($dateFrom,$dateTo);
		else	$data['datatbls'] = '';
		

		//Configuration for table header
        $data['tbHdr'] = array(
            "transDate",
            "customerName",
            "valueBadDebt",
            "gstBadDebt",
        );

        //right aligned columns
        $data['alignRight'] = array('valueBadDebt','gstBadDebt');



		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js')
					->add_includes('js/validationengine/jquery.validationEngine.js');
		$this->layouts->view('gst/report/bad_debt_print', array('latest' => 'sidebar/latest'), $data);
    }


    /*******************************Bad Debt Recover********************************/
    //customer output removeable
    public function badDebtRecover(){
		$this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('GSBADBTR');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $this->lang->load("gst",$this->session->userdata('language'));
        $this->load->model('gst');

        //Configuration for table header
        $data['tbHdr'] = array(
            "invoiceNo",
            "badDebtReliefDate",
            "totalAmount",
            "gstAmount",
            "payMade",
            "outStand",
            "badDebtRecover",
            "taxCode"
        );

        //right aligned columns
        $data['alignRight'] = array('totalAmount','gstAmount',"payMade",'outStand','badDebtRecover');

        //Customer List
        $this->load->model('customer/Customer_model');
        $data['customer'] = $this->Customer_model->customermaster_all();

        $data['datatbls'] = $this->gst->getDebtRecover(date('Y-m-d'));
        //print_r($data['datatbls']);
        //exit();
        $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/validationengine/jquery.validationEngine.js')
					->add_includes('js/accounting.js');
        $this->layouts->view('gst/transaction/badDebtRecover', array('latest' => 'sidebar/latest'), $data);
    }

    //Gather Bad Debt customers
    public function recoverBadCust(){
        $this->load->model('gst');
        echo json_encode($this->gst->getBadDebt($this->input->post('date'),$this->input->post('customerID')));
    }

    public function getDebtRecover(){
		$this->load->model('gst');
        echo json_encode($this->gst->getDebtRecover($this->input->post('date'),$this->input->post('customerID')));    	
    }

    public function saveDebtRecovery(){
    	$this->load->model('gst');
    	$data = array(
    			"companyID" 	=> element('compID', $this->session->userdata('logged_in')),
    			"custID"		=> $this->input->post("custID"),
    			"valueDebtRecover"	=> $this->input->post("valueDebtRecover"),
    			"gstDebtRecover"	=> $this->input->post("gstDebtRecover"),
    			"transDate"		=> date("Y-m-d",strtotime($this->input->post("transDate"))),
    			"createdBy"		=> element('role', $this->session->userdata('logged_in')),
    		);
    	$DebtRecoverID = $this->gst->insert('comp_sales_debt_recover',$data);
    	if($DebtRecoverID){
    		if($this->gst->updateDebtRecoverDetail($DebtRecoverID,$this->input->post("invID"))){
    			echo json_encode('success');
    		}
    	}
    }

    //Bad Debt recovery confirm list
    public function DebtRecoverConfirm($startDate = '',$endDate = ''){
    	$this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APBANKRE');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }

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

        $data['startDate'] = $startDate = ($startDate == '')?date('Y-m-01'):date('Y-m-d',strtotime($startDate));
        $data['endDate'] = $endDate = ($endDate == '')?date('Y-m-d'):date('Y-m-d',strtotime($endDate));
		
		//Customer List
        /*$this->load->model('customer/Customer_model');
        $data['customer'] = $this->Customer_model->customermaster_all();*/

        $data['datatbls'] = $this->gst->DebtRecoverList($startDate,$endDate);

        //Configuration for table header
        $data['tbHdr'] = array(
            "transDate",
            "custName",
            "valueDebtRecover",
            "gstDebtRecover",
        );

        //right aligned columns
        $data['alignRight'] = array('valueBadDebt','gstBadDebt');

        $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/validationengine/jquery.validationEngine.js')
					->add_includes('js/accounting.js');
        $this->layouts->view('gst/transaction/DebtRecoverConfirm', array('latest' => 'sidebar/latest'), $data);
    }

    //bad debt recovery report
    public function badDebtrecoverPrint($dateFrom = '',$dateTo = ''){
    	$this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('INVMOVRP');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }		

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

		if($dateFrom == '')  $dateFrom= date('Y-m-d', strtotime(date('Y-m-1')));
		if($dateTo == '')	 $dateTo= date('Y-m-d', time());
		
		$data['dateFrom'] = $dateFrom;
		$data['dateTo'] = $dateTo;
		if($dateFrom != '' && $dateTo != '')
			$data['datatbls'] = $this->gst->DebtRecoverList($dateFrom,$dateTo);
		else	$data['datatbls'] = '';
		

		//Configuration for table header
        $data['tbHdr'] = array(
            "transDate",
            "custName",
            "valueDebtRecover",
            "gstDebtRecover",
        );

        //right aligned columns
        $data['alignRight'] = array('valueBadDebt','gstBadDebt');


		$this->layouts->add_includes('js/datatables/jquery.dataTables.min.js')
					->add_includes('js/validationengine/jquery.validationEngine.js');
		$this->layouts->view('gst/report/bad_debtrecover_print', array('latest' => 'sidebar/latest'), $data);
    }

    //Bad Debt recovery edit

    public function editDebtRecover($ID){
    	$this->load->model('UseraccessDetails');
        $query = $this->UseraccessDetails->UseraccessDetails_id_code('APBANKRE');
        if (!$query) {
            echo '<script>alert("Not authorised..");
				window.location.replace("' . base_url() . 'Error");
				</script>';
        }
        $this->load->model('gst');
        $data['prevData'] = $this->gst->getPrevDetail($ID);
        $data['datatbls'] = $this->gst->getDebtRecoverEntry($ID,$data['prevData'][0]->custID);
        //print_r($data['datatbls']);
        $this->lang->load("gst",$this->session->userdata('language'));
        $this->load->model('gst');

        //Configuration for table header
        $data['tbHdr'] = array(
            "invoiceNo",
            "badReliefDate",
            "totAmount",
            "gstAmnt",
            "payment",
            "outStanding",
            "badDebtRecover",
            "taxCode"
        );

        //right aligned columns
        $data['alignRight'] = array('totalAmnt','gstAmnt','outAmnt','badDebtsAmnt');

        //Customer List
        $this->load->model('customer/Customer_model');
        $data['customer'] = $this->Customer_model->customermaster_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/validationengine/jquery.validationEngine.js')
					->add_includes('js/accounting.js');
        $this->layouts->view('gst/transaction/editRecovery', array('latest' => 'sidebar/latest'), $data);
    }
    //Update Debt Recovery entry
    //Update bad debt information
    public function updateDebtRecover(){
        $this->load->model('gst');
    	$data = array(
    			"valueDebtRecover"	=> $this->input->post("valueDebtRecover"),
    			"gstDebtRecover"	=> $this->input->post("gstDebtRecover"),
    			"updatedBy"		=> element('role', $this->session->userdata('logged_in')),
    		);
    	$badDebtID = $this->gst->update('comp_sales_debt_recover',$this->input->post("ID"),$data);
    	if($badDebtID){
    		if($this->gst->updateDebtRecoverDetail($this->input->post("ID"),$this->input->post("invID"),true)){
    			echo json_encode('true');
    		}
    	}else{
    		echo json_encode("false");
    	}
    }


    /*******************************Bad Debt Recover end********************************/
} //big end
