<!DOCTYPE html>
<?php
require_once('../Db/dbconfig.php');
@$userid=$_GET['userid'];

?>
<html>
<head>
<link href="../css/styles.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://kit.fontawesome.com/c17eae44a3.js" crossorigin="anonymous"></script>

<style type="text/css">
select.rou{
 border: 1px solid #ccc;
  -moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;

-moz-box-shadow: 2px 2px 3px #666;
-webkit-box-shadow: 2px 2px 3px #666;
box-shadow: 2px 2px 3px #666;
font-size: 18px;
padding: 4px 7px;
outline: 0;
-webkit-appearance: none;
}
#round{
 border: 1px solid #ccc;
 -moz-border-radius: 10px;
 -webkit-border-radius: 10px;
 border-radius: 10px;
	
 -moz-box-shadow: 2px 2px 3px #666;
 -webkit-box-shadow: 2px 2px 3px #666;
 box-shadow: 2px 2px 3px #666;
 font-size: 15px;
 padding: 4px 7px;
 outline: 0;
 -webkit-appearance: none;
}
</style>
</head>
<body>
<div class="page-header">
  <h3 class="page-title"  >
    <span class="page-title-icon bg-gradient-primary text-white mr-2">
      <i class="fas fa-cart-arrow-down fa-xs" style="color: black"></i>
    </span><b>Purchase Entry</b></h3>
</div>
 <div class="card-body" style="background-color:#F5F5DC">
 <form action="" method="post" enctype='multipart/form-data' id="purchaseForm">
<?php 
  $query="select * from purchase order by p_id desc limit 1";
  $result=mysqli_query($con,$query);
  $rowcount = mysqli_num_rows($result);
  
  if($rowcount == 0)
  {
	  $supid="CHA";
	  $invid="INV";
  }else
  {
	$row=mysqli_fetch_array($result);
	$lastid=$row['p_id'];
	$supid="CHA" .($lastid + 1);
	$invid="INV" .($lastid + 1);
  }
	  ?>
 <div class="form-group">
    <label style="width:150px;" style="size:150px;" class="r" for="l_no"><b>Vendors Code</b></label>
    <input type="text" style="width:250px;" id="l_no" class="rounded" name="l_no" placeholder="Vendors Code" required>
	<label style="width:700px;"></label>
	 <label style="width:110px;" id="round" for="no"><b>Challen Number</b></label>
    <input style="width:80px;" type="text" class="rounded" id="cha_no" name="cha_no" value="<?php echo $supid; ?>"  >
 </div>
<div class="form-group">
    <label style="width:150px;" for="no"><b>Invoice Number</b></label>
    <input type="text" style="width:250px;" id="inv_no" class="rounded" placeholder="invoice no" name="inv_no" value="<?php echo $invid; ?>">
</div>
<div class="form-group">
    <label style="width:150px;" for="dat"><b>Date</b></label>
	
    <input style="width:250px;" class="rounded" type="date" id="dat" name="dat"  required>
</div>
<div class="form-group">
    <label style="width:150px;" for="no"><b>Time</b></label>
    <input style="width:250px;" class="rounded" type="time" id="time" name="time"  required>
</div>
<div class="form-group">
    <label style="width:150px;" for="no"><b>Vehicle Number</b></label>
    <input type="text" style="width:250px;" id="vno" class="rounded" name="vno" required>
</div>
<div class="form-group">
    <label  style="width:150px;"for="no"><b>Item Category</b></label>
                       
	<select name="item_category" id="item_category" style="width:250px;" class="rou" onchange="getItemDesctp(this.value);" required>
	<option value="" disabled selected hidden>Please Choose an Item...</option>
	<?php 
		$sql1="select * from product";
		$res=mysqli_query($con,$sql1);
		while($row1 = mysqli_fetch_array($res))
		{
	?>
	<option value="<?php echo $row1['id']; ?>"><?php echo $row1['item']; ?></option> 
	<?php
		}
	?>
	</select> 
	<button type="button" class="btn bg-gradient-primary text-white mr-2 add" data-toggle="tooltip" data-placement="bottom" title="Add product" style="background-color:#b134eb ;"><i class="ace-icon fa fa-plus bigger-130"></i></button>
</div>
<div class="form-group" id="pol">
    <label  style="width:150px;"for="no"><b>Item Description</b></label>
   
	<select name="item" id="item" style="width:250px;" class="rou" required>
		<option value="" disabled selected hidden>Please Select...</option>
	</select> 
	<button type="button" class="btn bg-gradient-primary text-white mr-2 editinv" data-toggle="tooltip" data-placement="bottom" title="Add Inventory" style="background-color:#b134eb ;"><i class="fas fa-cart-arrow-down"></i></button>			
</div>
<div class="form-group">
   <label style="width:150px;" for="sname"><b>Supplier Name</b></label>
   <select name="sname" id="supplier_name" style="width:250px;" class="rou" required>
   <option value="" disabled selected hidden>Please Choose an Supplier...</option>
   <?php 
		$sql="select * from supplier";
	    $res=mysqli_query($con,$sql);
		while($row = mysqli_fetch_array($res))
		{ 
	?>
	<option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option>
	<?php
		}
	?>
	</select>
	<button type="button" class="btn bg-gradient-primary text-white mr-2 editbtn" data-toggle="tooltip" data-placement="bottom" title="Add Supplier" style="background-color:#b134eb ;"><i class="fa fa-user-plus"></i></button>
</div>
<div class="form-group">
    <label style="width:150px;" for="item"><b>Product Type</b></label>
    <select style="width:250px;" class="rou" id="ptype" name="ptype" required>
    <option value="" disabled selected hidden>Please Select...</option>
	<?php 
		$sql1="select * from productype";
	    $res=mysqli_query($con,$sql1);
		while($row1 = mysqli_fetch_array($res))
		{
	?>
	<option value="<?php echo $row1['id']; ?>"><?php echo $row1['item']; ?></option> 
    <?php
		}
	?>
	</select> 
	 <button type="button" class="btn bg-gradient-primary text-white mr-2 productype" data-toggle="tooltip" data-placement="bottom" title="Add product type" style="background-color:#b134eb ;"><i class="ace-icon fa fa-plus bigger-130"></i></button>
					
</div>
<div class="form-group">
    <label style="width:150px;" for="qty_typ"><b>Quantity Type</b></label>
    <select style="width:250px;" class="rou" id="qty_typ" name="qty_typ" onchange="changefunc()" required>
	  <?php 
		$sql1="select * from quantity_type";
	    $res=mysqli_query($con,$sql1);
		while($row1 = mysqli_fetch_array($res))
		{
		?>
		<option value="<?php echo $row1['id']; ?>"><?php echo $row1['q_name']; ?></option> 
	    <?php
		}
		?>
    </select>
	<input type="hidden" class="rounded" style="width:100px;"  id="qty" name="qty" readonly>
</div>
<div class="form-group" id="qty11" >
	<label style="width:150px;" for="qty"><b>Quantity</b></label>
    <input type="text" style="width:250px;" maxlength="6" class="rounded" id="ko" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Kilo</label>
	<input type="text" style="width:250px;" maxlength="3" class="rounded" id="gr" pattern="^(0|[1-9][0-9]*)$" value ="0"><label>gram</label>
	
</div>
<div class="form-group" id="qty12" style="display:none">
	<label style="width:150px;" for="qty"><b>Quantity</b></label>
	<input type="text" style="width:250px;" maxlength="6" class="rounded" id="piec" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Pieces</label>
</div>
<div class="form-group" id="qty13" style="display:none">
	<label style="width:150px;" for="qty"><b>Quantity</b></label>
	<input type="text" style="width:250px;" maxlength="6" class="rounded" id="litr" pattern="^(0|[1-9][0-9]*)$" title="Enter a Valid Input" value="0"><label>Litre</label>
	<input type="text" style="width:250px;" maxlength="3" class="rounded" id="mltr" pattern="^(0|[1-9][0-9]*)$" value ="0">ml
</div>
<div class="form-group" id="qty14" style="display:none">
	<label style="width:150px;" for="qty"><b>Quantity</b></label>
	<input type="text" style="width:250px;" maxlength="6" class="rounded" id="mtr" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Meter</label>
</div>
<div class="form-group" id="qty15" style="display:none">
	<label style="width:150px;" for="qty"><b>Quantity</b></label>
	<input type="text" style="width:250px;" maxlength="6" class="rounded" id="ft" pattern="^[0-9]+(\.[0-9]{1,4})?$" title="Enter a Valid Input" value="0"><label>Feet</label>
</div>
<div class="form-group">
    <label style="width:150px;" for="moisture"><b>Moisture</b></label>
    <input type="text" style="width:250px;" id="moisture" class="rounded" name="moisture" maxlength="2" placeholder="%"  oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" required>%
 </div>
 <div class="form-group">
    <label style="width:150px;" for="lap_report"><b>Lab report</b></label>
    <input type="text" class="form-control" id="lab_report" name="lab_report"  placeholder="Lab report" required>
</div>
<div class="form-group">
    <label><b>Lab report File upload</b></label>
    <input type="file" name="labfile" class="file-upload-default" onchange="loadfile(event)" >
    <div class="input-group col-xs-12">
      <input type="text"  class="form-control file-upload-info" disabled placeholder="Lab report Upload Image" >
    </div>
					
	<div>
		<img id="preview" height="100" width="100" > 
	</div>
</div>
    <button type="submit"  class="btn btn-primary" id = "purchaseSubmit" name="submit">Submit</button>
    <!-- <button class="btn btn-danger">Cancel</button> -->
</form>
</div>

<!-- Add inventory Modal -->
<div id="add_inv" class="modal fade" role="dialog" tabindex="-1" aria-hidden="true"> 
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
         <h4 class="modal-title">Add Inventory</h4>
		 <button type="button" onclick="clearForm('add_name')" class="close" data-dismiss="modal">&times;</button>
       
      </div>
      <div class="modal-body">
       
		<form name="add_name" id="add_name">
		
		<table class="table table-bordered" id="dynamic_field">
				
			<tr>
			<div class="form-group">
                <label  style="width:150px;"for="no"><b>Item Category</b></label>
            
				<select name="items" id="items" style="width:250px;" class="rou">
				<?php 
					$sql1="select * from product";
				    $res=mysqli_query($con,$sql1);
					while($row1 = mysqli_fetch_array($res))
					{
				?>
				<option value="<?php echo $row1['id']; ?>"><?php echo $row1['item']; ?></option> 
				<?php
				}
				?>

				</select> 
						
			</div>
					   
				<td><input type="text" name="name[]" id="name" placeholder="Enter Item Description" class="form-control name_list"></td>
				<td><button type="button" name="addp" id="addp" class="btn btn-success">Add More</button></td>
			</tr>
		
		</table>
			
		  <b id="mesgInv"></b>			
		  <input type="button" name="submit" id="submitInv" style="background-color:#FF6666" class="btn bg-gradient-primary text-white mr-2" value="Submit"/>
		  <button type="button" class="btn btn-danger" data-dismiss="modal" onclick="clearForm('add_name')">Close</button>
		</form> 

      </div>
      <div class="modal-footer">
       
      </div>
    </div>

  </div>
</div>

<!-- Add Product Modal -->
<div id="ad_product" class="modal fade" role="dialog" tabindex="-1" aria-hidden="true"> 
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Add Product</h4>
		<button type="button" onclick="clearForm('user_form')" class="close" data-dismiss="modal">&times;</button>
        
      </div>
      <div class="modal-body">
       
		<form method="POST" id="user_form">
		
		<div class="form-group">
            <label>Product Name</label>
            <input type="text" class="form-control" id="pname" name="pname" required>
        </div>
        <b id="mesg"></b>
		<input type="button" name="add_product" id="add_product" style="background-color:#FF6666" class="btn btn-default" value="Submit"/>
		<button type="button" style="background:radial-gradient(#FFF176, #ff3300)" class="btn btn-default" data-dismiss="modal" onclick="clearForm('user_form')">Close</button>
		</form> 

      </div>
      <div class="modal-footer">
       
      </div>
    </div>

  </div>
</div>

<!-- Add Product type Modal -->
<div id="ad_productype" class="modal fade" role="dialog" tabindex="-1" aria-hidden="true"> 
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
        <div class="modal-header">
	        <h4 class="modal-title">Add Product Type</h4>
			<button type="button" class="close" data-dismiss="modal" onclick="clearForm('user_form2')">&times;</button>
        </div>
        <div class="modal-body">
       
		<form method="POST" id="user_form2">
			<div class="form-group">
                <label>Product Type</label>
                <input type="text" class="form-control" id="ptname" name="ptname" placeholder="Enter product type" required>
            </div>
            <b id="mesg2"></b>
		 	<input type="button" name="productype" id="productype" style="background-color:#FF6666" class="btn btn-default" value="Submit"/>
		    <button type="button" style="background:radial-gradient(#FFF176, #ff3300)" class="btn btn-default" data-dismiss="modal" onclick="clearForm('user_form2')">Close</button>
		</form> 

      </div>
      <div class="modal-footer">
       
      </div>
      </div>

  </div>
</div>

<!-- Update Supplier Modal -->
<div id="add_sup" class="modal fade" role="dialog" tabindex="-1" aria-hidden="true"> 
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
         <h4 class="modal-title">Add Supplier</h4>
		 <button type="button" class="close" onclick="clearForm('user_form1')" data-dismiss="modal">&times;</button>
       
      </div>
      <div class="modal-body">
       
		<form method="post" id="user_form1">
			<div class="form-group">
               <label for="sname">Supplier Name</label>
                       
               <input type="text" class="form-control" name="sname" id="sname" required>
                      
            </div>
            <div class="form-group">
                <label for="phone">Phone</label>
                <input type="text" class="form-control" maxlength="10" name="phone" id="phone"  oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" required>
            </div>
            <div class="form-group">
                <label for="email">Email address</label>
                <input type="email" class="form-control" name="email" id="email" placeholder="Email" required>
            </div>
			<div class="form-group">
                <label for="address">Address</label>
                <textarea class="form-control" id="address" rows="4" name="address" required></textarea>
            </div>
                      
                     
		 
		 <b id="mesg1"></b>
		 
		  <input type="button" name="add" id="add" style="background-color:#FF6666" class="btn btn-default" value="Submit"/>
		   <button type="button" class="btn btn-default" data-dismiss="modal" onclick="clearForm('user_form1')">Close</button>
		</form> 

      </div>
      <div class="modal-footer">
       
      </div>
    </div>

  </div>
</div>

</body>

<script>
$(document).ready(function(){
	var userid = '<?php echo @$userid; ?>';

	$('#dat').val(new Date().toDateInputValue());

	$('#time').val(formatTime(new Date()));

	$('.editinv').on('click',function() {
		$('#add_inv').modal('show');

		$('#item_category option').each(function() {
		    if($(this).is(':selected')){
		    	$('#items').val($('#item_category').val());
		    }
		});
	});

	$('.productype').on('click',function() {
			
		$('#ad_productype').modal('show');
			
	});

	$('.add').on('click',function() {
			
		$('#ad_product').modal('show');
	});

	$('.editbtn').on('click',function() {
			
		$('#add_sup').modal('show');
	});

	$("#purchaseForm").submit(function(e) {
    document.getElementById("purchaseSubmit").disabled=true;
    //prevent Default functionality
    e.preventDefault();
    //do your own request an handle the results
   	var formData = new FormData(this);

   	var selectedValue = formData.get('qty_typ');
   	//console.log('Slected data',selectedValue);
   	if(selectedValue == "1")
	{
		var kilogrm = (parseInt($('#ko').val()) * 1000)+parseInt($('#gr').val());
		formData.set('qty',kilogrm);
		
	}else if(selectedValue == "3")
	{
		var milliltr = (parseInt($('#litr').val()) * 1000)+parseInt($('#mltr').val());
		formData.set('qty',milliltr);
	}else if(selectedValue == "2")
	{
		formData.set('qty',$('#piec').val());
	}else if(selectedValue == "4")
	{
		formData.set('qty',$('#mtr').val());
		
	}else if(selectedValue == "5")
	{
		formData.set('qty',$('#ft').val());
	}

	formData.append('type','storePurchase');
	formData.append('userId',userid);
	
     $.ajax( {
        url: '../controller/purchase_controller.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,

        success: function(data){
          console.log('Msg',data);
          if(data.status == true){
	        alert('Purchase Item Added successfully'); 
	        window.location.reload();
      	  }else{
      	  	alert('Failed To Add Item'); 
      	  	document.getElementById("purchaseSubmit").disabled=false;
      	  }
        },
        error: function(r) {
          alert('Unable to Add Item'); 
          document.getElementById("purchaseSubmit").disabled=false;
        }
      } );

	});

	$('#add_product').click(function(){
		var data=$('#user_form').serialize()+'&type=add_product';
		var productnm = $('#pname').val();
		$.ajax({
			url:'../controller/purchase_controller.php',
			type:'POST',
			data:data,
			success:function(response){
				console.log('Result',response);
				if(response.status == true){
					alert(response.msg);
					$('#item_category').append($('<option>', {
					    value: response.rowId,
					    text: productnm
					}));
					$('#items').append($('<option>', {
					    value: response.rowId,
					    text: productnm
					}));

					$('#ad_product').modal('hide');
					clearForm('user_form');

				}else{
					alert(response.msg);
				}
			}
		});
	});

	$('#add').click(function(){
		var data=$('#user_form1').serialize()+'&type=addSup';
		var snm = $('#sname').val();
		$.ajax({
			url:'../controller/purchase_controller.php',
			type:'POST',
			data:data,
			success:function(response){
				console.log('Result s',response);
				if(response.status == true){
					alert(response.msg);
					$('#supplier_name').append($('<option>', {
					    value: response.rowId,
					    text: snm
					}));

					$('#add_sup').modal('hide');
					clearForm('user_form1');
				}else{
					alert(response.msg);
				}
			}
		});
	});

	$('#productype').click(function(){
		var data=$('#user_form2').serialize()+'&type=productype';
		var prodtypname = $('#ptname').val();
		$.ajax({
			url:'../controller/purchase_controller.php',
			type:'POST',
			data:data,
			success:function(response){
				console.log('Result pt',response);
				if(response.status == true){
					alert(response.msg);
					$('#ptype').append($('<option>', {
					    value: response.rowId,
					    text: prodtypname
					}));

					$('#ad_productype').modal('hide');
					clearForm('user_form2');
				}else{
					alert(response.msg);
				}
			}
		});
	});

	addMoreInv();

	
});

function loadfile(event){
	var output=document.getElementById('preview');
	output.src=URL.createObjectURL(event.target.files[0]);
};

function changefunc() {
	var y = document.getElementById("qty_typ");
	var selectedValue = y.options[y.selectedIndex].value;
	
	if(selectedValue == "1")
	{
		$('#qty11').show();
		$('#qty12').hide();
		$('#qty13').hide();
		$('#qty14').hide();
		$('#qty15').hide();
		
	}else if(selectedValue == "2")
	{
		$('#qty12').show();
		$('#qty11').hide();
		$('#qty13').hide();
		$('#qty14').hide();
		$('#qty15').hide();
		
	}else if(selectedValue == "4")
	{
		$('#qty12').hide();
		$('#qty11').hide();
		$('#qty13').hide();
		$('#qty14').show();
		$('#qty15').hide();
		
	}else if(selectedValue == "5")
	{
		$('#qty12').hide();
		$('#qty11').hide();
		$('#qty13').hide();
		$('#qty14').hide();
		$('#qty15').show();
		
	}else
	{
		$('#qty13').show();
		$('#qty11').hide();
		$('#qty12').hide();
		$('#qty14').hide();
		$('#qty15').hide();
		
	}
}

function clearForm(formname){
	$("#"+formname).trigger("reset");

	if(formname == 'user_form'){
		$('#mesg').text('');
		$('#add_product').show();
	}else if(formname == 'user_form1'){
		$('#mesg1').text('');
		$('#add').show();
	}else if(formname == 'user_form2'){
		$('#mesg2').text('');
		$('#productype').show();
	}else if(formname == 'add_name'){
		$('#mesgInv').text('');
		$("#dynamic_field").find("tr:gt(0)").remove();
	}
}

function addMoreInv(){
	var i=1;  
	$('#addp').click(function(){
		i++;
		$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" id="name" placeholder="Enter Item Description" class="form-control name_list"></td><td><button name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
	});
	$(document).on('click','.btn_remove',function(){
		var button_id=$(this).attr("id");
		$("#row"+button_id+"").remove();
	});
	
	$('#submitInv').click(function(){

		$.ajax({
			url:"../controller/purchase_controller.php",
			method:"POST",
			data:$('#add_name').serialize()+'&type=validateInventory',
			success:function(data)
			{
				if(data.status == true){
					$.ajax({
						url:"../controller/purchase_controller.php",
						method:"POST",
						data:$('#add_name').serialize()+'&type=addInventory',
						success:function(data)
						{
							alert(data);
							$('#add_name')[0].reset();
							$("#dynamic_field").find("tr:gt(0)").remove();
							$('#add_inv').modal('hide');
							getItemDesctp($("#item_category").val());
							
						}
					});
				}else{
					$('#mesgInv').text(data.msg);
				}
				
			}
		});
		
	});
}

function getItemDesctp(value){
$.ajax( {
    url: '../controller/purchase_controller.php',
    type: 'POST',
    data: 'value='+value+'&type=getItemDesp',

    success: function(data){
      console.log('Msg',data);
      if(data.status == true){
      	  $('#item').empty();
          $('#item').append(data.data);
  	  }else{
  	  	$('#item').empty();
  	  }
    },
    error: function(r) {
      console.log(r);
      $('#item').empty();
    }
  } );
}

Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});

const getTwoDigits = (value) => value < 10 ? `0${value}` : value;

const formatTime = (date) => {
  const hours = getTwoDigits(date.getHours());
  const mins = getTwoDigits(date.getMinutes());

  return `${hours}:${mins}`;
}

</script>
</html>