<?php

	include 'header.php';
	include 'navbar.php';
	include 'includes/admin_API_Config.php';

	$obj = new API_Config;
	$data = array();
	$data['admin_username'] = $_SESSION['admin_username'];
	$response = json_decode($obj->call_API("API_Product_List.php", $data));
	$storeList  = json_decode($obj->call_API("API_Store_List.php", $data));
	//var_dump($store);
	error_reporting(0);

?>

	 <div class="card">
		<div class="card-body">
		  <h4 class="card-title">Member Package Purchase</h4>
		  <form id="frmMemberPackage" method="post">
			 <div class="row">
				<div class="col-md-2">
					<label>Member ID:</label>
					<input class="form-control" name="memberID" id="memberID" maxlength="9">
				</div>
				<div class="col-md-2">
					<label>Member Name:</label>
					<input class="form-control" name="memberName" id="memberName" readonly>
				</div>
				<div class="col-md-2">
					<label>Customer ID:</label>
					<input class="form-control" name="customerID" id="customerID" readonly>
				</div>
				<div class="col-md-6">
					<label>Shipping Address:</label>
					<textarea class="form-control" rows="3" name="address" id="address" readonly></textarea>
				</div>
			 </div>
			 <p>&nbsp;</p>
			 <div class="row">
					<div class="form-radio form-radio-flat col-md-2">
						<label class="form-check-label">
						  <input type="radio" class="form-check-input" name="deliveryType" value="1">
						  Shipping Method
						<i class="input-helper"></i></label>
					</div>
					<div class="form-radio form-radio-flat col-md-2">
						<label class="form-check-label">
						  <input type="radio" class="form-check-input" name="deliveryType"  value="2" checked>
						  Store Pickup
						<i class="input-helper"></i></label>
					</div>
					<div class="col-md-4" id="storeList">
						<label>Select Store:</label>
						<select class="col-md-12 js-example-basic-single" name="cmbStore" id="cmbStore" class="form-control valid">
						<?php
							foreach($storeList->eCommerceStores as $row)
							{
								echo "<option value='" . $row->id . "' price='" . $row->price . "'  pv='" . $row->pricevalue . "'>" . ucwords($row->name) . "</option>";
							}
						?>
						</select>
					</div>				
			</div>
    	    <p>&nbsp;</p>
	        <div class="row">
				<div class="col-md-4">
					<label>Select Product:</label>
					<select class="col-md-12 js-example-basic-single" name="cmbProduct" id="cmbProduct" class="form-control valid" required="" aria-invalid="false">
					<?php
						foreach($response->productList as $row)
						{
							echo "<option value='" . $row->id . "' price='" . $row->price . "'  pv='" . $row->pricevalue . "'>" . ucwords($row->name) . "</option>";
						}
					?>
                    </select>
				</div>
				<div class="col-md-2">
					<label>Product Price:</label>
					<input class="form-control" name="productPrice" id="productPrice" readonly value="<?php  echo $response->productList[0]->price;?>">
				</div>
				<div class="col-md-2">
					<label>Product PV</label>
					<input class="form-control" name="productPV" id="productPV" readonly value="<?php  echo $response->productList[0]->pricevalue;?>">
				</div>
			 </div>
			 <p>&nbsp;</p>
			 <!--div class="row">
				<div class="col-md-3">
					<label>Paid By Deposit/Cheque:</label>
					<input class="form-control" name="paidByDeposit" id="paidByDeposit" value="0">
				</div>
				<div class="col-md-3">
					<label>Paid By Cash:</label>
					<input class="form-control" name="paidByCash" id="paidByCash" value="0">
				</div>
				<div class="col-md-3">
					<label>Paid By BBT:</label>
					<input class="form-control" name="paidByBBT" id="paidByBBT" value="0">
				</div>
			  </div-->
  			 <p>&nbsp;</p>
 			 <div class="row">
				<button type="button" class="btn btn-primary" name="btnPurchase" id="btnPurchase">Purchase</button>
			 </div>
			 <div class="dot-opacity-loader" id="profileloader">
				  <span></span>
				  <span></span>
				  <span></span>
              </div>
		  </form>
		</div>
	  </div>

<?php
	include 'footer.php';
?>



   <script type="text/javascript">

    var productDetails =  <?php echo json_encode($response->productList);?>;


	 $("#memberID").on("keypress keyup blur paste change",function (event) {
	   
           $(this).val($(this).val().replace(/[^\d].+/, ""));
            if ((event.which < 48 || event.which > 57)) {
                event.preventDefault();
            }
			else
			{
				if($("#memberID").val().length==9)
				{

					  $.post("../API/API_check_refer_idV3.php",
					  {
						refer_id: $("#memberID").val(),
						//ajax : 1,

					  },

					  function(data, status){
						if(status)
						{
						  if(data.status==1)
						  {
							 $("#memberName").val(data.user_info.name + "  " + data.user_info.last_name);
							 $("#customerID").val(data.user_info.customer_id);
							 var address = data.user_info.address1 + ", " + data.user_info.address2 + ", " + data.user_info.city + " - " + data.user_info.zip_code + " "  + data.user_info.state + "."; 
							 $("#address").text(address);

						  }
						  else
						  {
							 $("#memberName").val("Invalid Member ID!");
 							 $("#memberName").val("Invalid Member ID!");
						  }

						}

						else
						  {
							alert("Cannot get a response from the server. Please try later!");
							$('#finish').attr('disabled', true);

						  }
						
						});
				   }

				
			  }
    });



	$("#cmbProduct").change(function(){

		$("#productPrice").val($(':selected', this).attr("price"));
		$("#productPV").val($(':selected', this).attr("pv"));

	});

	
	
	$("input[name='deliveryType']").click(function(){
		
		if($("input[name='deliveryType']:checked").val() ==2)
			$("#storeList").css("display","");

		else
			$("#storeList").css("display","none");



	});

	  
	 $("#btnPurchase").click(function(){

			 // validate signup form on keyup and submit
		 $("#frmMemberPackage").validate({
			  rules: {
				memberID:{
				  required: true,
				  minlength: 9,
				}/*,
				paidByDeposit:{
				  required: true,
				},
				paidByCash:{
				  required: true,
				},
				paidByBBT:{
				  required: true,
				}*/
			  },
			  messages: {
				memberID:{
				required: 'Please enter the Member ID.',
				minlength: "Please enter 9 digit valid Member ID"
		    	}/*,
				paidByDeposit:{
				  required: "Please enter the amount.",
				},
				paidByCash:{
				  required: "Please enter the amount.",
				},
				paidByBBT:{
				  required: "Please enter the amount.",
				}*/
			  },
			  errorPlacement: function(label, element) {
				label.addClass('mt-2 text-danger');
				label.insertAfter(element);
			  },
			  highlight: function(element, errorClass) {
				$(element).parent().addClass('has-danger')
				$(element).addClass('form-control-danger')
			  }

			
		  });

		  if($("#frmMemberPackage").valid())
			 $("#frmMemberPackage").submit();

	  });


	  $("#frmMemberPackage").on('submit',(function(e){
			
		    if($("#memberName").val()=="Invalid Member ID!")
				 return false;

			/*var formData = {
            'memberID'		:    $("#memberID").val(), 
			'product_id'	:    $("#cmbProduct").val(),
			'position'      :    $("#cmbPosition").val(),
			'paidByDeposit' :    $("#paidByDeposit").val(),
			'paidByCash'    :    $("#paidByCash").val(), 
		    'paidByBBT'     :    $("#paidByBBT").val() 
			};*/

			//var payment = parseFloat(formData.paidByDeposit) + parseFloat(formData.paidByCash) + parseFloat(formData.paidByBBT);

			var payment = parseFloat($("#paidByDeposit").val()) + parseFloat($("#paidByCash").val()) + parseFloat($("#paidByBBT").val());

			if(payment < parseFloat($("#productPrice").val()))
		    {
				alert("Amount paid cannot be less than purchase price!");
			 	return false;
			}
			 e.preventDefault();
			 $("#profileloader").show();
			 $("#btnPurchase").hide();

			 $.ajax({
				type        : 'POST', 
				url         : '../API/API_Package_Purchase.php', 
				data        : new FormData(this),
				dataType    : 'json', 
				encode      :  true,
				cache		: false,
				contentType : false,
				processData : false,
				})

				.done(function(data){
				  $("#profileloader").hide();
				  $("#btnPurchase").show();

				  if (data.success){
					alert(data.message);
					location.reload();
				  }

				  else{
					alert(data.message);
				  } 

				}) 
				
				.fail(function(data){
					$("#profileloader").hide();
					$("#btnPurchase").show();
					alert("Some error has occured. Please try again later!"); 
				});


		}));



</script>

