<?php
error_reporting(E_ALL ^ E_NOTICE ^E_WARNING);
class damFunctions extends active_record
{
	
	
	function getDeferralUserList($link,$deferral_user=FALSE) {
	
	$def_user = $this->select("*","asset_admin_master","asset_admin_usertype = 'operations' AND asset_user_status = 'Active'",$link);
	
	$def_user_list.= "<option value=''>-Select-</option>";
	for($u=0;$u<COUNT($def_user);$u++) {
		if($deferral_user==$def_user[$u]["asset_admin_username"])
		$def_user_list.= "<option value='".$def_user[$u]["asset_admin_username"]."' selected='selected'>".ucfirst($def_user[$u]["asset_admin_username"])."</option>";
		else
		$def_user_list.= "<option value='".$def_user[$u]["asset_admin_username"]."'>".ucfirst($def_user[$u]["asset_admin_username"])."</option>";
	}
	
	
	return $def_user_list;
	
	}
	
	function getNIIPLUserList($deferral_user=FALSE) {
		
		$niipl_user=array('Vijay Agre','Rajkumar Mali','Mangesh Hande','Deepak Janjire','Arun Viramgama','Sanjay Pethani','Jayanti Paghdar','Narendra Dhandre','Sangamesh B','Saravanakumar');
		$niipl_user_list.="<option value=''>-Select-</option>";
		foreach($niipl_user as $nu){
			$niipl_user_list.="<option value='".$nu."' ".$this->getDamDeferral($nu,$deferral_user,'select').">".$nu."</option>";
		}
		
		return $niipl_user_list;
	}	
		
	function getSBUUserList($deferral_user=FALSE) {
		
		$niipl_user=array('Vikas Sonawane','Vijay Rathod','K Mahamulkar');
		$niipl_user_list.="<option value=''>-Select-</option>";
		foreach($niipl_user as $nu){
			$niipl_user_list.="<option value='".$nu."' ".$this->getDamDeferral($nu,$deferral_user,'select').">".$nu."</option>";
		}
		
		return $niipl_user_list;
	}	
	
	function getDAMDeferralCompliedStatus($status=FALSE) {
		
		//echo $status;
		$def_status_list.= "<select name='compliance_status[]'><option value=\"\">-Select-</option>";
		
		$def_status_list.= "<option value=\"complied\" ".$this->getDamDeferral($status,'complied','select').">complied</option>";
		$def_status_list.= "<option value=\"pending\" ".$this->getDamDeferral($status,'pending','select').">pending</option>";
		$def_status_list.= "</select>";
		
		return $def_status_list;
	}
	
	function getKSDFSanctionList($link,$product_name=false,$dealer_code=false,$limit_check=false,$getorder_no=false){
		
		if($limit_check!='0'){
			
			
			$df_p=explode('-',$limit_check);
			$limit_check=$df_p[0];
			$s=$this->select("final_loan_amount","df_dam","niipl_order_no='$limit_check'",$link);	
			$ks_df_limit=$s[0]["final_loan_amount"];
			return $ks_df_limit;
			}
		else{
			
				
			$df_p=explode('-',$product_name);
			$df_product=$df_p[1];

			//$s=$this->select("*","df_dam","facility_type='$df_product' AND fk_dealer_code='$dealer_code'");	
			$s=$this->select("*","df_dam"," fk_dealer_code='$dealer_code'",$link);	
			$ks_df_limit.="<option value='NA' ".$this->getDamDeferral('NA',$getorder_no,'select').">NA</option>";
			foreach($s as $p){
			$dam_id=$p["df_dam_id"];
			$final_loan_amount=$p["final_loan_amount"];
			$final_invoice_value=$p["final_invoice_value"];
			$niipl_order_no=$p["niipl_order_no"];
			$order_no=$niipl_order_no."-".$dam_id;
			//echo "<br/>";
			$ff_amount=$this->select("SUM(cp_approved_amount) as total_disbursement","nafa_applicant_master","df_disbursement_id='$dam_id'",$link);

			$total_disbursement=$ff_amount[0]["total_disbursement"];
			if($total_disbursement <= $final_invoice_value){
			$ks_df_limit.="<option value=".$order_no." ".$this->getDamDeferral($order_no,$getorder_no,'select')." >$niipl_order_no</option>";


				}

			} 
			return $ks_df_limit;
		}
		
		
	}
	
		
	function getDamDeferral($dd,$cc,$type) {
		
		//echo $dd;
		if($dd==$cc) {
			if($type=='select')
			$pp = "selected='selected'";
			else
			$pp = "checked='checked'";
		}
		return $pp;
	}
	
	function DFExtraMaster(){	
	
		$type=func_get_arg(0);
		$location=func_get_arg(1);
	
		if($type==1 && $location==0)
			$product_name=array('FBL','FBL-Normal','FBL-Thin Wall','FBL-CMT','PRAGATI','SAHAJ','SAHAJ CMT','BL','FBL-CF','FBL-KISAN SAMRUDDHI');
		if($type==2 && $location==0)
			$product_name=array('REGULAR');
		if($type==0 && $location=='g')
			$product_name=array('GUJ1','GUJ2','GUJ3','GUJ4','GUJ5','GUJ6','GUJ7','Gujarat');
			
		return $product_name;			
	}
	
	function postDFActivity($activity_desc,$activity_by,$actId,$activityType,$link)	{
		$this->exe($link,"INSERT INTO `nafa_df_activity`(`df_fk_id`,`df_activity_description`, `df_activity_by`,`df_activity_type`) VALUES ('$actId','$activity_desc','$activity_by','$activityType')");
	}
	
	function getTransactionType($type=FALSE){
		
		$transaction_type.="";
		$transaction_type.="<option value=' '>-Select-</option><option value='2' ".$this->getDamDeferral($type,'2','select')." >PF/Insurance</option><option value='1' ".$this->getDamDeferral($type,'1','select').">Collateral</option><option value='3' ".$this->getDamDeferral($type,'3','select').">Interest</option><option value='4' ".$this->getDamDeferral($type,'4','select').">Penal Interest</option><option value='5' ".$this->getDamDeferral($type,'5','select').">Principal</option><option value='6' ".$this->getDamDeferral($type,'6','select').">Margin</option><option value='7' ".$this->getDamDeferral($type,'7','select').">Deferral Non-comp Chgs</option><option value='8' ".$this->getDamDeferral($type,'8','select').">Cheque Return Charges</option><option value='9' ".$this->getDamDeferral($type,'9','select').">Stamp Duty</option><option value='10' ".$this->getDamDeferral($type,'10','select').">Other Charges</option>";
		return $transaction_type;
	}
	
	function getReceiptType($type){
		switch($type){
			case 1:
			$receipt_type='Collateral';
				break;
			
			case 2:
			$receipt_type='PF/Insurance';
				break;
			
			case 3:
			$receipt_type='Interest';
				break;
				
			case 4:
			$receipt_type='Penal Interest';
				break;
				
			case 5:
			$receipt_type='Principal';
				break;			
				
			case 6:
			$receipt_type='Margin';
				break;
				
			case 7:
			$receipt_type='Deferral Non-comp Chgs';
				break;
			case 8:
			$receipt_type='Cheque Return Charges';
				break;
			case 9:
			$receipt_type='Stamp Duty';
				break;
			case 10:
			$receipt_type='Other Charges';
				break;
				
			default:
				break;
		}
		
		return $receipt_type;
	}
	
	function getDFBankList($bank=FALSE){
		
		$bankList="<option value=''>-Select-</option><option value='SBI Bank' ".$this->getDamDeferral($bank,'SBI Bank','select')." >SBI Bank</option><option value='YES Bank' ".$this->getDamDeferral($bank,'YES Bank','select').">YES Bank</option><option value='HDFC Bank' ".$this->getDamDeferral($bank,'HDFC Bank','select').">HDFC Bank</option><option value='YES-114' ".$this->getDamDeferral($bank,'YES-114','select').">YES-114</option>";
		return $bankList;
	}
	
	function getPFAmount($dealer_code,$product,$link){
		
		
		$cam_pf=$this->select_join("processing_fee","df_cam_proposed_loan_details a","LEFT JOIN df_cam_entry b ON a.fk_cam_id=b.cam_entry_id","a.fk_dealer_code='$dealer_code' AND a.fk_product_name='$product'",$link);
		
		$dam_pf=$this->select("sum(pf) as total_dam_pf","df_dam","fk_dealer_code='$dealer_code' AND dam_product_name='$product'",$link);
		
		$total_cam_pf=$cam_pf[0]["processing_fee"];
		$total_dam_pf=$dam_pf[0]["total_dam_pf"];
		$balance_pf=$total_cam_pf-$total_dam_pf;
		return $balance_pf;
		
	}
	
	function getDealerReceipt($dealer_rcode,$link){
		
		$dealer_receipt=$this->select("df_receipt_entry_id,receipt_number,receipt_amount,receipt_date","nafa_df_receipt_entry","fk_dealer_code='$dealer_rcode' AND receipt_status='UnApplied' ORDER BY receipt_date",$link);		
	
		$receipt_list= "<option value=''>-Select-</option>";
		if($dealer_receipt){
			
			for($l=0;$l<count($dealer_receipt);$l++){			
				$df_receipt_entry_id=$dealer_receipt[$l]["df_receipt_entry_id"];
				$receipt_number=$dealer_receipt[$l]["receipt_number"];
				$receipt_amount=$dealer_receipt[$l]["receipt_amount"];
				$receipt_date=$this->oracle_date($dealer_receipt[$l]["receipt_date"]);
				
				$receipt_app=$this->select("ROUND(SUM(applied_receipt_amount),0) as total_applied","nafa_df_receipt_application","fk_dealer_code='$dealer_rcode' AND fk_receipt_number='$df_receipt_entry_id'",$link);
				$receipt_applied=$receipt_app[0]["total_applied"];
				$receipt_available=$receipt_amount-$receipt_applied;


				$receipt_list.= "<option value='".$df_receipt_entry_id."' receipt_available='".$receipt_available."' >".$receipt_number.' - ('.$receipt_date .")</option>";

			}
			
			return $receipt_list;
		}
	
	}
	
	function getDealerProduct($dealer_rcode,$link){
		
		//$df_limit=$this->select("*","dealer_limit_master","fk_dealer_code='$dealer_rcode' AND product_name not in('SAHAJ','PRAGATI','SAHAJ CMT') ");	
		$df_limit=$this->select("*","dealer_limit_master","fk_dealer_code='$dealer_rcode'",$link);	
		
		$product.= "<option value='0'>All</option>";
		if($df_limit){
			
			for($l=0;$l<count($df_limit);$l++){
				
				$bl_limit=$df_limit[$l]["bl_limit"]	;
				$base_limit=$df_limit[$l]["base_limit"]	;
				$dealer_limit=$df_limit[$l]["dealer_limit"]	;
				$product_name=$df_limit[$l]["product_name"];
				
				$fbl_product_name=array('FBL-Normal','FBL-Thin Wall','FBL-CMT');
				/*
				if($product_name=='FBL'){
					foreach($fbl_product_name as $p){
						$product.= "<option value='".$p."'>".$p."</option>";
					}
				}
				else{
					*/					
				$product.= "<option value='".$df_limit[$l]["product_name"]."'>".$df_limit[$l]["product_name"]."</option>";
				
				//}				
			}
		}
		
	return $product;

	}
	
	function getDateDifference($from_date,$to_date,$format){
		//format %d,%m,%y
		$today_date = new DateTime($from_date);
		$dob = new DateTime($to_date);
		$interval = $dob->diff($today_date);
		return $interval->$format;
		
		/*
		* $date2 = new DateTime("2015-04-28");
$date1 = new DateTime("2015-06-11");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; 

// shows the total amount of days (not divided into years, months and days like above)
echo "difference " . $interval->days . " days ";
		
		*/
		
	}
	
	function getDateSum($date,$days){
		
		return date("Y-m-d",strtotime($date.' + '.$days.' days'));	
	}
	
	function getDateMinus($date,$days){
		
		return date("Y-m-d",strtotime($date.' - '.$days.' days'));	
	}
	
	function getDateMatch($date1,$date2){
		$date1 = new DateTime($date1);
		$date2 = new DateTime($date2);
		if($date1==$date2){
			return true;
		}
	}
	
	function makeLoanInstallment($short_term_line,$link){
		
		$ans=$this->select("*","df_dam","short_term_line='$short_term_line'",$link);
	 	$df_dam_id=$ans[0]["df_dam_id"];
	 	$short_term_line=$ans[0]["short_term_line"];
	 	$rate_of_interest=$ans[0]["rate_of_interest"];
	 	//$dam_approved_date=$ans[0]["dam_approved_date"];
	 	$dam_approved_date=$ans[0]["dam_date"];
	 	
	 	$roi=$this->select("*","nafa_df_roi_master","rate_of_interest='$rate_of_interest'",$link);
	 	
		$exist_inst=$this->select("loan_roi_id","nafa_df_loan_roi","fk_stl_no='$short_term_line'",$link);

		if($exist_inst){

			$this->exe($link,"DELETE FROM nafa_df_loan_roi WHERE `fk_stl_no`='$short_term_line' ");
		}
	 	
	 	$i=1;
	 	$inst_date='0';
	 	foreach($roi as $r){
			
			//$inst_date1=$dam_approved_date;
			$inst_date1=$this->getDateSum($dam_approved_date,$inst_date);
			
			$inst_date=$this->getDateSum($dam_approved_date,$r["roi_end_day"]);
			$inst_date=$this->getDateMinus($inst_date,1);
			$inst_rate=$r["roi"];
			
			$exist_inst=$this->select("loan_roi_id","nafa_df_loan_roi","fk_stl_no='$short_term_line'",$link);
			
			$this->exe($link,"INSERT INTO `nafa_df_loan_roi`(`fk_stl_no`,`fk_dam_id` , `installment_no`, `installment_date1`, `installment_date`, `installment_rate`) VALUES ('$short_term_line','$df_dam_id','$i','$inst_date1','$inst_date','$inst_rate')");
			
			$inst_date=$r["roi_end_day"];
			
			$i++;
		}
		
		
	}
	
	function makeLoanDiscount($short_term_line,$link){
		
		$ans=$this->select("*","df_dam","short_term_line='$short_term_line'",$link);
	 	$df_dam_id=$ans[0]["df_dam_id"];
	 	$short_term_line=$ans[0]["short_term_line"];
	 	$add_dis_eligibility=$ans[0]["add_dis_eligibility"];
	 	$dam_approved_date=$ans[0]["dam_approved_date"];
	 	
	 	$discount=$this->select("*","nafa_df_discount_master","additional_discount='$add_dis_eligibility'",$link);
	 	
		$exist_inst=$this->select("loan_discount_id","nafa_df_loan_discount","fk_stl_no='$short_term_line'",$link);

		if($exist_inst){

			$this->exe($link,"DELETE FROM nafa_df_loan_discount WHERE `fk_stl_no`='$short_term_line' ");
		}
	 	
	 	$i=1;
	 	$inst_date='0';
	 	foreach($discount as $r){
			
			//$inst_date1=$dam_approved_date;
			$inst_date1=$this->getDateSum($dam_approved_date,$inst_date);		
			$inst_date=$this->getDateSum($dam_approved_date,$r["discount_end_day"]);
			$inst_date=$this->getDateMinus($inst_date,1);
			$inst_rate=$r["discount"];
			
			$exist_inst=$this->select("loan_discount_id","nafa_df_loan_discount","fk_stl_no='$short_term_line'",$link);
			
			$this->exe($link,"INSERT INTO `nafa_df_loan_discount`(`fk_stl_no`,`fk_dam_id` , `discount_no`, `discount_start_date`, `discount_end_date`, `discount_rate`) VALUES ('$short_term_line','$df_dam_id','$i','$inst_date1','$inst_date','$inst_rate')");
			
			$inst_date=$r["discount_end_day"];
			
			$i++;
		}
		
		
	}
	
	function getAmountOs($stlno,$msd,$med,$type,$link){
	
		$cam = new cam();
		$dam=$this->select("*","df_dam","short_term_line='$stlno' AND dam_date BETWEEN '$msd' AND '$med' ",$link);
		$dam_date=$dam[0]["dam_date"];
		
		$inst_due=$this->select("SUM(interest_amount) as total_interest_amount","nafa_df_due_list","fk_stl_no='$stlno' ORDER BY due_month DESC LIMIT 1",$link);
		
		$last_due=$this->select("*","nafa_df_due_list","fk_stl_no='$stlno' ORDER BY due_month DESC LIMIT 1",$link);
		
		
		$rec_app=$this->select("SUM(applied_receipt_amount) as total_fee_applied","nafa_df_receipt_application","fk_stl_no='$stlno' AND applied_receipt_type='$type'");
		
		switch($type){
				
			case 2:
				$total_charges=$dam[0]["total_charges"];
			  	$charges_collected=$dam[0]["charges_collected"];
			  	$balance_charges=$dam[0]["balance_charges"];
			  	$total_fee_applied=$rec_app[0]["total_fee_applied"];
			  	//if($last_due[0]["fee_amount"]!='')
			  	if(!empty($last_due[0]["fee_amount"]))
			  		$due=$cam->make_roundoff($last_due[0]["fee_amount"]);
			  	else{
					//echo $due=$cam->make_roundoff($balance_charges-$total_fee_applied);	
			  		$due=$cam->make_roundoff($total_charges);	
				}
			  		
				break;			
			default:
				break;
				
			
		}
		
		return $due;
	}
	
	function getAmountDue($stlno,$type){
		$cam = new cam();
		$dam=$this->select("*","df_dam","short_term_line='$stlno'",$link);
		$dam_date=$dam[0]["dam_date"];
		$today_date=date("Y-m-d");		
		
		$last_due=$this->select("*","nafa_df_due_list","fk_stl_no='$stlno' ORDER BY due_month DESC LIMIT 1",$link);
		$charge_due_qry =$this->select("SUM(amount)as amount","nafa_dealer_charges_master","fk_stl_no='$stlno'  AND comp_type='$type' ",$link);	
		$total_charge_due = $charge_due_qry[0]['amount'];	
		switch($type){
				
			case 2:
				$total_charges=$dam[0]["total_charges"];
			  	$charges_collected=$dam[0]["charges_collected"];
			  	$balance_charges=$dam[0]["balance_charges"];
			  	
				if($last_due){
					$due=$cam->make_roundoff($last_due[0]["fee_amount"]);
					$pay_date_from=$this->getDateSum($last_due[0]["due_month"],1);
				}						
				else{					
					$due=$cam->make_roundoff($total_charges);	
					$pay_date_from=$dam_date;
				}
				
				$fee_apply=$this->getRepaymentAmount($stlno,2,1,$pay_date_from,$today_date);
				$due=$cam->make_roundoff($due-$fee_apply);
			  		
				break;
			case 1:
			
				if($last_due){				
					$cash_collateral_required=$last_due[0]["margin_amount"];
					$pay_date_from=	$this->getDateSum($last_due[0]["due_month"],1);	
				}
				else{					
					$cash_collateral_required=$dam[0]["cash_collateral_required"];
					$pay_date_from=$dam_date;					
				}	
				
				$collateral_apply=$this->getRepaymentAmount($stlno,1,1,$pay_date_from,$today_date);
			  	
			  	$due=$cam->make_roundoff($cash_collateral_required-$collateral_apply);
			  	break;
			case 3:	
				
				if($last_due){
				
					$total_inst_due=$last_due[0]["interest_os"];
					$pay_date_from=	$this->getDateSum($last_due[0]["due_month"],1);
				}else{
					$pay_date_from=$dam_date;
				}	
				$int_apply=$this->getRepaymentAmount($stlno,3,1,$pay_date_from,$today_date);				
				
			  	$due=$cam->make_roundoff($total_inst_due-$int_apply);
			  	break;  	
			case 4:	
				
				if($last_due){
					$total_penal_interest_amount=$last_due[0]["penal_interest_os"];
					$pay_date_from=	$this->getDateSum($last_due[0]["due_month"],1);
				}
				else{
					$pay_date_from=$dam_date;
				}
				
				$penal_apply=$this->getRepaymentAmount($stlno,4,1,$pay_date_from,$today_date);
			  	$due=$cam->make_roundoff($total_penal_interest_amount-$penal_apply);
			  	break;   	
			case 5:
			
				
				if($last_due){
					$pay_date_from=$this->getDateSum($last_due[0]["due_month"],1);
					$final_loan_amount=$last_due[0]["principal_amount"];
				}
				else{
					$cash_collateral_required=$dam[0]["cash_collateral_required"];
					$pay_date_from=$dam[0]["dam_date"];						
					$final_loan_amount=$dam[0]["final_loan_amount"];
					$final_loan_amount=$final_loan_amount-$cash_collateral_required;
					
				}
				$principal_apply=$this->getRepaymentAmount($stlno,5,1,$pay_date_from,$today_date);
				$due=$cam->make_roundoff($final_loan_amount-$principal_apply);
				
			  	
			  	break;  
			case 6:	
				if($last_due){
					$margin=$last_due[0]["margin_six"];
					$pay_date_from=$this->getDateSum($last_due[0]["due_month"],1);
				}
				else{
					
					$margin_paid_to=$dam[0]["margin_paid_to"];
					if($margin_paid_to=='NAFA'){
						
						$margin_money=$dam[0]["margin_money"];
						//$final_loan_amount = $dam[0]["final_loan_amount"];
						$margin=$cam->make_roundoff($margin_money);				
						$pay_date_from=$dam[0]["dam_date"];
					}
					
				}						
				
				$margin_apply=$this->getRepaymentAmount($stlno,6,1,$pay_date_from,$today_date);
			  	$due=$cam->make_roundoff($margin-$margin_apply);
			  	break;	
			  	
			  	case 7:
				$pay_date_from=$dam_date;			
				$charges_apply=$this->getRepaymentAmount($stlno,$type,1,$pay_date_from,$today_date);				
				//echo "==".$charges_apply;
				
				$due=$cam->make_roundoff($total_charge_due-$charges_apply);
			  	break;  
			case 8:
				$pay_date_from=$dam_date;			
				$charges_apply=$this->getRepaymentAmount($stlno,$type,1,$pay_date_from,$today_date);				
				//echo "==".$charges_apply;
				
				$due=$cam->make_roundoff($total_charge_due-$charges_apply);
			  	break;  
			case 9:
				$pay_date_from=$dam_date;			
				$charges_apply=$this->getRepaymentAmount($stlno,$type,1,$pay_date_from,$today_date);				
				//echo "==".$charges_apply;
				
				$due=$cam->make_roundoff($total_charge_due-$charges_apply);
			  	break;  
			case 10:
				$pay_date_from=$dam_date;			
				$charges_apply=$this->getRepaymentAmount($stlno,$type,1,$pay_date_from,$today_date);				
				//echo "==".$charges_apply;
				
				$due=$cam->make_roundoff($total_charge_due-$charges_apply);
			  	break;  
			  		
			default:
				break;
				
			
		}
		return $due;
		
	}
	
	function getDealerAvailableLimit($dealer_code){
		
	}
	
	function getMarginDue($stlno){
		$dam=$this->select("*","df_dam","short_term_line='$stlno'");
		$total_charges=$dam[0]["total_charges"];
	}
	
	function getOneDayInterest($principal,$roi){
		return $principal*($roi/100)*1/365;
		
	}
	
	function getSwitchNo($repayment){
		$SwitchNo=strlen($repayment);
		if($SwitchNo>0)
			return 'y';
		else
			return 'n';	
	}
	/*
	function getRetroROI($stlno){
				
		$roi=$this->select_join("a.rate_of_interest","df_dam a ","LEFT JOIN nafa_df_roi_master b ON a.rate_of_interest=b.rate_of_interest ","a.short_term_line='$stlno' AND roi_retro=1 LIMIT 1");
		if($roi){
			
			$roi_3=$this->select("*","nafa_df_loan_roi","fk_stl_no='$stlno' ORDER BY installment_date DESC LIMIT 1");
			return $roi_4=$roi_3[0]["installment_rate"];
		}
		
	}
	*/
	function getRetroROI($stlno,$ced){
				
		$roi=$this->select_join("a.rate_of_interest","df_dam a ","LEFT JOIN nafa_df_roi_master b ON a.rate_of_interest=b.rate_of_interest ","a.short_term_line='$stlno' AND roi_retro=1 LIMIT 1");
		if($roi){
			
			$end_date=$this->select("installment_date","nafa_df_loan_roi","fk_stl_no='$stlno'ORDER BY loan_roi_id DESC LIMIT 1");
			$end_date=$end_date[0]["installment_date"];
			if(new DateTime($ced) < new DateTime($end_date)){
				$roi_3=$this->select("*","nafa_df_loan_roi","fk_stl_no='$stlno' AND '$ced' between installment_date1 AND installment_date");
			}else{
				$roi_3=$this->select("*","nafa_df_loan_roi","fk_stl_no='$stlno' ORDER BY installment_date DESC LIMIT 1");
			}
			
			return $roi_4=$roi_3[0]["installment_rate"];
		}
		
	}
	
	function getCurrentROI($stlno,$date){
		
		$roi_3=$this->select("*","nafa_df_loan_roi","fk_stl_no='$stlno' AND '$date' between installment_date1 AND installment_date");
		return $roi_3[0]["installment_rate"];
	}
	
	function getDealerROI($stlno,$ced,$location,$loan_extansion){
		
		//echo $loan_extansion;
		//die;
		
		$guj_location=array('GUJ1','GUJ2','GUJ3','GUJ4','GUJ5','Gujarat');
		
		if(in_array($location,$guj_location)){
			
			$roi_3=$this->select("*","nafa_df_loan_roi","fk_stl_no='$stlno' ORDER BY installment_date DESC LIMIT 1");
			$roi_4=$roi_3[0]["installment_rate"];	
		
		}
		else{
			
			$roi_3=$this->select("*","nafa_df_loan_roi","fk_stl_no='$stlno' AND '$ced' between installment_date1 AND installment_date");
			$roi_4=$roi_3[0]["installment_rate"];
			
			if($roi_4==''){
			
				if($loan_extansion=='yes'){
				$roi_3=$this->select("*","nafa_df_loan_roi","fk_stl_no='$stlno' ORDER BY installment_date DESC LIMIT 1");
				$roi_4=$roi_3[0]["installment_rate"];
				//$roi_4='16.5';
			}
			
			}
		}	
		
		if(!in_array($location,$guj_location)){
			$roi=$this->getRetroROI($stlno,$ced);
			if($roi)
				return $roi_4=$roi;
		}		
		
		return $roi_4;	
		
	}
	
	function getDealerDiscount($stlno,$ced,$location,$loan_extansion){
		
		$discount=$this->select("*","nafa_df_loan_discount","fk_stl_no='$stlno' AND '$ced' between discount_start_date AND discount_end_date");
		$discount_rate=$discount[0]["discount_rate"];
		
		return $discount_rate;
	}
	
	
	function getRepaymentAmount($stlno,$type,$total_yn=FALSE,$date_from=FALSE,$date_to=FALSE){
		
		if($total_yn){
			$field="SUM(applied_receipt_amount) as applied_receipt_amount";
		}			
		else{
			$field="applied_receipt_amount as applied_receipt_amount";
		}
		
		if($date_from){
			$condition="applied_receipt_date BETWEEN '$date_from' AND '$date_to' AND";
		}
		else{
			$condition="";
		}
		
		$repayment=$this->select($field,"nafa_df_receipt_application","fk_stl_no='$stlno' AND $condition applied_receipt_type='$type'");
		
		return $repayment[0]["applied_receipt_amount"];
		
	}
	
	function getRepaymentAmountUnTag($stlno,$type,$total_yn=FALSE,$date_from=FALSE,$date_to=FALSE){
		
		if($total_yn){
			$field="SUM(applied_receipt_amount) as applied_receipt_amount";
		}			
		else{
			$field="applied_receipt_amount as applied_receipt_amount";
		}
		
		if($date_from){
			$condition="applied_receipt_date BETWEEN '$date_from' AND '$date_to' AND";
		}
		else{
			$condition="";
		}
		
		$repayment=$this->select($field,"nafa_df_receipt_application","fk_stl_no='$stlno' AND $condition applied_receipt_type='$type' AND receipt_status!=1");
		
		return $repayment[0]["applied_receipt_amount"];
		
	}
	
	function getCurrectRepayment($stlno,$date_from,$type,$date_to=FALSE){
		
		$url=explode('/',$_SERVER['PHP_SELF']);
		$loanClosure=$url[2];
		if($loanClosure=='loan_closure2.php'){
			$closureCondition=" AND receipt_closure_status!='1'";
		}
		
		if($type==0){
			
			$repay=$this->select("SUM(applied_receipt_amount) as total_applied_receipt_amount","nafa_df_receipt_application","fk_stl_no='$stlno' AND receipt_status!='1' AND applied_receipt_type=5 $closureCondition AND applied_receipt_date='$date_from'  order by applied_receipt_date");
	
			return $repay[0]["total_applied_receipt_amount"];
		}
		if($type==1){
			$repay=$this->select("SUM(applied_receipt_amount) as total_applied_receipt_amount","nafa_df_receipt_application","fk_stl_no='$stlno' AND receipt_status!='1' AND applied_receipt_type=5 AND applied_receipt_date BETWEEN '$date_from' AND '$date_to'  order by applied_receipt_date");
	
			return $repay[0]["total_applied_receipt_amount"];
		}
		
		
	}
	
	function getRepaymentTag($stlno,$date_from,$type,$date_to=FALSE){
		
		if($type==0){
			
			$result=$this->exe("UPDATE nafa_df_receipt_application SET receipt_status='1' WHERE fk_stl_no='$stlno' AND applied_receipt_type=5 AND applied_receipt_date='$date_from'");	
			
		}
		if($type==1){
			
			$result=$this->exe("UPDATE nafa_df_receipt_application SET receipt_status='1' WHERE fk_stl_no='$stlno' AND applied_receipt_type=5 AND applied_receipt_date BETWEEN '$date_from' AND '$date_to' ");
			//$repay=$this->select("SUM(applied_receipt_amount) as total_applied_receipt_amount","nafa_df_receipt_application","fk_stl_no='$stlno' AND applied_receipt_type=5 AND applied_receipt_date BETWEEN '$date_from' AND '$date_to' order by applied_receipt_date");
	
			
		}
		
		return $result;
		
	}
	
	function getRepaymentClosureTag($stlno,$date_from,$type,$date_to=FALSE){
		
		$url=explode('/',$_SERVER['PHP_SELF']);
		$loanClosure=$url[2];
		if($loanClosure=='loan_closure2.php'){
			
			if($type==0){
			
				$result=$this->exe("UPDATE nafa_df_receipt_application SET receipt_closure_status='1' WHERE fk_stl_no='$stlno' AND applied_receipt_type=5 AND applied_receipt_date='$date_from'");	
			
			}
			if($type==1){
				
				$result=$this->exe("UPDATE nafa_df_receipt_application SET receipt_closure_status='1' WHERE fk_stl_no='$stlno' AND applied_receipt_type=5 AND applied_receipt_date BETWEEN '$date_from' AND '$date_to' ");
				//$repay=$this->select("SUM(applied_receipt_amount) as total_applied_receipt_amount","nafa_df_receipt_application","fk_stl_no='$stlno' AND applied_receipt_type=5 AND applied_receipt_date BETWEEN '$date_from' AND '$date_to' order by applied_receipt_date");
	
			
			}
		}
		
		
		
		return $result;
		
	}
	
	function getRepaymentUnTag(Array $var){
		$stlno=$var[0];		
		$result=$this->exe("UPDATE nafa_df_receipt_application SET receipt_closure_status=0 WHERE fk_stl_no='$stlno' AND applied_receipt_type=5");
		
		return $result;
	}
		
	
	function getRepaymentInterest($inst,$principal,$roi,$days){
		
		return $inst+($principal*($roi/100)*$days/365);
	}
	
	function getInterestDueAsOn($stlno,$msd,$med,$lineClosure,$deburg){
		
		//$msd=date("Y-$interest_month-01");
		//$med=date("Y-m-t",strtotime($msd));
		$cam = new cam();
		
		$condition="status not in ('Request info','Paid Off','Canceled') ";
		
		$a=$this->select("*","df_dam"," $condition AND short_term_line='$stlno' ");

		for($d = 0; $d < count($a); $d++){	

		$csd=$msd;
		$ced=$med;

		$df_dam_id=$a[$d]["df_dam_id"];
		$stlno=$a[$d]["short_term_line"];
		$final_loan_amount=$a[$d]["final_loan_amount"];
		$loandate=$a[$d]["dam_approved_date"];
		//$loanstartdate=$a[$d]["dam_approved_date"];
		$loanstartdate=$a[$d]["dam_date"];
		$fk_dealer_code=$a[$d]["fk_dealer_code"];
		$rate_of_interest=$a[$d]["rate_of_interest"];
		$product_name=$a[$d]["dam_product_name"];
		$dam_extension=$a[$d]["dam_extension"];
		$final_niipl_transfer=$a[$d]["final_niipl_transfer"];
		$cash_collateral_required=$a[$d]["cash_collateral_required"];
		
		$total_charges=$a[$d]["total_charges"];
		$charges_collected=$a[$d]["charges_collected"];
		$balance_charges=$a[$d]["balance_charges"];
		$dam_extension=$a[$d]["dam_extension"];

		//$last_due=$this->select("*","nafa_df_due_list","fk_stl_no='$stlno'  AND due_month >='2016-02-29' LIMIT 1");

		//var_dump($last_due);
		$last_due=$this->select("*","nafa_df_due_list","fk_stl_no='$stlno' ORDER by due_month DESC LIMIT 1");


		$fbl_product_name=array('FBL','FBL-Normal','FBL-Thin Wall','FBL-CMT','PRAGATI','SAHAJ','SAHAJ CMT','BL','FBL-CF','FBL-KISAN SAMRUDDHI');
		$df_product_name=array('REGULAR');
		$guj_location=array('GUJ1','GUJ2','GUJ3','GUJ4','GUJ5','GUJ6','GUJ7','Gujarat');


		$dm=$this->select("dealer_location","dealer_info_master","dealer_code='$fk_dealer_code'");
		$dealer_location=$dm[0]["dealer_location"];


		$mroi=$this->select("roi_retro","nafa_df_roi_master","rate_of_interest='$rate_of_interest'");
		$roi_retro=$mroi[0]["roi_retro"];

		//if(!empty($last_due[0]["principal_amount"])){
		if($last_due){
			
			$principal_amt=$last_due[0]["principal_amount"];
			$loanstartdate=$this->getDateSum($last_due[0]["due_month"],1);
			$collateral=$last_due[0]["margin_amount"];
			if($deburg)
				echo "<h2>ss($collateral)</h2>";
				
			$margin=$last_due[0]["margin_six"];
			$fee=$last_due[0]["fee_amount"];
			$interest_os=$last_due[0]["interest_os"];
			$interest_amount=$last_due[0]["interest_amount"];
		}
		else{
			
			$principal_amt=$final_loan_amount-$cash_collateral_required;
			$collateral=$cash_collateral_required;
			$margin=$final_niipl_transfer-$principal_amt;
			$fee=$total_charges;
			$interest_os='0';
			$interest_amount='0';
		}

		//charges
		$deferral_charges=$this->getLoanCharges($stlno,7);
		$cheque_return_charges=$this->getLoanCharges($stlno,8);
		$stamp_duty_charges=$this->getLoanCharges($stlno,9);
		$other_charges=$this->getLoanCharges($stlno,10);

		$collateral_apply=$this->getRepaymentAmount($stlno,1,1,$loanstartdate,$med);
		$margin_apply=$this->getRepaymentAmount($stlno,6,1,$loanstartdate,$med);
		$fee_apply=$this->getRepaymentAmount($stlno,2,1,$loanstartdate,$med);
		if($deburg)
			echo "<h1>$collateral - $collateral_apply</h1>";
		if($deburg)	
			echo "<h1>$collateral</h1>";
		
		//$principal_amt=$principal_amt-$collateral_apply;
		
			
		$collateral=$collateral-$collateral_apply;
		$margin=$margin-$margin_apply;
		$fee=$fee-$fee_apply;
		$principal_amt=$principal_amt;
		if($deburg)
			echo $principal_amt."--".$loanstartdate."/".$ced."<br/>";

		$loanMonth=date('Y-M',strtotime($loandate));
		$instMonth=date('Y-M',strtotime($med));

		$csd=$loanstartdate;

		$counter='0';
		$interest1='0';
		$switch_case_no='';

		//penal interest
		//$df_due=$this->select("SUM(interest_amount) as total_interest","nafa_df_due_list","fk_stl_no='$stlno' AND due_month BETWEEN '$msd' AND '$med'");
		//$df_due=$this->select("SUM(interest_amount) as total_interest","nafa_df_due_list","fk_stl_no='$stlno' ");
		
		$total_interest=$interest_os;
		

		//$df_applied=$this->select("SUM(applied_receipt_amount) as total_interest_paid","nafa_df_receipt_application","fk_stl_no='$stlno' AND applied_receipt_type='3' AND applied_receipt_date BETWEEN '$msd' AND '$med'");
		if(empty($lineClosure)){
			
		//$df_applied=$this->select("SUM(applied_receipt_amount) as total_interest_paid","nafa_df_receipt_application","fk_stl_no='$stlno' AND applied_receipt_type='3' ");

		//$total_interest=$df_due[0]["total_interest"];
		//$total_interest_paid=$df_applied[0]["total_interest_paid"];
		
		$total_interest_paid=$this->getRepaymentAmount($stlno,3,1,$msd,$med);

		$total_interest_os=$total_interest-$total_interest_paid;
		
		if($total_interest_os>$interest_amount){
			//echo "ppp$lineClosure";
			
			$balance=$total_interest_os-$interest_amount;
			
			$penal=$cam->make_roundoff_two($balance*2/100);
			if($deburg)
				echo "Penal interest--".$penal."<br/>";

			$penal=$cam->make_roundoff($penal);

			//penal interest
			
		}
		
		
		
		}
		
		if(in_array($product_name,$this->DFExtraMaster(1,0))){
			
			if($product_name=='BL'){
				$product_name='BL';
			}
			elseif($product_name=='FBL-CF'){
				$product_name='FBL-CF';
			}	
			elseif($product_name=='FBL-KISAN SAMRUDDHI'){
				$product_name='FBL-KISAN SAMRUDDHI';
			}	
			else{
				$product_name='FBL';
			}
	
	
			if($roi_retro){		
				include "inc_mmm_this.php";
			}
			else{
							
			//working fine for not same day repayment
			$roi_end=$this->select("if(installment_date >'$med',installment_date1,installment_date) as installment_date,installment_rate,null as repayment","nafa_df_loan_roi","fk_stl_no='$stlno' AND installment_date between  '$csd' AND '$ced' OR installment_date1 between  '$csd' ANd '$ced' AND fk_stl_no='$stlno' union select applied_receipt_date,null as installment_rate, applied_receipt_amount as repayment from nafa_df_receipt_application where fk_stl_no='$stlno' AND applied_receipt_type=5 AND applied_receipt_date between '$csd' AND '$ced' order by installment_date ");
		
		
			
	
			//$this->postDueMaster($fk_dealer_code,$product_name,$df_dam_id,$stlno,$msd,$med,$med,'0','0','0',$fee,$penal,$margin);
			//$due_id=mysql_insert_id();	

			//---insert into due table	
		
		//1 for
		for($i=0;$i<=count($roi_end);$i++){
			
			$ced=$roi_end[$i]["installment_date"];			
			$roi_end[$i]["repayment"];
			if($deburg)
				echo "[ start-date $csd------- end date $ced ----row $i<br/>";
			
			if(new DateTime($csd)== new DateTime($ced)){	
			if($deburg)	
				echo "equal<br/>";				
				$roi_4=$this->getDealerROI($stlno,$ced,$dealer_location,$dam_extension);
				$days_1=$this->getDateDifference($csd,$ced,'days')+1;	
				$repay=$this->getCurrectRepayment($stlno,$csd);
				$this->getRepaymentClosureTag($stlno,$csd);
				$re_amt_1=$repay;
				if($deburg)
					echo "($roi_4)";	
				
				if($repay){
					if($deburg)
						echo "($re_amt_1)";
					$principal_amt=$principal_amt-$re_amt_1;
				}	
				
				$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);	
				if($deburg)			
					echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";				
							
				$csd=$this->getDateSum($ced,1);
				
			}
			if(new DateTime($csd) < new DateTime($ced) && $ced!=''){
				if($deburg)
					echo "csd less <br/>";				
				$repay=$this->getCurrectRepayment($stlno,$ced);
				$this->getRepaymentClosureTag($stlno,$ced);
				$re_amt_1=$repay;
				
				if($repay){
					$ced=$this->getDateMinus($ced,1);				
				}				
				
				$roi_4=$this->getDealerROI($stlno,$ced,$dealer_location,$dam_extension);
				
				$days_1=$this->getDateDifference($csd,$ced,'days')+1;
				
				$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
				if($deburg)
					echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";
				if($repay){
					if($deburg)
						echo "($re_amt_1)";
					$principal_amt=$principal_amt-$re_amt_1;
				}
				$csd=$this->getDateSum($ced,1);				
				
			}
			if($ced==''){
				if($deburg)
					echo "blank <br/>";	
				if($csd<=$med){
					$ced=$med;
				if($deburg)	
					echo $csd;
				$roi_4=$this->getDealerROI($stlno,$ced,$dealer_location,$dam_extension);

				$days_1=$this->getDateDifference($csd,$ced,'days')+1;
				
				$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
				if($deburg)
					echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";
				
				$csd=$this->getDateSum($ced,1);
				}
			}

		}
	
	
	}//else
		$interest=$cam->make_roundoff($interest1);
		$principal_amt=$cam->make_roundoff($principal_amt);
		
		$interest_os=$cam->make_roundoff($this->getInterestOs($stlno,$interest,$msd,$med,3));
		$penal_os=$cam->make_roundoff($this->getInterestOs($stlno,$penal,$msd,$med,4));
		
		//$result=$this->putDueMaster($due_id,$interest,$interest_os,$penal_os,$principal_amt,$collateral,$margin,'',$med);
		
		
	
	}

		if(in_array($product_name,$this->DFExtraMaster(2,0))){
		
		if($deburg)
			echo "--RE---<br/>"	;

			if($loanMonth==$instMonth){
				
				if($deburg)
					echo "same m <br/>";
				$roi_end=$this->select("if(installment_date >'$med',installment_date1,installment_date) as installment_date,installment_rate,null as repayment","nafa_df_loan_roi","fk_stl_no='$stlno' AND installment_date between  '$csd' ANd '$ced' OR installment_date1 between  '$csd' ANd '$ced' AND fk_stl_no='$stlno' union select applied_receipt_date,null as installment_rate, applied_receipt_amount as repayment from nafa_df_receipt_application where fk_stl_no='$stlno' AND applied_receipt_type=5 AND applied_receipt_date between '$csd' AND '$ced' order by installment_date ");
			
			
			//$this->postDueMaster($fk_dealer_code,$product_name,$df_dam_id,$stlno,$msd,$med,$med,'0','0','0',$fee,$penal,$margin);
			//$due_id=mysql_insert_id();

			//---insert into due table		
				
				//1 for
			for($i=0;$i<=count($roi_end);$i++){			
								
					$ced=$roi_end[$i]["installment_date"];
					$repayment=$roi_end[$i]["repayment"];
					if($deburg)
						echo "[ start-date $csd------- end date $ced ----row $i<br/>";
					$repay=$this->select("sum(applied_receipt_amount) as total_applied_receipt_amount","nafa_df_receipt_application","fk_stl_no='$stlno' AND applied_receipt_type=5 AND applied_receipt_date between '$rcsd' AND '$rced' order by applied_receipt_date");
						
					$re_amt_1=$repay[0]["total_applied_receipt_amount"];
					if($principal_amt==$re_amt_1){
						
						$roi_4=$this->getDealerROI($stlno,$rced,$dealer_location,$dam_extension);
						
					}
					else{
						$roi_3=$this->select("*","nafa_df_loan_roi","fk_stl_no='$stlno' ORDER BY installment_date DESC LIMIT 1");
						$roi_4=$roi_3[0]["installment_rate"];
					}		
					if(new DateTime($csd)== new DateTime($ced)){
						if($deburg)
							echo "equal<br/>";
							
						$days_1=$this->getDateDifference($csd,$ced,'days')+1;	
						$repay=$this->getCurrectRepayment($stlno,$csd);
						$this->getRepaymentClosureTag($stlno,$csd);
						$re_amt_1=$repay;				
						
						if($repay){
							if($deburg)
								echo "($re_amt_1)";
							$principal_amt=$principal_amt-$re_amt_1;
						}	
								
						$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
						
						if($deburg)
							echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";
						
						$csd=$this->getDateSum($ced,1);
						
					}
					if(new DateTime($csd) < new DateTime($ced) && $ced!=''){
						if($deburg)
							echo "csd less <br/>";				
						$repay=$this->getCurrectRepayment($stlno,$ced);
						$this->getRepaymentClosureTag($stlno,$ced);
						$re_amt_1=$repay;
						
						if($repay){
							$ced=$this->getDateMinus($ced,1);	
							
						}				
						$days_1=$this->getDateDifference($csd,$ced,'days')+1;
						
						$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
						
						if($deburg)
							echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";
						if($repay){
							$principal_amt=$principal_amt-$re_amt_1;
						}
						$csd=$this->getDateSum($ced,1);
						
						
					}
					if($ced==''){
						if($deburg)
							echo "blank <br/>";	
						if($csd<=$med){
							$ced=$med;
						if($deburg)
							echo $csd;				
						$days_1=$this->getDateDifference($csd,$ced,'days')+1;
						
						$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
						if($deburg)
							echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";
						
						$csd=$this->getDateSum($ced,1);	
						
						}			
					}
			
			}
			
			$interest=$cam->make_roundoff($interest1);
			$principal_amt=$cam->make_roundoff($principal_amt);
			
			$interest_os=$cam->make_roundoff($this->getInterestOs($stlno,$interest,$msd,$med,3));
			$penal_os=$cam->make_roundoff($this->getInterestOs($stlno,$penal,$msd,$med,4));
			
			//$result=$this->putDueMaster($due_id,$interest,$interest_os,$penal_os,$principal_amt,$collateral,$margin,'',$med);
			
			
			/*
			if($result)
				$interest1='';
				*/
			
			}
			else
			{
				if($deburg)
					echo "other m $csd - $ced <br/>";
				$dstf=$csd;
				//$dstf="2016-02-01";
				$dst=date("Y-m-01",strtotime($dstf));
				$date = new DateTime($dst);
				$dsta = $date->add(new DateInterval('P14D'));
				$dedf=$dsta->format('Y-m-d');

				$dsds=$this->getDateSum($dedf,1);

				$deds=date("Y-m-t",strtotime($dstf));
				
				if($deburg)
				echo "other m start - $dstf end - $dedf == strat - $dsds end - $deds <br/>";
				
				if(new DateTime($ced) < new DateTime($dedf) ){					
					$ddarray1=array("0"=>array('start'=>$dstf,'end'=>$dedf) );
				}					
				else{					
					$ddarray1=array("0"=>array('start'=>$dstf,'end'=>$dedf),"1"=>array('start'=>$dsds,'end'=>$deds) );
				}
					
					
				if(in_array($dealer_location,$this->DFExtraMaster(0,'g'))){
				
			
				//$this->postDueMaster($fk_dealer_code,$product_name,$df_dam_id,$stlno,$msd,$med,$med,'0','0','0',$fee,$penal,$margin);
				//$due_id=mysql_insert_id();

				//---insert into due table		

				if($deburg)
					echo "GUJU..<br/>";	
				for($j=0;$j<count($ddarray1);$j++){
			
					$ncsd=$ddarray1[$j]["start"];
					$nced=$ddarray1[$j]["end"];
					if($deburg)
						echo "[ start-date $ncsd------- end date $nced ----row $i<br/>";
				
					if($j==0){
					//if($j==0  && new DateTime($ced) > new DateTime($ncsd) || new DateTime($ced) < new DateTime($nced) ){
						
						//$roi_4=$this->getCurrentROI($stlno,$nced);
						$roi_4=$this->getDealerROI($stlno,$nced,$dealer_location,$dam_extension);
						$days_1=$this->getDateDifference($ncsd,$nced,'days')+1;
						$repay=$this->getCurrectRepayment($stlno,$ncsd,1,$nced);
						$this->getRepaymentClosureTag($stlno,$ncsd,1,$nced);
						$re_amt_1=$repay;
						if($re_amt_1){
							$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
							
						if($deburg)
							echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";
							$principal_amt=$principal_amt-$re_amt_1;
							$ncsd=$this->getDateSum($nced,1);
						}
						else{
							
							$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
							
						if($deburg)
							echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";					
							$ncsd=$this->getDateSum($nced,1);			
						}
						
					}
					if($j==1){
					//if($j==1  && new DateTime($ced) > new DateTime($ncsd) || new DateTime($ced) < new DateTime($nced) ){
						if($deburg)
							echo "<h2>$ncsd-$j-$nced</h2>";
						//$roi_4=$this->getCurrentROI($stlno,$nced);
						$roi_4=$this->getDealerROI($stlno,$nced,$dealer_location,$dam_extension);
						$days_1=$this->getDateDifference($ncsd,$nced,'days')+1;
						$repay=$this->getCurrectRepayment($stlno,$ncsd,1,$nced);
						$this->getRepaymentClosureTag($stlno,$ncsd,1,$nced);
						$re_amt_1=$repay;
						if($re_amt_1){
							$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
							
						if($deburg)
							echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";
							$principal_amt=$principal_amt-$re_amt_1;
							$ncsd=$this->getDateSum($nced,1);
						}
						else{
							
							$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
							
						if($deburg)
							echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";					
							$ncsd=$this->getDateSum($nced,1);					
						}
						
					}  		
					
				/*
					$repayment=$this->select("*","nafa_df_receipt_application","fk_stl_no='$stlno' AND applied_receipt_type=5 AND applied_receipt_date between '$ncsd' AND '$nced'");
				
					if($repayment){
					
						$repay=$this->select("sum(applied_receipt_amount) as total_applied_receipt_amount","nafa_df_receipt_application","fk_stl_no='$stlno' AND applied_receipt_type=5 AND applied_receipt_date between '$ncsd' AND '$nced' order by applied_receipt_date");
						
						$re_amt_1=$repay[0]["total_applied_receipt_amount"];
						if($principal_amt==$re_amt_1){
							if(!$last_due){					
								$roi_4=$this->getDealerROI($stlno,$rced,$dealer_location,$dam_extension);
							} 
							else{						
								$roi_4=$this->getDealerROI($stlno,$rced,$dealer_location,$dam_extension);
							}
						}
						else{					
							$roi_4=$this->getDealerROI($stlno,$rced,$dealer_location,$dam_extension);
							
						}		
					$applied_receipt_date=$repayment[0]["applied_receipt_date"];			
					$days_1=$this->getDateDifference($ncsd,$nced,'days')+1;
					$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
					
					if($deburg)
						echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";
					if(new DateTime($applied_receipt_date) <= new DateTime($nced) ){				
						$principal_amt=$principal_amt-$re_amt_1;
					}		
				
				}
				else{
					
					if($deburg)		
						echo "principal-".$principal_amt."<br/>";
					$roi_3=$this->select("*","nafa_df_loan_roi","fk_stl_no='$stlno' ORDER BY installment_date DESC LIMIT 1");
					$roi_4=$roi_3[0]["installment_rate"];
					
					$days_1=$this->getDateDifference($ncsd,$nced,'days')+1;	

					$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
					if($deburg)
						echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";
				
				}
				*/
				
			  }	 
			   
				$interest=$cam->make_roundoff($interest1);
				$principal_amt=$cam->make_roundoff($principal_amt);

				$interest_os=$cam->make_roundoff($this->getInterestOs($stlno,$interest,$msd,$med,3));
				$penal_os=$cam->make_roundoff($this->getInterestOs($stlno,$penal,$msd,$med,4));

				//$result=$this->putDueMaster($due_id,$interest,$interest_os,$penal_os,$principal_amt,$collateral,$margin,'',$med);
				//$result=$this->exe("UPDATE `nafa_df_due_list` SET `interest_amount`='$interest',`principal_amount`='$principal_amt',`margin_amount`='',`fee_amount`='' WHERE due_id='$due_id'");
				
				//if($result)
				//$interest1='';
				
					
			
			}
				else{
						
				//$this->postDueMaster($fk_dealer_code,$product_name,$df_dam_id,$stlno,$msd,$med,$med,'0','0','0',$fee,$penal,$margin);
				//$due_id=mysql_insert_id();
				//---insert into due table	
				if($deburg)
					echo "non gu<br/>";
				for($j=0;$j<count($ddarray1);$j++){
			
					$ncsd=$ddarray1[$j]["start"];
					$nced=$ddarray1[$j]["end"];
					
					if($j==0){
						
						//$roi_4=$this->getCurrentROI($stlno,$nced);
						$roi_4=$this->getDealerROI($stlno,$nced,$dealer_location,$dam_extension);
						$days_1=$this->getDateDifference($ncsd,$nced,'days')+1;
						$repay=$this->getCurrectRepayment($stlno,$ncsd,1,$nced);
						$this->getRepaymentClosureTag($stlno,$ncsd,1,$nced);
						$re_amt_1=$repay;
						if($re_amt_1){
							$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
							
						if($deburg)
							echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";
							$principal_amt=$principal_amt-$re_amt_1;
							$ncsd=$this->getDateSum($nced,1);
						}
						else{
							
							$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
							
						if($deburg)
							echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";					
							$ncsd=$this->getDateSum($nced,1);			
						}
						
					}
					if($j==1){
						if($deburg)
							echo "<h2>$ncsd-$j-$nced</h2>";
						//$roi_4=$this->getCurrentROI($stlno,$nced);
						$roi_4=$this->getDealerROI($stlno,$nced,$dealer_location,$dam_extension);
						$days_1=$this->getDateDifference($ncsd,$nced,'days')+1;
						$repay=$this->getCurrectRepayment($stlno,$ncsd,1,$nced);
						$this->getRepaymentClosureTag($stlno,$ncsd,1,$nced);
						$re_amt_1=$repay;
						if($re_amt_1){
							$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
							
						if($deburg)
							echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";
							$principal_amt=$principal_amt-$re_amt_1;
							$ncsd=$this->getDateSum($nced,1);
						}
						else{
							
							$interest1=$this->getRepaymentInterest($interest1,$principal_amt,$roi_4,$days_1);
							
						if($deburg)
							echo $principal_amt." | ".$days_1." | ".$roi_4." | ".$interest1."<br/>]<br/>";					
							$ncsd=$this->getDateSum($nced,1);					
						}
						
					}  		
					
		  		}	
				
				$interest=$cam->make_roundoff($interest1);
				$principal_amt=$cam->make_roundoff($principal_amt);

				$interest_os=$cam->make_roundoff($this->getInterestOs($stlno,$interest,$msd,$med,3));
				$penal_os=$cam->make_roundoff($this->getInterestOs($stlno,$penal,$msd,$med,4));

				//$result=$this->putDueMaster($due_id,$interest,$interest_os,$penal_os,$principal_amt,$collateral,$margin,'',$med);
				
			}
			
		}
	if($deburg)
		echo "--RE---<br/>";
		}

	
	$interest=$cam->make_roundoff($interest1);
	$principal_amt=$cam->make_roundoff($principal_amt);
	$penal=$cam->make_roundoff($penal);
	//$interest_os=$cam->make_roundoff($this->getInterestOs($stlno,$interest,$msd,$med,3));
	if($roi_retro && !in_array($dealer_location,$this->DFExtraMaster(0,'g')))
	{
		$interest_os=$cam->make_roundoff(0);
		$penal_os=$cam->make_roundoff(0);
	}
	else{
		$interest_os=$cam->make_roundoff($this->getInterestOs($stlno,$interest,$msd,$med,3));	
		$penal_os=$cam->make_roundoff($this->getInterestOs($stlno,$penal,$msd,$med,4));
	}
	

	

	//$table.="<tr><td>$stlno</td><td>$interest</td><td>$principal_amt</td><td>$penal</td></tr>";



		}
		
		$this->getRepaymentUnTag(array($stlno));
		
		return array("fee"=>$fee,"margin"=>$margin,"interest"=>$interest,"interest_os"=>$interest_os,"penal"=>$penal,"penal_os"=>$penal_os,"principal"=>$principal_amt,"collateral"=>$collateral);
	
	}
	
	function createDFDealerReceipt($dealer_code,$stlno,$receipt_date,$percentage,$amount,$bank,$receipt_number,$receipt_type){
		
		$receipt_amount=round(($amount*$percentage/100),0);
		/*
		$receipt_exist=$this->select("df_receipt_entry_id","nafa_df_receipt_entry","fk_dealer_code='$dealer_code' AND receipt_amount='$receipt_amount' AND receipt_number='$receipt_number'");
		
		if(!$receipt_exist){
			*/
		$dam=$this->select("df_dam_id","df_dam","short_term_line='$stlno'");
		$df_dam_id=$dam[0]["df_dam_id"];
		
		$sql="INSERT INTO nafa_df_receipt_entry (`fk_dealer_code`,`fk_dam_id`,`classification`,`receipt_date`,`bank_name`,`receipt_amount`,`receipt_number`,`receipt_created_by`,`receipt_created_datetime`,`receipt_status`,`receipt_type`) VALUES('$dealer_code','$df_dam_id','Dealer','$receipt_date','$bank','$receipt_amount','$receipt_number','sys',NOW(),'UnApplied','$receipt_type')";
		$result=$this->exe($sql);
		
		//}
		return $result;
		
	}
	
	function getDiscountReceipt($stlno,$lineClosureDate,$receipt_date,$deburg,$checkReceipt=FALSE){
		
		$lineClosureDate=$this->change_to_newdate($lineClosureDate);
		$cam = new cam();
		
		$condition="status not in ('Request info','Canceled') ";
		
		$collateral=$this->select("*","nafa_df_collateral","fk_stl_no='$stlno' ");
		
		//var_dump($stlno);
		
		if($collateral){
			
			$receipt_date=$collateral[0]["collateral_received_date"];
			$a=$this->select("*","df_dam"," $condition AND short_term_line='$stlno' ");
			$df_dam_id=$a[0]["df_dam_id"];
			$fk_dealer_code=$a[0]["fk_dealer_code"];
			$loan_start_date=$a[0]["dam_date"];
			$niipl_order_no=$a[0]["niipl_order_no"];
			$order_value=$a[0]["order_value"];
			//Monika:sn. 04/25/2017 insert closure date for paid off cases----------
			$dam_closure_date=$a[0]["dam_closure_date"];
			
			//When closure date is blank then take line closure date.	
			if ($dam_closure_date='0000-00-00 00:00:00' || $dam_closure_date='0000-00-00' || $dam_closure_date=='' || $dam_closure_date==null){
				$dam_closure_date=$lineClosureDate;
			}			
			//Monika:en. 04/25/2017-----------------------
			$dealer_commission_to_be_held_per=$a[0]["dealer_commission_to_be_held_per"];
			$dealer_commission_to_be_held=$a[0]["dealer_commission_to_be_held"];
			$niipl_subvention_per=$a[0]["niipl_subvention_per"];
			$niipl_subvention=$a[0]["niipl_subvention"];
			
			if(empty($dealer_commission_to_be_held_per)){
				$dealer_commission_to_be_held_per=round(($dealer_commission_to_be_held/$order_value*100),2);
			}
			
			$discount_rate=$this->getDealerDiscount($stlno,$lineClosureDate,$location,$loan_extansion);
			
			$final_dealer_discount=$discount_rate-$dealer_commission_to_be_held_per;
			
			if(empty($niipl_subvention_per)){
				$niipl_subvention_per=round(($niipl_subvention/$order_value*100),2);	
			}
			
			$nafa_income=$niipl_subvention_per-$final_dealer_discount;
			
			//Monika: 04/25/2017 : Change date parameter dam_closure_date instead of receipt_date.
			$receipt_result=$this->createDFDealerReceipt($fk_dealer_code,$stlno,$dam_closure_date,$dealer_commission_to_be_held_per,$order_value,'YES-114',$niipl_order_no.'-Collateral',2);
			if($final_dealer_discount > 0){
				//Monika: 04/25/2017 : Change date parameter dam_closure_date instead of receipt_date.
				$receipt_result=$this->createDFDealerReceipt($fk_dealer_code,$stlno,$dam_closure_date,$final_dealer_discount,$order_value,'YES-114',$niipl_order_no.'-CN',3);
				
			}
			
			
			$dm=$this->select("dealer_office_name,nafa_dealer_code","dealer_info_master","dealer_code='$fk_dealer_code'");
		
			$dealer_office_name=$dm[0]["dealer_office_name"];
			$nafa_dealer_code=$dm[0]["nafa_dealer_code"];
			
			$df_receipt=$this->select("*","nafa_df_receipt_entry","fk_dam_id='$df_dam_id' AND receipt_type in('2','3')");
				for($r = 0; $r < count($df_receipt); $r++){
					
					$fk_dealer_code=$df_receipt[$r]["fk_dealer_code"];
					$receipt_no=$df_receipt[$r]["receipt_number"];				
					$receipt_amount=$df_receipt[$r]["receipt_amount"];
					$receipt_type=$df_receipt[$r]["receipt_type"];
					
					if($receipt_type==2){
						$description=$receipt_no.' - Credit Note';
					}
					if($receipt_type==3){
						$description=$receipt_no.' - Balance of Advance Interest';
					}
					
					//Monika: 04/25/2017 : Change date parameter dam_closure_date instead of receipt_date.
					$this->DFCreateSubventionEntry($nafa_dealer_code,$dam_closure_date,'','','REC',$receipt_no,$description,'0',$receipt_amount,'2');
					
				}
			
		}
		else{
			$receipt_result=0;
		}
		
		return $receipt_result;
		die;
		/*echo "<script type='text/javascript'>
		(function(){
		var ss= 'no';
		if(getStatus(ss)){
		alert('Status return true');   
		}else{
		alert('Status return false'); 
		}
		function getStatus(ask){
		if(ask=='yes')
		{
		return true;     
		}
		else
		{
		return false;
		}
		}
		})();
		</script>";
		*/
	}	
	
	function DFCreateSubventionEntry($dealer_code,$dealer_date,$reference_no,$dealer_product,$tran_type,$receipt_no,$dealer_description,$debit,$credit,$stmt_status){
				
		$sql="INSERT INTO `tmp_dealer_statement`(`tmp_customer_code`,`tmp_dealer_date`, `tmp_reference_no`, `tmp_dealer_product`, `tmp_tran_type`, `tmp_receipt_no`, `tmp_dealer_description`, `tmp_debit`, `tmp_credit`,`tmp_stmt_status`) VALUES ('$dealer_code','$dealer_date','$reference_no','$dealer_product','$tran_type','$receipt_no','$dealer_description','$debit','$credit',$stmt_status)";
		
		$this->exe($sql);
		
	}
	//Harsha Start-17-4-2017
		function DFCreateSubventionEntryChange($dealer_code,$dealer_office_name,$dealer_date,$reference_no,$dealer_product,$tran_type,$receipt_no,$dealer_description,$debit,$credit,$stmt_status){
		
		$username=$_SESSION["asset_admin_username"];
				
		$sql="INSERT INTO `dealer_statement`(`fk_dealer_id`, `dealer_name`, `dealer_date`, `reference_no`, `dealer_product`, `tran_type`, `receipt_no`, `dealer_description`, `debit`, `credit`, `balance`,`created_user`,`created_date`) VALUES ('$dealer_code','$dealer_office_name','$dealer_date','$reference_no','$dealer_product','$tran_type','$receipt_no','$dealer_description','$debit','$credit','$balance','$username',NOW())";
		
		 $this->exe($sql);
		 
		 $sql_history="INSERT INTO `history_CrDr_entries`(`fk_dealer_id`, `dealer_name`, `dealer_date`, `reference_no`, `dealer_product`, `tran_type`, `receipt_no`, `dealer_description`, `debit`, `credit`, `balance`,`created_user`,`created_date`) VALUES ('$dealer_code','$dealer_office_name','$dealer_date','$reference_no','$dealer_product','$tran_type','$receipt_no','$dealer_description','$debit','$credit','$balance','$username',NOW())";
		
		 $this->exe($sql_history);
		
	}
	
	function DFSubvention($stlno,$collateral_received_date){
		
		$dam=$this->select_join("df_dam_id,short_term_line,fk_dealer_code,dam_date,niipl_order_no,amount_to_be_recovered_niipl,status,dam_closure_date,dealer_office_name","df_dam a","LEFT JOIN dealer_info_master b ON a.fk_dealer_code=b.dealer_code","short_term_line='$stlno'");
				
		$df_dam_id=$dam[0]["df_dam_id"];
		$short_term_line=$dam[0]["short_term_line"];
		$fk_dealer_code=$dam[0]["fk_dealer_code"];
		$dealer_office_name=$dam[0]["dealer_office_name"];
		$dam_product_name=$dam[0]["dam_product_name"];
		$product_name=array('FBL-Normal','FBL-Thin Wall','FBL-CMT');
		if(in_array($dam_product_name, $product_name)){
			$dealer_product='FBL';
		}elseif($dam_product_name=='FBL-CF'){
			$dealer_product='FBL-CF';
		}elseif($dam_product_name=='FBL-KISAN SAMRUDDHI'){
			$dealer_product='FBL-KS';
		}
		
		$dam_date=$dam[0]["dam_date"];
		$status=$dam[0]["status"];
		$reference_no=$dam[0]["niipl_order_no"];
		$dam_closure_date=$this->change_to_newdate($dam[0]["dam_closure_date"]);
		$amount_to_be_recovered_niipl=$dam[0]["amount_to_be_recovered_niipl"];
		//$=$dam[0][""];
		
		$dm=$this->select("dealer_office_name,nafa_dealer_code","dealer_info_master","dealer_code='$fk_dealer_code'");
		
		$dealer_office_name=$dm[0]["dealer_office_name"];
		$nafa_dealer_code=$dm[0]["nafa_dealer_code"];
		
		if($status=='Paid Off'){
		//if($stmt){
			$this->DFCreateSubventionEntryChange($fk_dealer_code,$dealer_office_name,$collateral_received_date,$reference_no,$dealer_product,$tran_type,$receipt_no,'Advance Interest & Collateral',$amount_to_be_recovered_niipl,'0','1');
			
			$this->DFCreateSubventionEntryChange($fk_dealer_code,$dealer_office_name,$collateral_received_date,$reference_no,$dealer_product,$tran_type,$receipt_no,'Received from NIIPL','0',$amount_to_be_recovered_niipl,'1');
			
			//receipt creation based on loan closure date
			$dis=$this->getDiscountReceipt($short_term_line,$dam_closure_date,$collateral_received_date,0);
			/*
			if($dis){
				
				$df_receipt=$this->select("*","nafa_df_receipt_entry","fk_dam_id='$df_dam_id' AND receipt_type in('2','3')");
				for($r = 0; $r < count($df_receipt); $r++){
					
					$fk_dealer_code=$df_receipt[$r]["fk_dealer_code"];
					$receipt_no=$df_receipt[$r]["receipt_number"];				
					$receipt_amount=$df_receipt[$r]["receipt_amount"];
					$receipt_type=$df_receipt[$r]["receipt_type"];
					
					if($receipt_type==2){
						$description=$receipt_no.' - Credit Note';
					}
					if($receipt_type==3){
						$description=$receipt_no.' - Balance of Advance Interest';
					}
					
					$this->DFCreateSubventionEntry($nafa_dealer_code,$collateral_received_date,'','','REC',$receipt_no,$description,'0',$receipt_amount);
					
				}
				
				//$df_receipt=$this->select("*","nafa_df_receipt_entry","fk_dam_id='$df_dam_id' AND receipt_type=3");
				
			}
			*/
			$this->exe("UPDATE `nafa_df_collateral` SET `collateral_status`='1' WHERE fk_stl_no='$short_term_line' ");
			
		}
		else{
			$this->DFCreateSubventionEntryChange($fk_dealer_code,$dealer_office_name,$collateral_received_date,$reference_no,$dealer_product,$tran_type,$receipt_no,'Advance Interest & Collateral',$amount_to_be_recovered_niipl,'0','1');
			
			$this->DFCreateSubventionEntryChange($fk_dealer_code,$dealer_office_name,$collateral_received_date,$reference_no,$dealer_product,$tran_type,$receipt_no,'Received from NIIPL','0',$amount_to_be_recovered_niipl,'1');
			
			$this->exe("UPDATE `nafa_df_collateral` SET `collateral_status`='1' WHERE fk_stl_no='$short_term_line' ");
			
		}
		
	} //Harsha End-17-4-2017
	
		
	function getBalanceReceiptAmt($receipt_no){		
		
		$r=$this->select("receipt_amount","nafa_df_receipt_entry ","df_receipt_entry_id='$receipt_no'");
		$receipt_amount=$r[0]["receipt_amount"];
		$ra=$this->select("ROUND(SUM(applied_receipt_amount),2) as total_receipt_application","nafa_df_receipt_application","fk_receipt_number='$receipt_no'");
		$total_receipt_application=$ra[0]["total_receipt_application"];
		$balance_receipt_amount=$receipt_amount-$total_receipt_application;
		return $balance_receipt_amount;
		
	}
	
	function getPenalInterestDue($stlno){
			
	}
	
	function getPrincipalDue($stlno){
			
	}
	
	function makeReceiptUpdate($dealer_code,$receipt_number){
		
		$rq=$this->select("receipt_amount","nafa_df_receipt_entry","fk_dealer_code='$dealer_code' AND df_receipt_entry_id='$receipt_number'");
		
		$apprec=$this->select("IFNULL(SUM(applied_receipt_amount),0)as applied_receipt_amount1","nafa_df_receipt_application","fk_dealer_code='$dealer_code' AND fk_receipt_number='$receipt_number'");
		
		$apprec_receipt_amount = $rq[0]["receipt_amount"];
		$apprec_applied_receipt_amount = $apprec[0]["applied_receipt_amount1"];
		
		if($apprec_applied_receipt_amount <  $apprec_receipt_amount)
		{			
			$apprec_result=$this->exe("UPDATE `nafa_df_receipt_entry` SET `receipt_status`='UnApplied' WHERE fk_dealer_code='$dealer_code' AND df_receipt_entry_id='$receipt_number'");
		}
		else if($apprec_applied_receipt_amount == $apprec_receipt_amount)
		{
			$apprec_result=$this->exe("UPDATE `nafa_df_receipt_entry` SET `receipt_status`='Applied' WHERE fk_dealer_code='$dealer_code' AND df_receipt_entry_id='$receipt_number'");
		}	
		
		return $apprec_result;
	}
	
	function getDealerLimitDetail($dealer_code,$product_name,$limit){
		if($limit=='Original'){
			$ans=$this->select_join("dealer_office_name,bl_limit,base_limit,dealer_limit","dealer_info_master a","RIGHT JOIN dealer_limit_master b ON a.dealer_code=b.fk_dealer_code","a.dealer_code='$dealer_code' AND b.product_name='$product_name' ");
		}elseif($limit=='Temporary'){
			$ans=$this->select_join("dealer_office_name,bl_limit,base_limit,ps_limit","dealer_info_master a","RIGHT JOIN dealer_limit_master b ON a.dealer_code=b.fk_dealer_code","a.dealer_code='$dealer_code' AND b.product_name='$product_name' ");
		}
		
		$today_date=date("Y-m-d");
		$bl_limit=$ans[0]["bl_limit"];
		$base_limit=$ans[0]["base_limit"];
		
		if($limit=='Original'){
			$dealer_limit=$ans[0]["dealer_limit"];
			$sanction_limit=$bl_limit+$base_limit+$dealer_limit;

		}/* elseif($limit=='Temporary'){
			$ps_limit=$ans[0]["ps_limit"];
			$sanction_limit=$bl_limit+$base_limit+$ps_limit;
		} */

		if(in_array($product_name,array('SAHAJ','PRAGATI','SAHAJ CMT','FBL','FBL Normal','FBL-Normal','FBL-Thin Wall','FBL-CMT'))){
			$pcondition="in('SAHAJ','PRAGATI','SAHAJ CMT','FBL','FBL-Normal','FBL-Thin Wall','FBL-CMT')";
		}
		else{
			$pcondition="in('$product_name')";
		}

		if($limit=='Original'){
			$status_condition="fk_dealer_code='$dealer_code' AND limit_status='$limit' AND dam_product_name $pcondition AND status not in ('Request info','Paid Off','Canceled')";

		}elseif($limit=='Temporary'){
			$status_condition="fk_dealer_code='$dealer_code' AND limit_status='$limit' AND dam_product_name $pcondition AND status not in ('Request info','Canceled')";			
		}
		
		$a=$this->select("*","df_dam","$status_condition"); 
		// echo($status_condition."$status_condition");exit;
		for($i=0;$i<=count($a);$i++){

			$stlno=$a[$i]["short_term_line"];
			$dam_date=$a[$i]["dam_date"];

			$last_due=$this->select("principal_amount,margin_amount,due_month","nafa_df_due_list","fk_stl_no='$stlno' ORDER by due_month DESC LIMIT 1");

			if($last_due && $limit=='Original' ){
				$principal_amount+=$last_due[0]["principal_amount"];	
				$collateral_amount+=$last_due[0]["margin_amount"];	
				$due_month=$last_due[0]["due_month"];
				
				$receipt_app_date=$this->getDateSum($due_month,1);
				$pri_apply=$this->getRepaymentAmount($stlno,5,1,$receipt_app_date,$today_date);
				$coll_apply=$this->getRepaymentAmount($stlno,1,1,$receipt_app_date,$today_date);
				
				$total_received_pri+=$pri_apply;
				$total_received_coll+=$coll_apply;
				
			}else{
				$final_loan_amount=$a[$i]["final_loan_amount"];	
				$cash_collateral_required=$a[$i]["cash_collateral_required"];	
				$principal_amount+=$final_loan_amount;
				$receipt_app_date=$this->getDateSum($dam_date,0);	
				
				$pri_apply=$this->getRepaymentAmount($stlno,5,1,$receipt_app_date,$today_date);
				$coll_apply=$this->getRepaymentAmount($stlno,1,1,$receipt_app_date,$today_date);
				$total_received_pri+=$pri_apply;
				$total_received_coll+=$coll_apply;
			}	
			
		}
		$principal_amount=$principal_amount+$collateral_amount;
		if($limit=='Original'){
			$blocked_limit=($principal_amount)-($total_received_pri+$total_received_coll);
		}else if($limit=='Temporary'){
			$blocked_limit=($principal_amount)-($total_received_pri+$total_received_coll);
			$sanction_limit=$blocked_limit;
		}
				
		$available_limit=$sanction_limit-$blocked_limit;
		return array('sanction_limit'=>$sanction_limit,'blocked_limit'=>$blocked_limit,'available_limit'=>$available_limit);
	}
	
	function getDealerLimitDetails($dealer_code,$product_name,$limit){
		if($limit=='Original'){
			$ans=$this->select_join("dealer_office_name,bl_limit,base_limit,dealer_limit","dealer_info_master a","RIGHT JOIN dealer_limit_master b ON a.dealer_code=b.fk_dealer_code","a.dealer_code='$dealer_code' AND b.product_name='$product_name' ");
		}elseif($limit=='Temporary'){
			$ans=$this->select_join("dealer_office_name,bl_limit,base_limit,ps_limit","dealer_info_master a","RIGHT JOIN dealer_limit_master b ON a.dealer_code=b.fk_dealer_code","a.dealer_code='$dealer_code' AND b.product_name='$product_name' ");
		}
		
		$today_date=date("Y-m-d");
		$bl_limit=$ans[0]["bl_limit"];
		$base_limit=$ans[0]["base_limit"];
		
		if($limit=='Original'){
			$dealer_limit=$ans[0]["dealer_limit"];
			$sanction_limit=$bl_limit+$base_limit+$dealer_limit;

		}elseif($limit=='Temporary'){
			$ps_limit=$ans[0]["ps_limit"];
			$sanction_limit=$bl_limit+$base_limit+$ps_limit;
		}

		if(in_array($product_name,array('SAHAJ','PRAGATI','SAHAJ CMT','FBL','FBL Normal','FBL-Normal','FBL-Thin Wall','FBL-CMT'))){
			$pcondition="in('SAHAJ','PRAGATI','SAHAJ CMT','FBL','FBL-Normal','FBL-Thin Wall','FBL-CMT')";
		}
		else{
			$pcondition="in('$product_name')";
		}

		if($limit=='Original'){
			$status_condition="fk_dealer_code='$dealer_code' AND limit_status='$limit' AND dam_product_name $pcondition AND status not in ('Request info','Paid Off','Canceled')";

		}elseif($limit=='Temporary'){
			$status_condition="fk_dealer_code='$dealer_code' AND limit_status='$limit' AND dam_product_name $pcondition AND status not in ('Request info','Canceled')";			
		}
		
		$a=$this->select("*","df_dam","$status_condition"); 
		// echo($status_condition."$status_condition");exit;
		for($i=0;$i<=count($a);$i++){

			$stlno=$a[$i]["short_term_line"];
			$dam_date=$a[$i]["dam_date"];

			$last_due=$this->select("principal_amount,margin_amount,due_month","nafa_df_due_list","fk_stl_no='$stlno' ORDER by due_month DESC LIMIT 1");

			if($last_due && $limit=='Original' ){
				$principal_amount+=$last_due[0]["principal_amount"];	
				$collateral_amount+=$last_due[0]["margin_amount"];	
				$due_month=$last_due[0]["due_month"];
				
				$receipt_app_date=$this->getDateSum($due_month,1);
				$pri_apply=$this->getRepaymentAmount($stlno,5,1,$receipt_app_date,$today_date);
				$coll_apply=$this->getRepaymentAmount($stlno,1,1,$receipt_app_date,$today_date);
				
				$total_received_pri+=$pri_apply;
				$total_received_coll+=$coll_apply;
				
			}else{
				$final_loan_amount=$a[$i]["final_loan_amount"];	
				$cash_collateral_required=$a[$i]["cash_collateral_required"];	
				$principal_amount+=$final_loan_amount;
				$receipt_app_date=$this->getDateSum($dam_date,0);	
				
				$pri_apply=$this->getRepaymentAmount($stlno,5,1,$receipt_app_date,$today_date);
				$coll_apply=$this->getRepaymentAmount($stlno,1,1,$receipt_app_date,$today_date);
				$total_received_pri+=$pri_apply;
				$total_received_coll+=$coll_apply;
			}	
			
		}
		$principal_amount=$principal_amount+$collateral_amount;
		if($limit=='Original'){
			$blocked_limit=($principal_amount)-($total_received_pri+$total_received_coll);
		}else if($limit=='Temporary'){
			$blocked_limit=($principal_amount);
		}
				
		$available_limit=$sanction_limit-$blocked_limit;
		return array('sanction_limit'=>$sanction_limit,'blocked_limit'=>$blocked_limit,'available_limit'=>$available_limit);
	}
	
	function getInterestOs($stlno,$amount,$msd,$med,$type){
		
		if($type==3){
			
		$insOs=$this->select("*","nafa_df_due_list","fk_stl_no='$stlno' ORDER BY due_month DESC LIMIT 1,1");
		//$insOs=$this->select("interest_amount","nafa_df_due_list","fk_stl_no='$stlno' AND due_month='2016-02-29' ORDER BY due_month DESC LIMIT 1");
		
		$insApp=$this->select("SUM(applied_receipt_amount) as total_applied_receipt_amount","nafa_df_receipt_application","applied_receipt_type ='3' AND fk_stl_no='$stlno' AND applied_receipt_date BETWEEN '$msd' AND '$med'");
		if($insOs){
			$interest_os=$insOs[0]["interest_os"];	
		}
		else{
			$interest_os='0';
		}
			
		
		$total_applied_receipt_amount=$insApp[0]["total_applied_receipt_amount"];
		return $InterestOs=($amount+$interest_os)-$total_applied_receipt_amount;
		
		}
		if($type==4){
			
		$insOs=$this->select("*","nafa_df_due_list","fk_stl_no='$stlno' ORDER BY due_month DESC LIMIT 1,1");
		//$insOs=$this->select("penal_interest_amount","nafa_df_due_list","fk_stl_no='$stlno' AND due_month='2016-03-31' ORDER BY due_month DESC LIMIT 1");
		$insApp=$this->select("SUM(applied_receipt_amount) as total_applied_receipt_amount","nafa_df_receipt_application","applied_receipt_type ='4' AND fk_stl_no='$stlno' AND applied_receipt_date BETWEEN '$msd' AND '$med'");
		if($insOs){
			$penal_interest_os=$insOs[0]["penal_interest_os"];	
		}
		else{
			$penal_interest_os='0';
		}
			
			
		
		$total_applied_receipt_amount=$insApp[0]["total_applied_receipt_amount"];
		return $PenalOs=($amount+$penal_interest_os)-$total_applied_receipt_amount;
		
		}
		
		
	}
	
	//charges
	function getLoanCharges($stlno,$charge_type){
		
		$other_charges=$this->select("SUM(amount) as total_amount","nafa_dealer_charges_master","fk_stl_no='$stlno' AND comp_type='$charge_type'");
		$charges_amount=$other_charges[0]["total_amount"];
		return $charges_amount;
	}

	//function postDueMaster($dealer_code,$product_name,$id,$stlno,$msd,$med,$med,$interest,$principal,$collateral,$fee,$penal_interest,$margin,$type=FALSE){
	function postDueMaster($dealer_code,$product_name,$id,$stlno,$msd,$med,$med,$interest,$principal,$collateral,$fee,$penal_interest,$margin,$deferral_due,$cheque_return_due,$stamp_duty_due,$other_charges_due,$type=FALSE){
	//echo "(".$fee.")";
	
	if(!$type){
			
		$exist=$this->select("fk_stl_no","nafa_df_due_list","fk_dam_id='$id' AND due_month='$med'");
		if($exist){
			$penal_interest='';
		}
	}	
		$username=$_SESSION["asset_admin_username"];
		return $this->exe("INSERT IGNORE INTO `nafa_df_due_list`(`fk_dealer_code`,`fk_product_name`,`fk_dam_id`, `fk_stl_no`, `due_start_date`, `due_end_date`, `due_month`, `interest_amount`, `principal_amount`,`margin_amount`,`fee_amount`,`penal_interest_amount`,`margin_six`,`deferral_charge`, `cheque_return_charge`, `stamp_duty_charge`,`other_charge`,`due_type`,`calculated_by`) VALUES ('$dealer_code','$product_name','$id','$stlno','$msd','$med','$med','$interest','$principal','$collateral','$fee','$penal_interest','$margin','$deferral_due', '$cheque_return_due','$stamp_duty_due','$other_charges_due','$type','$username')");
		
	}
	
	function putDueMaster($id,$interest,$interest_os,$penal_interest_os,$principal,$collateral,$margin,$fee,$med,$deferral_due,$cheque_return_due,$stamp_duty_due,$other_charges_due){
		$cam = new cam();
		$due=$this->select("fk_dam_id","nafa_df_due_list","due_id='$id'");
		$fk_dam_id=$due[0]["fk_dam_id"];
		$exist=$this->select("fk_stl_no","nafa_df_due_list","fk_dam_id='$fk_dam_id' AND due_month='$med' AND principal_amount !='0'");
		//echo "fk_dam_id='$fk_dam_id' AND due_month='$med' AND principal_amount !='0'";
		
		//echo "( $principal )";
		//die;
		
		if($exist){
			//$principal='0';
			$collateral='0';
			$fee='0';
		}
		//echo "( $principal )";
		$principal=$cam->make_roundoff($principal);
		//echo "<h2>$interest_os</h2><br/>";
		return $this->exe("UPDATE `nafa_df_due_list` SET `interest_amount`='$interest',`interest_os`='$interest_os',`principal_amount`='$principal',`margin_amount`='$collateral',`penal_interest_os`='$penal_interest_os',`margin_six`='$margin',`deferral_charge`='$deferral_due', `cheque_return_charge`='$cheque_return_due', `stamp_duty_charge`='$stamp_duty_due',`other_charge`='$other_charges_due' WHERE due_id='$id'");
		
	}
	
	
	function updateDueMaster($id,$dealer_code,$product_name,$dam_id,$stlno,$msd,$med,$med,$interest,$principal,$collateral,$fee,$penal_interest,$margin,$type=FALSE){
		
		return $this->exe("UPDATE `nafa_df_due_list` SET `fk_dealer_code`='$dealer_code',`fk_product_name`='$product_name',`fk_dam_id`='$dam_id', `fk_stl_no`='$stlno', `due_start_date`='$msd', `due_end_date`='$med', `due_month`='$med', `interest_amount`='$interest', `principal_amount`='$principal',`margin_amount`='$collateral',`fee_amount`='$fee',`penal_interest_amount`='$penal_interest',`margin_six`='$margin',`due_type`='$type',`calculated_by`='' WHERE due_id='$id'");
		
	}
	
	function getBlank(){
		
	}
	function getEqual(){
		
	}
	function getLessThan(){
		
	}
	
	function bucketing_value($month_int,$amount_outstanding,$due_year_mon,$next_date_mon,$total_int_val,$total_pre_val)
	{		
		if(intval($amount_outstanding) < intval($total_int_val)) 
		{
			$abc = $amount_outstanding-$total_pre_val;			
			if($abc < 0){ $val ="";}else{$val =$abc;}
			$final_outstanding_amt = $val;		
		}
		if(intval($amount_outstanding) == intval($total_int_val)) 
		{				
					$final_outstanding_amt = $month_int;			
		}
		if(intval($amount_outstanding) > intval($total_int_val)) 
		{	
			$final_outstanding_amt = $month_int;
		}
		//echo "/==".$final_outstanding_amt."==/"	;	
		return $final_outstanding_amt;
	} 
	//=================
	//KS
	function KSLoanReceiptCreation($app_no){
		
		$app_details=$this->select("addusername","nafa_applicant_master","application_ref_no='$app_no'");
		$fk_dealer_code=$app_details[0]["addusername"];
		
		$da=$this->select("total_fee,disbur_amt,df_order_no,DATE(created_date) as created_date,DATE(verified_date) as verified_date","disbursment_advice","fk_app_no='$app_no'");
		
		$total_fee=$da[0]["total_fee"];	
		$disbur_amt=$da[0]["disbur_amt"];
		$df_order_no=$da[0]["df_order_no"];
		$created_date=$da[0]["created_date"];
		$verified_date=$da[0]["verified_date"];
		$percentage='100';
		
		if($df_order_no=="NA")
		{
			$receipt_no = "KS-OS-".$app_no;
			//$receipt_amt =round($disbur_amt-$total_fee);	
			$receipt_amt= $disbur_amt;		
		}else if($df_order_no!="NA")
		{
			$receipt_no = "KS-ON-".$df_order_no;		
			$receipt_amt= $disbur_amt;	
		}
		
		
		$ks_receipt_exist=$this->select("df_receipt_entry_id","nafa_df_receipt_entry","receipt_number='$receipt_no'");
		//if(!$ks_receipt_exist){			
			$receipt_result=$this->createDFDealerReceipt($fk_dealer_code,$stlno,$verified_date,$percentage,$receipt_amt,'YES-114',$receipt_no,4);			
		//}	
	}	
	//KS
	function KSMakeChargesDue($app_no){		
		$da=$this->select("total_fee,df_order_no,fk_app_no,DATE(created_date) as created_date,DATE(verified_date) as verified_date","disbursment_advice","fk_app_no='$app_no'");
		$total_fee=$da[0]["total_fee"];
		$df_order_no=$da[0]["df_order_no"];
		$created_date=$da[0]["created_date"];
		$verified_date=$da[0]["verified_date"];
		$fk_app_no=$da[0]["fk_app_no"];
		
		if($df_order_no!="NA")
		{
			$dam=$this->select("df_dam_id,fk_dealer_code,short_term_line","df_dam","niipl_order_no LIKE '%$df_order_no%'");
			$df_dam_id=$dam[0]["df_dam_id"];
			$fk_dealer_code=$dam[0]["fk_dealer_code"];
			$short_term_line=$dam[0]["short_term_line"];
			$component='Other Charges';
			$comp_type='10';	
			$value_date=date("Y-m-d");	
			
			$ks_charges_exist=$this->select("charges_id","nafa_dealer_charges_master","fk_dam_id='$df_dam_id' AND comp_type='10' AND charges_added_by='sys'");
			
			
			if(!$ks_charges_exist){		
				$this->exe("INSERT INTO `nafa_dealer_charges_master`(`fk_app_no`,`fk_dealer_code`, `fk_stl_no`, `fk_dam_id`, `component`, `comp_type`, `amount`,`value_date`, `reason`,`remark`, `charges_added_by`, `create_datetime`) VALUES ('$fk_app_no','$fk_dealer_code','$short_term_line','$df_dam_id','$component','$comp_type','$total_fee','$verified_date','','KS','sys',NOW())");	
			}	
		}	
	}	
	
}

$damObj=new damFunctions();
?>