<!DOCTYPE html>
<?php
require_once('../Db/dbconfig.php');
@$name=$_GET['username'];
@$userid=$_GET['userid'];
?>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">
<script src="https://kit.fontawesome.com/c17eae44a3.js" crossorigin="anonymous"></script>
<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://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.24/api/sum().js"></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;
}

@media only screen and (max-height: 700px) {
	.child{
	  width:1000px;
	  float:left;
	  font-size:15px;
	  font-family:arial;
	  padding:10px;
	  cursor: pointer;
	}
}
</style>
</head>
<body>
<div class="card">
	<div class="page-header">
      <h3 class="page-title">
        <span class="page-title-icon bg-gradient-primary text-white mr-2">
        <i class="fas fa-cubes fa-xs" style="color: black"></i>
        </span><b>Stock</b></h3>
        <input type="hidden" id="username" value="<?php echo @$name;?>">
    </div>
    <div class=" card-header d-flex flex-row-reverse">
		<a href="../view/multiple_stock_to_export.php?userid=<?php echo @$userid; ?>&multipleraw=0"><button type="button" class="btn btn-primary sendbtn"><i class="ace-icon fa fa-share bigger-130"></i></button></a>
        <label class="p-2" style="width:200px;" for="dat"><b>Multiple Product Send :</b></label>
	</div>
	<div class="card-body child" style="overflow: auto;">
		
		<table id="datatableid1" class="table table-striped table-bordered table-hover">
			<thead class="thead-dark">
				<tr style="background-color:#f54281">
					<th class="center">
						
					</th>
					<th>Sr.No</th>
					<th>Lot Number</th>
					<th>Sent From</th>
					<th>Final Product</th>
					<th>Quantity</th>	
					<th>Quantity Type</th>
					<th>#Total Boxes</th>
					<th>Sent DateTime</th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<!--<th style="width: 13%;">Final Product Details</th>-->
					<th>Send To</th>
					<th>Delete</th>
				</tr>
			</thead>
			<tbody>
			<?php 
				$sql = "select '1' as is_single,s.ids,s.id,s.frmdpt,s.finalprodID,s.send_to_quantity,s.q_name,s.qttypeId,s.totalBoxs,s.senddttime,s.finalProdname,s.admindpt_parent_details,s.lotnumber from (select group_concat(ad.id order by ad.id asc) as ids, max(ad.id) as id,frmd.depart as frmdpt,p.item as finalProdname,p.id as finalprodID,
				sum(if(ad.totalBoxs > 1,ad.send_to_quantity * ad.totalBoxs,ad.send_to_quantity)) as send_to_quantity,sendqt.q_name,sendqt.id as qttypeId,
				max(ad.created_at) as senddttime ,sum(ad.totalBoxs) as totalBoxs,ad.admindpt_parent_details,ad.lotnumber
				from package_to_stock ad ,department frmd,final_product p ,quantity_type sendqt
				where frmd.id = 2 and ad.final_product = p.id and ad.send_to_qtny_type = sendqt.id and ad.send_to_quantity > 0 and ad.storageId !=0 group by ad.lotnumber,p.id,sendqt.id having sum(ad.send_to_quantity) > 0) s
				UNION
				select '0' as is_single,m.ids,m.id,m.frmdpt,m.finalprodID,m.send_to_quantity,m.q_name,m.qttypeId,m.totalBoxs,m.senddttime,m.finalProdname,m.admindpt_parent_details,m.lotnumber from (select group_concat(ad.id order by ad.id asc) as ids, max(ad.id) as id,frmd.depart as frmdpt,p.item as finalProdname,p.id as finalprodID,
				sum(if(ad.totalBoxs > 1,ad.send_to_quantity * ad.totalBoxs,ad.send_to_quantity)) as send_to_quantity,sendqt.q_name,sendqt.id as qttypeId,
				max(ad.created_at) as senddttime ,sum(ad.totalBoxs) as totalBoxs,ad.admindpt_parent_details,ad.lotnumber
				from package_to_stock ad ,department frmd,final_product p ,quantity_type sendqt
				where frmd.id = 2 and ad.final_product = p.id and ad.send_to_qtny_type = sendqt.id and ad.send_to_quantity > 0 and ad.storageId =0 group by ad.lotnumber,p.id,sendqt.id having sum(ad.send_to_quantity) > 0) as m order by senddttime";
				$result = $con->query($sql);

				if ($result->num_rows > 0) 
				{
					// output data of each row
					while($row = $result->fetch_assoc()) 
					{
			?>
			<tr style="background-color:#AFF3CA">
				<td class="center">
					
					<p style="display: none"><?php echo $row['ids']?></p>
				</td>
				<td>
					<p><?php 
						if($row['is_single'] == '1'){
							echo $row['id']."-S";
						}else{
							echo $row['id']."-M";
						}
					?></p>
				</td>
				<td>
					<?php 
						echo $row['lotnumber'];
					?>
				</td>
				<td>
					<p><?php echo $row['frmdpt']?></p>
				</td>
				<td>
					<p><?php echo $row['finalProdname']?></p>
				</td>
				<td>
					<p><?php 

					if($row['qttypeId'] == '1' or $row['qttypeId'] == '3'){
						if($row['send_to_quantity'] != 0){
							echo ($row['send_to_quantity']/1000);
						}else{
							echo $row['send_to_quantity'];
						}
					}else{
						echo $row['send_to_quantity'];
					}
					?>
					</p>
				</td>
				<td>
					<p><?php echo $row['q_name']?></p>
				</td>
				<td>
					<p><?php echo $row['totalBoxs']?></p>
				</td>
				<td>
					<p><?php 
						$date = new DateTime($row['senddttime'], new DateTimeZone('MST'));
						$date->setTimezone(new DateTimeZone('Asia/Kolkata'));
						echo $date->format('Y-m-d H:i:s');
					?></p>
				</td>
				<td style="display: none;"><?php echo $row['finalprodID']?></td>
				<td style="display: none;"><?php echo $row['qttypeId']?></td>
				<td style="display: none;"><?php echo $row['is_single']?></td>
				<!--
				<td>
					<button type="button" class="btn btn-primary viewbtn"><i class="ace-icon fa fa-search-plus bigger-130"></i></button>
				</td>
				-->
				<td>
					<button type="button" class="btn btn-primary sendbtn"><i class="ace-icon fa fa-plus bigger-130"></i></button>
				</td>
				<td><button type="button" class="btn btn-primary deletebtn" title="Delete"><i class="ace-icon fa fa-trash-o"></i></button></td>
			</tr>
			<?php
					}
				}

			?>
			</tbody>
		</table>
						
	</div>
</div>

<!--Send Modal-->
<div id="single_send" class="modal fade" role="dialog" tabindex="-1" aria-hidden="true" style="overflow: auto;text-align: center;"> 
  <div class="modal-dialog" style="text-align: left; max-width: 100%;width: auto !important; display: inline-block;">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header" style="background-image: linear-gradient(to right,#e60b81, #8800ff);">
	  <h4 class="modal-title" style="color: white">Send To Export</h4>
        <button type="button" class="close" data-dismiss="modal" onclick="clearForm('stockForm')">&times;</button>
        
      </div>
      <div class="modal-body">
      	<input type="hidden" id="issendfromsingle" readonly>
        <form id="stockForm">
        <div class= "row" style="margin-left: 0px;">
		    <div class="form-group col-3">
				    <label for="revcdFinalProdct">Final Product : </label>
				    <input type="text" class="rounded" id="revcdFinalProdct" name="revcdFinalProdct" disabled>
				</div>
				<div class="form-group col-3">
				 	<label for="boxescat">Available Boxes/Quantity :</label>
          <select style="width:150px;" class="rou" id="boxescat" name="boxescat" onchange="setQauntityPerBox()" required>
          </select>
				</div>
				<div class="form-group col-3">
				    <label for="revcdFinalProdct">Quantity Per Box: </label>
				    <select style="width:150px;" class="rou" id="totalQty" name="totalQty" disabled>
            </select>
				    <label id=totalQtyType></label>
				</div>
			</div>
			<div class="row" style="margin-left: 0px;">
				<div class="form-group">
			    <label style="width:119px;" for="no">Invoice Number:</label>
			    <input type="text" style="width:150px;" id="inv_no" class="rounded" placeholder="Invoice no" name="inv_no" required>
			</div>
		
			<div class="form-group" style="margin-left: 2%;">
			    <label style="width:93px;" for="invdat">Invoice Date:</label>
				
			    <input style="width:150px;" class="rounded" type="date" id="invdat" name="invdat"  required>
			</div>
			</div>
			<div class="row" style="margin-left: 0px;">
			<div class="form-group">
			    <label for="revcdFinalProdct">Buyer's Name : </label>
				    <select style="width:250px;" class="rou" id="buyrname" name="buyrname" required>
					   <?php 
						$sql1="select * from purchaser_master";
					    $res=mysqli_query($con,$sql1);
						while($row1 = mysqli_fetch_array($res))
						{
						?>
						<option value="<?php echo $row1['id']; ?>"><?php echo $row1['name']; ?></option> 
					    <?php
						}
						?>
				    </select>
					<button type="button" class="btn btn-primary addpurchaser" data-toggle="tooltip" data-placement="bottom" title="Add Purchaser" style="background-color: #b134eb;"><i class="ace-icon fa fa-plus bigger-130"></i></button>
			</div>
			<div class="form-group" style="margin-left: 2%;">
          <label for="isinternational">Export :</label>
          <select style="width:150px;" class="rou" id="isinternational" name="isinternational" required>
            <option value="1">International</option>
						<option value="0">Domestic</option>
				</select>
      </div>
      <div class="form-group" style="margin-left: 2%;">
				    <label for="noofbox">No. of Boxes to Send: </label>
				    <input type="text" style="width:100px;" class="rounded" id="noofbox" name="noofbox" value="0" required>
				</div>
      </div>
      
			<button type="submit" name="stockSend" id="stockSend" class="p-1 mb-1 bg-primary text-white rounded">Submit</button>
	  		<button type="button" class="p-1 mb-2 bg-danger text-white rounded" data-dismiss="modal" onclick="clearForm('stockForm')">Close</button>
	      </form>
      </div>
      <div class="modal-footer">
 
      </div>
    </div>

  </div>
</div>

<!--Edit Modal-->
<div id="editModal" 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">Delete Stock</h4>
        <button type="button" class="close" data-dismiss="modal" onclick="clearForm('editForm')">&times;</button>
        
      </div>
      <div class="modal-body">
       
	<form id="editForm">
	<input type="hidden" class="form-control" id="editadminId" name="editadminId">
	<input type="hidden" class="form-control" id="editis_single">
		<div class="form-group" >
      <label  style="width:150px;"for="editfin_product"><b>Final Product :</b></label>
      <input type="text" style="width:150px;" maxlength="6" class="rounded" id="editfin_product" disabled>
		</div>	
		<div class="form-group">
		<label style="width:150px;" for="totqty"><b>Quantity Per Box:</b></label>
		<input type="text" style="width:150px;" maxlength="6" class="rounded" id="totqty" disabled><label id="totqtytype"></label>
		</div>

		<div class="form-group">
		<label style="width:150px;" for="totqty"><b>Total Boxes Available:</b></label>
		<input type="text" style="width:150px;" maxlength="6" class="rounded" id="totboxes" disabled>
		</div>

		<div class="form-group">
		<label style="width:150px;" for="totqty"><b>No. of Boxes to Delete:</b></label>
		<input type="text" style="width:150px;" maxlength="6" class="rounded" id="noofboxes" name="noofboxes" value ="0" required>
		</div>
		
      <button type="submit" id = "updateProds" name="updateProds" class="btn btn-gradient-primary mr-2">Update</button>
		  <button type="button" class="btn btn-default" data-dismiss="modal" onclick="clearForm('editForm')">Close</button>
	</form> 

      </div>
     
    </div>

  </div>
</div>

<!-- Add Table Modal -->
<div id="tableModal" class="modal fade" role="dialog" tabindex="-1" aria-hidden="true" style="overflow: auto;text-align: center;"> 
  <div class="modal-dialog" style="text-align: left; max-width: 100%;width: auto !important; display: inline-block;">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
         <h4 class="modal-title">Final Product Details</h4>
		 <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
       	<table id="datatableid" class="table table-striped table-bordered table-hover">
			<thead class="thead-dark">
				<tr style="background-color:#048065">
					<th>Sr. No</th>
					<th>Sent From</th>
					<th>Final Product</th>
					<th>Quantity Per Box</th>	
					<th>Quantity Type</th>
					<th>Total Boxes</th>
					<th>Sent DateTime</th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<?php
						if(@$name == 'superadmin'){
					?>
					<th>Delete</th>
					<?php
						}
					?>
					
				</tr>
			</thead>
			<tbody>
			
			</tbody>
		</table>
	  </div>
      <div class="modal-footer">
       
      </div>
    </div>

  </div>
</div>

<!-- Add Table Modal -->
<div id="tableModalMl" class="modal fade" role="dialog" tabindex="-1" aria-hidden="true" style="overflow: auto;text-align: center;"> 
  <div class="modal-dialog" style="text-align: left; max-width: 100%;width: auto !important; display: inline-block;">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
         <h4 class="modal-title">Final Product Details</h4>
		 <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
       	<table id="datatableid3" class="table table-striped table-bordered table-hover">
			<thead class="thead-dark">
				<tr style="background-color:#048065">
					<th>Sr. No</th>
					<th>Sent From</th>
					<th>Final Product</th>
					<th>Quantity Per Box</th>	
					<th>Quantity Type</th>
					<th>Total Boxes</th>
					<th>Sent DateTime</th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<?php
						if(@$name == 'superadmin'){
					?>
					<th>Delete</th>
					<?php
						}
					?>
					
				</tr>
			</thead>
			<tbody>
			
			</tbody>
		</table>
	  </div>
      <div class="modal-footer">
       
      </div>
    </div>

  </div>
</div>

<!-- Add Purchaser 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 Purchaser</h4>
		 <button type="button" class="close" onclick="clearForm('user_form1')" data-dismiss="modal">&times;</button>
       
      </div>
      <div class="modal-body">
       
		<form id="user_form1">
			<div class="form-group">
               <label for="sname">Purchaser 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" pattern="[^@\s]+@[^@\s]+\.[^@\s]+" title="Invalid email address" required>
            </div>
			<div class="form-group">
                <label for="address">Address</label>
                <textarea class="form-control" id="address" rows="4" name="address" required></textarea>
            </div>
         
		  <input type="submit" 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 type="text/javascript">
$(document).ready(function(){
	
	var userid = '<?php echo @$userid; ?>';
	var t = $('#datatableid1').DataTable( {
	rowReorder: true,
	"order": [[ 8, "desc" ]],
	columnDefs: [
	    { orderable: true, targets: '_all' }
	    
	]
	} );

	var t1 = $('#datatableid').DataTable( {
		rowReorder: true,
		"order": [[ 7, "desc" ]],
		columnDefs: [
			{ orderable: true, targets: '_all' }
			
		]
	} );

	var t3 = $('#datatableid3').DataTable( {
		rowReorder: true,
		"order": [[ 7, "desc" ]],
		columnDefs: [
			{ orderable: true, targets: '_all' }
			
		]
	} );

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

	$('#datatableid1').on('click','.viewbtn',function() {
		
		$tr = $(this).closest('tr');

		var data = $tr.children('td').map(function(){
			return $(this).text();
		}).get();

		var adminIds = data[0].trim();
		var isSingle = data[11].trim();

		var tableEle = t1;

		if(isSingle == '0'){
			tableEle = t3;
		}
		
		$.ajax( {
			url: '../controller/stock_controller.php',
			type: 'POST',
			data: 'id='+adminIds+'&type=viewStock',

			success: function(data){
				
				if(data.status == true){
					var rows = tableEle
					.rows()
					.remove()
					.draw();
					
					$.each(data.data,function(i,item){

						var finalqty = 0;
						if(item.qttypeId == '1' || item.qttypeId == '3'){
							finalqty = item.send_to_quantity/1000;
						}else{
							finalqty = item.send_to_quantity;
						}
						
						var rowNode = tableEle
						.row.add( [item.id, item.frmdpt,item.finalProdname,finalqty,item.q_name,item.totalBoxs,item.senddttime,item.finalprodID,item.qttypeId,item.ids,'<button type="button" name="edit" class="btn btn-primary editbtn" title="Delete"><i class="ace-icon fa fa-trash-o"></i></button>'])
						.draw()
						.node();
					
					});

					tableEle.columns([7,8,9]).visible(false);

					if(isSingle == '0'){
						$('#tableModalMl').modal('show');
					}else{
						$('#tableModal').modal('show');
					}

				}
			
			},
			error: function(r) {
			console.log(r);
			var rows = tableEle
					.rows()
					.remove()
					.draw();
			}
		});	
		
	});

	$('#datatableid1').on('click','.sendbtn',function() {
		
		$('#single_send').modal('show');

		$tr = $(this).closest('tr');

		var data = $tr.children('td').map(function(){
			return $(this).text();
		}).get();

		var adminIds = data[0].trim();
		var isSingle = data[11].trim();
		$('#issendfromsingle').val(isSingle);
		
		$.ajax( {
    url: '../controller/stock_controller.php',
    type: 'POST',
    data: 'id='+adminIds+'&type=viewStock',

    success: function(data){
    	
	    if(data.status == true){
	    	$('#boxescat').empty();
	    	$('#totalQty').empty();
	     	$.each(data.data,function(i,item){

	     		var finalqty = 0;
	     		if(item.qttypeId == '1' || item.qttypeId == '3'){
	     			finalqty = item.send_to_quantity/1000;
	     		}else{
	     			finalqty = item.send_to_quantity;
	     		}
	     		
			    $('#boxescat').append($("<option />").val(item.ids).text(item.totalBoxs));
					$('#totalQty').append($("<option />").val(item.ids).text(finalqty));
		    });


	  	}
      
    },
    error: function(r) {
      console.log(r);
      $('#boxescat').empty();
      $('#totalQty').empty();
    }
   });
		
		$('#revcdFinalProdct').val(data[4].trim());
		
		$('#totalQtyType').html(data[6].trim());
			
		
	});

//this is box wise delete funtion
	$('#datatableid').on('click','.editbtn',function() {
		$tr = $(this).closest('tr');

		var data = $tr.children('td').map(function(){
			return $(this).text();
		}).get();

		var adminId = data[0].trim();
    						        
		$('#tableModal').modal('hide');
		$('#editModal').modal('show');

		var editfin_product = data[2].trim();

		var rowIndex = $(this).closest("tr").index();

		var editsendqty_typ = t1.column(8).data()[rowIndex];
	  
		$('#editadminId').val(t1.column(9).data()[rowIndex]);
		$('#editfin_product').val(editfin_product);
		$('#totboxes').val(data[5].trim());
				
		var editSendQty = data[3].trim();								
		$('#totqty').val(editSendQty);
		
		$('#totqtytype').html(data[4].trim());
		$('#editis_single').val('1');
		
		
	});

	//this is box wise delete funtion
	$('#datatableid3').on('click','.editbtn',function() {
		$tr = $(this).closest('tr');

		var data = $tr.children('td').map(function(){
			return $(this).text();
		}).get();

		
		var adminId = data[0].trim();
    						        
		$('#tableModalMl').modal('hide');
		$('#editModal').modal('show');

		var editfin_product = data[2].trim();

		var rowIndex = $(this).closest("tr").index();
		
		var editsendqty_typ = t3.column(8).data()[rowIndex];

		$('#editadminId').val(t3.column(9).data()[rowIndex]);
		$('#editfin_product').val(editfin_product);
		$('#totboxes').val(data[5].trim());
				
		var editSendQty = data[3].trim();								
		$('#totqty').val(editSendQty);
				
		$('#totqtytype').html(data[4].trim());
		$('#editis_single').val('0');
		
	});

	$('#datatableid1').on('click','.deletebtn',function() {
		$tr = $(this).closest('tr');

		var datatb = $tr.children('td').map(function(){
			return $(this).text();
		}).get();

		var adminId = datatb[0].trim();
		if (confirm("Are You Sure?")) {

			var isSingle = datatb[11].trim();
			var url = '../controller/stock_controller.php';
			if(isSingle == '0'){
				url = '../controller/multiple_raw_material_controller.php';
			}

			$.ajax( {
	        url: '../controller/stock_controller.php',
	        method: 'POST',
	        data:'type=validateProductIsExported&adminId='+adminId,
	        
	        success: function(data1){
	          //console.log('Msg',data1);
	          if(data1.status == true){
		        	alert('This Product has been exported furthur, first please delete from Export to delete this!.'); 
					document.getElementById("updateProds").disabled=false;
			      }else{
					$.ajax( {
						url: url,
						method: 'POST',
						data:'type=stockDelete&adminId='+adminId+'&userId='+userid,
						
						success: function(data2){
						console.log('Msg',data2);
						if(data2.status == true){
							alert('Product deleted and Quantity reverted to Packing'); 
							window.location.reload();
						}else{
							alert('Failed To Delete Product'); 
						}
						},
						error: function(r) {
						alert('Unable To Delete Product'); 
						}
					} );
				
				}
	        },
	        error: function(r) {
	          alert('Unable To Delete Product'); 
	        }
	      } );

		}
	      	
	});

	$("#stockForm").submit(function(e) {
    document.getElementById("stockSend").disabled=true;
    //prevent Default functionality
    e.preventDefault();
    //do your own request an handle the results

  	if(parseInt($('#noofbox').val()) == 0){
  		alert('Sending boxes cannot be 0');
		document.getElementById("stockSend").disabled=false;
  	}else if(parseInt($('#noofbox').val()) > parseInt($("#boxescat option:selected").text())){
		alert('Sending boxes cannot exceed available amount of boxes');
		document.getElementById("stockSend").disabled=false;
	}else{
		var formData = new FormData(this);
		formData.append('type','stockSend');
		formData.append('userId',userid);

		var url ='';

		if($('#issendfromsingle').val() == '1'){
			url = '../controller/stock_controller.php';
		}else{
			url = '../controller/multiple_raw_material_controller.php';
		}

	   $.ajax( {
	      url: url,
	      type: 'POST',
	      data: formData,
	      processData: false,
	      contentType: false,

	      success: function(data){
	        console.log('Msg',data);
	        if(data.status == true){
	        	alert('All Boxes Exported Successfully');
	        	window.location.reload();
	    	  }else{
	    	  	if(data.duplicateInv.length > 0){
	    	  		alert('Cannot send to Stock because Invoice No(s) already exist: '+data.duplicateInv.join());
	    	  	}else{
	    	  		alert('Failed To Add Items'); 
	    	  	}
	    	  	document.getElementById("stockSend").disabled=false;
	    	  	
	    	  }
	      },
	      error: function(r) {
	        alert('Unable to Add Items'); 
	        document.getElementById("stockSend").disabled=false;
	      }
	    } );
	}
   	
	});

	$("#editForm").submit(function(e) {
    document.getElementById("updateProds").disabled=true;
    //prevent Default functionality
    e.preventDefault();
    //do your own request an handle the results
   	
	if(parseInt($('#noofboxes').val()) == 0){
		alert('Boxes cannot be 0');
		document.getElementById("updateProds").disabled=false;
	}else if(parseInt($('#noofboxes').val()) > parseInt($('#totboxes').val())){
		alert('Boxes cannot exceed total boxes');
		document.getElementById("updateProds").disabled=false;
	}else{
		var formData = new FormData(this);
		
		formData.append('type','stockBoxDelete');
		formData.append('userId',userid);

		var isSingle = $('#editis_single').val();
		var url = '../controller/stock_controller.php';
		if(isSingle == '0'){
			url = '../controller/multiple_raw_material_controller.php';
		}

		$.ajax( {
	        url: '../controller/stock_controller.php',
	        method: 'POST',
	        data:'type=validateProductIsExported&adminId='+$('#editadminId').val(),
	        
	        success: function(data1){
	          //console.log('Msg',data1);
	          if(data1.status == true){
		        	alert('This Product has been exported furthur, first please delete from Export to delete this!.'); 
					document.getElementById("updateProds").disabled=false;
			      }else{
					
					$.ajax( {
						url: url,
						type: 'POST',
						data: formData,
						processData: false,
						contentType: false,

						success: function(data){
							console.log('Msg',data);
							if(data.status == true){
								alert('Product Deleted!'); 
								window.location.reload();
							}else{
								alert(data.msg); 
								document.getElementById("updateProds").disabled=false;
							}
						},
						error: function(r) {
							alert('Unable To Update Product'); 
							document.getElementById("updateProds").disabled=false;
						}
					} );
				
				}
	        },
	        error: function(r) {
	          alert('Unable To Delete Product'); 
	        }
	      } );
		
	}
});

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

	formData.append('type','addPurchaser');
	var snm = $('#sname').val();
	$.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){
			document.getElementById("add").disabled=false;
	        alert('Purchaser Added successfully'); 
	        $('#buyrname').append($('<option>', {
			    value: data.rowId,
			    text: snm
			}));
			$('#add_sup').modal('hide');
			$('#single_send').modal('show');
			clearForm('user_form1');
			
      	  }else{
      	  	alert(data.msg); 
      	  	document.getElementById("add").disabled=false;
      	  }
        },
        error: function(r) {
          alert('Unable to Add Purchaser'); 
          document.getElementById("add").disabled=false;
        }
      } );

	});

});

function changefuncEdit(selectedValue){
	
	if(selectedValue == "1")
	{
		$('#qty31').show();
		$('#qty32').hide();
		$('#qty33').hide();
		$('#qty34').hide();
		$('#qty35').hide();
		
	}else if(selectedValue == "2")
	{
		$('#qty32').show();
		$('#qty31').hide();
		$('#qty33').hide();
		$('#qty34').hide();
		$('#qty35').hide();
		
	}else if(selectedValue == "4")
	{
		$('#qty32').hide();
		$('#qty31').hide();
		$('#qty33').hide();
		$('#qty34').show();
		$('#qty35').hide();
		
	}else if(selectedValue == "5")
	{
		$('#qty32').hide();
		$('#qty31').hide();
		$('#qty33').hide();
		$('#qty34').hide();
		$('#qty35').show();
		
	}else
	{
		$('#qty33').show();
		$('#qty31').hide();
		$('#qty32').hide();
		$('#qty34').hide();
		$('#qty35').hide();
		
	}
}

function clearForm(formname){
	$("#"+formname).trigger("reset");
	
	if(formname == 'stockForm'){
		$("#item_table").find("tr:gt(0)").remove();
	}
}

function openTabs(evt, tbName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(tbName).style.display = "block";
  evt.currentTarget.className += " active";
}

function setQauntityPerBox(){
	$('#totalQty').val($('#boxescat').val());
}

</script>
</html>