<?php 
include "includes/header.php"; 
include "includes/Mdme-functions.php";
$mdme = getMdme_Purchase_Payment($db,'');
include_once "includes/pagepermission.php";
//check permission - START
if(!($res_modm_prm)){
	header("Location:".admin_public_url."error.php");
}
//check permission - END

if(isset($_REQUEST['supplier_id']) && !empty($_REQUEST['supplier_id']) && isset($_REQUEST['company_id']) && !empty($_REQUEST['company_id']) ){
	$supplier_id = base64_decode($_REQUEST['supplier_id']);
	$company_id = base64_decode($_REQUEST['company_id']);
	//$supplier_id = $_REQUEST['supplier_id'];
	
	$str_ed = "select *, CASE WHEN sup_payment_type=2 THEN 'GST Supplier' ELSE 'Non-GST Supplier' END As disp_payment_type from m_supplier where 1=1 and sup_id = '".$supplier_id."' ";
	$sup_det = $db->get_a_line($str_ed);
	
	
	
	
	
	
	//get payment due amount [by invoice list]		
	$get_inv_list = $db->get_a_line("select GROUP_CONCAT(p_invoice_no) as inv_list from t_purchase_entry_main where 1=1 and sup_id = '".$supplier_id."' and IsActive=1  and company_id='".$company_id."'  ");
	
	$tot_due_amt = 0;
	$split_inv_list=0;
	if(!empty($get_inv_list['inv_list'])){
		$get_tot_due_amt = $db->get_a_line(" select sum(due_amt) as tot_due_amt from t_purchase_payment where 1=1 and p_invoice_no IN(".$get_inv_list['inv_list'].") ");		
		$tot_due_amt = $get_tot_due_amt['tot_due_amt'] ;
		
		//get only due amount greater 0 service list
		$get_inv_due = $db->get_a_line(" select GROUP_CONCAT(`p_invoice_no`) as due_inv_no from t_purchase_payment where 1=1 and p_invoice_no IN(".$get_inv_list['inv_list'].") and `due_amt` <>0 ");
		
		$split_inv_list = $get_inv_due['due_inv_no'];	
		
	}
	
	
}
else{
	header("Location:".admin_public_url."error.php");
}
?> 


<div class="wrapper">
    <div class="container">
        <!-- Page-Title - START -->
        <div class="row">
            <div class="col-sm-12">   										
                <h4 class="page-title">Manage Purchase Payments</h4>
				<input type="hidden" name="disptblname" id="disptblname" value="<?php echo "purchase_payments"; ?>" />				
            </div>
        </div>
		<!-- Page-Title - END -->	
					
		<div class="row">
            <div class="col-sm-12">
                <div class="card-box">                         
                    <div class="row">
						<div class="col-md-3">
							<div class="about-info-p">
								<strong>Supplier Name</strong> <br> <p class="text-muted"><?php echo $sup_det['sup_name']; ?></p>
							</div>
						</div>
					
						<div class="col-md-3">
							<div class="about-info-p">
								<strong>Mobile</strong> <br> <p class="text-muted"><?php echo $sup_det['sup_mobile']; ?></p>
							</div>
						</div>
						
						<div class="col-md-3">
							<div class="about-info-p">
								<strong>Address</strong> <br> <p class="text-muted"><?php echo $sup_det['sup_address'].', '.$sup_det['sup_city'].', '.$sup_det['sup_state'].', '.$sup_det['sup_country']; ?></p>
							</div>
						</div>
						
						<div class="col-md-3">
							<div class="about-info-p">
								<strong>Payment Type</strong> <br> <p class="text-muted"><?php echo $sup_det['disp_payment_type']; ?></p>
							</div>
						</div>
						
					</div>
                </div>
            </div>
        </div> <!-- end row -->		
	
	
<form id="jvalidate_purchase_payment_updt" role="form" class="form-horizontal" action="#" method="post">	
<input type="hidden" name="disp_sup_id" id="disp_sup_id" value="<?php echo $supplier_id; ?>"  />
<input type="hidden" name="disp_sup_name" id="disp_sup_name" value="<?php echo $sup_det['sup_name']; ?>"  />
<input type="hidden" name="hdn_tot_due_amt" id="hdn_tot_due_amt" value="<?php echo $tot_due_amt; ?>"  />
<input type="hidden" name="hdn_split_inv_list" id="hdn_split_inv_list" value="<?php echo $split_inv_list; ?>"  />
<input type="hidden" name="disp_company_id" id="disp_company_id" value="<?php echo $company_id; ?>"  />
					
<div class="row">
	<div class="col-sm-12">	
		<div class="card-box">    
			<div class="row">	
				<div class="col-lg-12">
					<label>Total Amount Due :  </label>	
					<span style="font-size:15px;" class="label label-success"><?php echo "Rs. ".$tot_due_amt; ?></span>						
				</div>
				<div class="col-lg-12">
					<br/>
				</div> 
				
				<div class="col-lg-12">
					<div class="panel panel-border panel-info">
						<div class="panel-heading">
							<h3 class="panel-title">Payment Details</h3>
                        </div>
                        <div class="panel-body">
							<div class="col-lg-12">																	
								<label>Payment Mode : </label>
								<?php 
								$rslt_payment_mode = $db->get_rsltset("select * from status_payment_type where 1=1 and IsActive=1 and payment_type_id IN(1,2)");
								foreach($rslt_payment_mode as $rslt_S){
								?>	
									<div class="radio-info radio-inline">
										<input type="radio" id="rbtn_payment_mode_<?php echo $rslt_S['payment_type_id']; ?>" value="<?php echo $rslt_S['payment_type_id']; ?>" name="rbtn_payment_mode">
										<label for="rbtn_payment_mode_<?php echo $rslt_S['payment_type_id']; ?>"> <?php echo $rslt_S['payment_type']; ?> </label>
									</div>
								<?php	
								}
								?>									
								<br/>
							</div>
							<div class="col-lg-12">
								<label>&nbsp;</label>
							</div>
							
							<div class="col-lg-12 dv_fields" id="dv_common_fields">
							
								<div class="form-group row">
									<div class="col-lg-3">
										<label>Bank </label>
										<select id="sel_bank" name="sel_bank" class="form-control select2 jsrequired">
											<option value="">Select Bank</option>
											<?php 
											$rslt_bank_list = $db->get_rsltset("select * from m_bank_list where 1=1 and IsActive=1 ");
											foreach($rslt_bank_list as $rslt_S){
											?>
											<option value="<?php echo $rslt_S['bank_id']; ?>"><?php echo $rslt_S['bank_name']; ?></option>
											<?php	
											}
											?>
										</select>
									</div>	
									<div class="col-lg-3">
										<label >Amount </label>
										<input id="txt_given_amount" name="txt_given_amount" class="form-control jsrequired" type="text" onkeypress="return isNumber(event);" onchange="get_service_details_with_options(2);" />
									</div>									
									<div class="col-lg-3">
										<label >Deposit Date </label>
										<input id="txt_recv_date" name="txt_recv_date" class="form-control cmn_st_date jsrequired" type="text" readonly="" />
									</div>
								</div>	
								
							</div>
							
							<!-- Cash -- start -->
							<div class="col-lg-12 dv_fields" id="dv_rbtn_payment_mode_1">
								<div class="form-group row">						
									<div class="col-lg-3">
										<label >Deposit City </label>
										<input id="txt_deposit_city_forcash" name="txt_deposit_city_forcash" class="form-control jsrequired" type="text" />
									</div>
									<div class="col-lg-3">
										<label >Deposit Branch </label>
										<input id="txt_deposit_branch" name="txt_deposit_branch" class="form-control" type="text" />
									</div>						
								</div>
							</div>
							<!-- Cash -- end -->
							
							<!-- Cheque -- start -->
							<div class="col-lg-12 dv_fields" id="dv_rbtn_payment_mode_2">
								<div class="form-group row">	
									<div class="col-lg-3">
										<label >Cheque No </label>
										<input id="txt_cheque_no" name="txt_cheque_no" class="form-control jsrequired" type="text" />
									</div>		
									<div class="col-lg-3">
										<label >Bank </label>
										<input id="txt_cheque_bank" name="txt_cheque_bank" class="form-control jsrequired" type="text" />
									</div>	
									<div class="col-lg-3">
										<label >Deposit City </label>
										<input id="txt_deposit_city" name="txt_deposit_city" class="form-control jsrequired" type="text" />
									</div>
									
								</div>
							</div>
							<!-- Cheque -- end -->
															
                        </div>
                    </div>
				</div>
				
				
				<!-- cleared bank details -- start -->
				<div class="col-lg-12 dv_fields" id="dv_cleared_bank_details">
					<div class="panel panel-border panel-pink">
						<div class="panel-heading">
							<h3 class="panel-title">Payment Cleared Details</h3>
                        </div>
                        <div class="panel-body">
							<div class="form-group has-success row">
								<div class="col-lg-3">
									<label>Cleared in Bank : </label>
									<input type="checkbox" id="chk_cleared_bank" name="chk_cleared_bank" class="" />
								</div>									
							</div>	
							<div class="form-group row">
								<div class="col-lg-3">
									<label >Cleared Date : </label>
									<input id="txt_cleared_date" name="txt_cleared_date" class="form-control cmn_st_date "  type="text" />
								</div>	
							</div>	
							
							<div class="form-group row">
								<div class="col-lg-12">
									&nbsp;
								</div>	
								
								<div class="col-lg-12">								
									<span class="label label-purple">Service Details</span>
									<br/> <br/>
									<div class="form-group row">
										<div class="col-lg-2">
											<label>Invoice No </label>							
										</div>	
										<div class="col-lg-2">
											<label>Due </label>							
										</div>	
										<div class="col-lg-2">
											<label>Paying </label>							
										</div>
										<div class="col-lg-4">
											<label>Balance </label>							
										</div>
									</div>	

									
									<div id="dy_due_invoice_list">
										<!-- dynamic serv list there -->
									</div>
									
									<div class="hdn_invoice_payment_details"> </div>	
									
									
								</div>	
							</div>															
							
						</div>
						
						<div class="panel-footer">					
							<button onclick="save_payment_details();" class="btn btn-purple waves-effect waves-light pull-right" type="button">Update Payment Details</button>
							<div class="clearfix"></div>
						</div>
						
                    </div>
				</div> 			
				<!-- cleared bank details -- end -->
								
				
			</div>
		</div>
	</div>
</div>	
</form>		
			
		

<?php include "includes/footer.php";  ?> 
	</div> <!-- container -->
</div> <!-- End wrapper -->

<?php include "includes/footer_script.php";  ?> 

<!-- Date Picker related --> 
<link type="text/css" href="assets/plugins/bootstrap-datepicker/jquery-ui.min.css" rel="stylesheet" /> 
<script src="assets/plugins/bootstrap-datepicker/jquery-ui.min.js" type="text/javascript"></script>	 


<script>
$(function () {  

    $(".dv_fields").hide();
	
	check_due_amount();
	
	$('input').on('ifClicked', function (event) {
		var rbtn_id = $(this).attr('id');	       
		if(rbtn_id == "rbtn_payment_mode_1" || rbtn_id=="rbtn_payment_mode_2" || rbtn_id=="rbtn_payment_mode_3" || rbtn_id=="rbtn_payment_mode_4" || rbtn_id=="rbtn_payment_mode_8" ){
			
			$(".dv_fields").hide();					
			
			$("#dv_common_fields").show();
			$("#dv_"+rbtn_id).show();
						
			$("#dv_cleared_bank_details").show();
		}
	});	
	
	$('.cmn_st_date').datepicker({					
		dateFormat: "dd-mm-yy",				
        changeMonth: true,
        changeYear: true,
        yearRange: "-100:+20",
		autoclose: true,
		todayHighlight:true		
	});	
			
//deposit date and cleared date custom funstion - start
	$("#txt_recv_date").on('change', function(ev){
		$("#txt_cleared_date").val("");
	});		
		
	$("#txt_cleared_date").on('change', function(ev){		
		var depositdate = $("#txt_recv_date").val();
		var clear_date = $(this).val(); 
		
		if(depositdate !='' && clear_date !=''){
			var temp_depo_dt = depositdate.split("-");
			arr_depo_dt=[];
			arr_depo_dt = arr_depo_dt.concat(temp_depo_dt);
			var chk_depo_dt = arr_depo_dt[1]+'/'+arr_depo_dt[0]+'/'+arr_depo_dt[2];
			
			var temp_clear_dt = clear_date.split("-");
			arr_clear_dt=[];
			arr_clear_dt = arr_clear_dt.concat(temp_clear_dt);
			var chk_clear_dt = arr_clear_dt[1]+'/'+arr_clear_dt[0]+'/'+arr_clear_dt[2];
									
			if(chk_clear_dt >= chk_depo_dt){
				
			}
			else{
				swal("Failure!", "Clearing date must be same or greater than the Deposited date", "warning");
				$("#txt_cleared_date").val("");
			}
			
		}
	});
	
//deposit date and cleared date custom funstion - end	
	
		
get_service_details_with_options(1);		

});

function check_due_amount(){
	var due_amt = $("#hdn_tot_due_amt").val();
	if(due_amt >0){
		return true;
	}
	else{
		swal({
			title: "Due Amount is 0",
			text: "Due amount is 0, so you can't do this operations, Click ok to redirect customer service details",
			type: "warning",
			showCancelButton: false,
			confirmButtonColor: "#DD6B55",
			confirmButtonText: "OK",
			closeOnConfirm: false			
		},
		function () {
			var redirect_url = '<?php echo BASE_URL ?>stockadmin/memberservicedet_mng.php?member_id=<?php echo $_REQUEST['member_id']; ?>';
			$(location).attr('href', redirect_url);
			//window.history.back();
		}); 			
		
	}
}


function get_service_details_with_options(chk_fst){
	var inv_ids = $("#hdn_split_inv_list").val();		
	var temp_given_amt =0;
	if($("#txt_given_amount").val() != ''){
		temp_given_amt =$("#txt_given_amount").val();
		
		//Amount restriction no need change - start
		/*
		if(chk_fst == 2){
			if(temp_given_amt <= 1500){
				swal("Failure!", "Amount must greaterthan 1500", "warning");
				$("#txt_given_amount").focus();
				return false;
			}
		}
		*/
		//Amount restriction no need change - end
		
	}
				
	if(inv_ids !='' && inv_ids !='0'){		
		$.ajax({		
			url        : 'bind_html_actions.php',
			method     : 'POST',
			dataType   : 'json',
			data       : 'action=due_invoice_list_for_payment&supplier_id='+$("#disp_sup_id").val()+'&invoice_ids='+inv_ids+'&given_amount='+temp_given_amt,
			beforeSend: function() { 				
				loading();
			},
			success: function(response){
				$("#dy_due_invoice_list").html('');	
				$("#dy_due_invoice_list").html(response.rslt);
				//alert(response.rslt);
				unloading();
			}		
		});	
	}
	
}




function save_payment_details(){
	if ($('#jvalidate_purchase_payment_updt').valid()) {	
		$(".hdn_invoice_payment_details").html("");
		
		var chk_validate = check_validate();
		if(chk_validate == true){
			var m_data = new FormData();		
			var formdatas = $("#jvalidate_purchase_payment_updt").serializeArray();
			$.each( formdatas, function( key, value ) {
				 m_data.append( value.name, value.value);							 
			});
			m_data.append("action", "update_invoice_payment_details");
			
			$.ajax({
				url        : 'purchase_payment_actions.php',
				type	   : 'POST',
				dataType   : 'json',
				processData: false,
				contentType: false,
				data       : m_data,
				beforeSend : function(){ loading();	},
				success: function(response){ 
					if(response.rslt == "1"){
						swal("Success!", "Payment details update successfully", "success");	
					}				
					else{
						swal("Failure!", "Some session data are missing please try again once or contact administrator", "warning");
					}
					unloading();
				}
			});
			
			
		}		
	}
}


function check_validate(){
	var due_amt = $("#hdn_tot_due_amt").val();
	if(due_amt >0){
		var temp_given_amt =$("#txt_given_amount").val();
				
		
		if($("#chk_cleared_bank").is(':checked')){				
			if($("#txt_cleared_date").val() == ''){
				swal("Failure!", "Please select cleared date", "warning");
				$("#txt_cleared_date").after('<label class="error" for="txt_cleared_date" generated="true"><small>This field is required.</small></label>');
				return false;
			}		
		}						
		
		var chk_serv_sel=0;
		var chk_tot_pay_amt=0;
		var chkUser=document.getElementsByName('chkbx_inv_ids[]');
		for (var i = 0; i < chkUser.length; i++) {
			if(chkUser[i].checked == true){
				chk_serv_sel =1;
				var inv_id = chkUser[i].value;
				var c_due_amt = $("#txt_due_amt_"+inv_id).val();
				var c_pay_amt = $("#txt_paying_amt_"+inv_id).val();
				var c_bal_sel = $("#sel_balance_opt_"+inv_id).val();
					
										
				c_due_amt = parseFloat(c_due_amt);
				c_pay_amt = parseFloat(c_pay_amt);
					
				chk_tot_pay_amt = chk_tot_pay_amt + c_pay_amt;
					
															
				if(c_pay_amt == 'NaN'){
					swal("Failure!", "Please enter paying amount for selected service", "warning");
					$("#txt_paying_amt_"+inv_id).after('<label class="error" for="txt_paying_amt_'+inv_id+'" generated="true"><small>This field is required.</small></label>');
					return false;
				}
				else{
					if(c_pay_amt > c_due_amt){
						swal("Failure!", "Paying amount greaterthan due amount, please check and update", "warning");
						$("#txt_paying_amt_"+inv_id).after('<label class="error" for="txt_paying_amt_'+inv_id+'" generated="true"><small>Check amount</small></label>');
						return false;
					}
					else if(c_pay_amt < c_due_amt){
						if(c_bal_sel == '0'){
							swal("Failure!", "Please select balance option keep as due / discount", "warning");
							$("#sel_balance_opt_"+inv_id).after('<label class="error" for="sel_balance_opt_'+inv_id+'" generated="true"><small>This field is required.</small></label>');
							return false;
						}
					}
							
					$(".hdn_invoice_payment_details").append('<input type="hidden" name="h_sel_invoice_id[]" value="'+inv_id+'"  /> <input type="hidden" name="h_invoice_due_amout[]" value="'+c_due_amt+'" /> <input type="hidden" name="h_invoice_pay_amout[]" value="'+c_pay_amt+'" /> <input type="hidden" name="h_sel_bal_opt[]" value="'+c_bal_sel+'" /> ');											
							
				}					
			}
			else{
				var inv_id = chkUser[i].value;
				var c_pay_amt = $("#txt_paying_amt_"+inv_id).val();
				if(c_pay_amt !=''){
					c_pay_amt = parseFloat(c_pay_amt);
					if(c_pay_amt > 0){
						swal("Failure!", "Please select the service to update the payment", "warning");
						$("#chkbx_inv_"+inv_id).after('<label class="error" for="chkbx_inv_'+inv_id+'" generated="true"><small>This field is required.</small></label>');
						return false;
					}
				}
			}
		}
				
		if(chk_serv_sel == 0){
			swal("Failure!", "No service selected for a payment", "warning");
			return false;
		}
		else{
			var actual_pay_amt = $("#txt_given_amount").val();				
			if(actual_pay_amt == chk_tot_pay_amt){
				return true;	
			}
			else{
				swal("Failure!", "Actual payment not equal to total of service paying amount", "warning");
					
				return false;
			}				
		}

		
	}
	else{
		swal("Failure!", "Due amount is 0, so you can't do this operations", "warning");
		return false;
	}
	
}


</script>	

</body>
</html>
