<!DOCTYPE html>
<?php
require_once('../Db/dbconfig.php');
@$name=$_GET['username'];
@$isInternational=$_GET['isInternational'];
@$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">
	@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-file-export fa-xs" style="color: black"></i>
        </span>
        <b>
        	<?php 
        		if(@$isInternational == 1){
        			echo "International";
        		} else{
        			echo "Domestic";
        		}
        	?>
        </b></h3>
        <input type="hidden" id="username" value="<?php echo @$name;?>">
	</div>
	<div class="card-body child" style="overflow: auto;">
		<div style="text-align: right;"><label id="totalqt"></label></div>  
		<table id="datatableid" class="table table-striped table-bordered table-hover">
			<thead class="thead-dark">
				<tr style="background-color:#e65f05">
					<th class="center">
						
					</th>
					<th>Sr. No</th>
					<th>Lot Number</th>
					<th>Buyer's Name</th>
					<th>Final Product</th>
					<th>Total Quantity</th>	
					<th>Quantity Type</th>
					<th>Invoice No.</th>
					<th>Invoice Date</th>
					<th>#Total Boxes</th>
					<th>Sent DateTime</th>
					<th>Invoice Details</th>
					<?php
						if(@$name == 'superadmin'){
					?>
					<th>Delete</th>
					<?php
						}
					?>
				</tr>
			</thead>
			<tbody>
			<?php 
				$sql = "select group_concat(ste.id order by ste.id asc) as ids,group_concat(distinct ste.adminId) as adminids,group_concat(distinct ste.lotnumber) as lotnumbers,ste.id,pm.name as purchaser_name ,qt.q_name ,qt.id as qtytypeId,sum(if(ste.no_of_boxes > 1,ste.quantity * ste.no_of_boxes,ste.quantity)) as quantity ,ste.invoice_dt ,ste.invoice_no ,fp.item,sum(ste.no_of_boxes) as no_of_boxes,ste.created_at 
					from stock_to_export ste,quantity_type qt ,final_product fp,purchaser_master pm where ste.quantity_type = qt.id and ste.final_productId = fp.id and ste.purchaser_name=pm.id and ste.is_international =".@$isInternational." group by ste.invoice_no ,pm.id ,fp.id,qt.id";
				$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 echo $row['id']?></p>
				</td>
				<td>
					<?php
						echo $row['lotnumbers'];
					?>
				</td>
				<td>
					<p><?php echo $row['purchaser_name']?></p>
				</td>
				<td>
					<p><?php echo $row['item']?></p>
				</td>
				<td>
					<p><?php 

					if($row['qtytypeId'] == '1' or $row['qtytypeId'] == '3'){
						if($row['quantity'] != 0){
							echo ($row['quantity']/1000);
						}else{
							echo $row['quantity'];
						}
					}else{
						echo $row['quantity'];
					}
					?>
					</p>
				</td>
				<td>
					<p><?php echo $row['q_name']?></p>
				</td>
				<td>
					<p><?php echo $row['invoice_no']?></p>
				</td>
				<td>
					<p><?php echo $row['invoice_dt']?></p>
				</td>
				<td>
					<p><?php echo $row['no_of_boxes']?></p>
				</td>
				<td>
					<p><?php 
						$date = new DateTime($row['created_at'], new DateTimeZone('MST'));
						$date->setTimezone(new DateTimeZone('Asia/Kolkata'));
						echo $date->format('Y-m-d H:i:s');
					?></p>
				</td>
				<td>
					<button type="button" class="btn btn-primary viewbtn"><i class="ace-icon fa fa-search-plus bigger-130"></i></button>
				</td>
				<?php
					if(@$name == 'superadmin'){
				?>
				<td>
						<button type="button" class="btn btn-primary deletebtn" title="Delete"><i class="ace-icon fa fa-trash-o"></i></button>
				</td>
				<?php
					}
				?>
				
			</tr>
			<?php
					}
				}

			?>
			</tbody>
		</table>
	</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">Invoice Details</h4>
		 <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
       	<table id="datatableid1" class="table table-striped table-bordered table-hover">
			<thead class="thead-dark">
				<tr style="background-color:#048065">
					<th>Sr. No</th>
					<th>Invoice No.</th>
					<th>Invoice Date</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>
					<?php
						if(@$name == 'superadmin'){
					?>
					<th>Delete</th>
					<?php
						}
					?>
					
				</tr>
			</thead>
			<tbody>
			
			</tbody>
		</table>
	  </div>
      <div class="modal-footer">
       
      </div>
    </div>

  </div>
</div>

<!--Delete 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 Export</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">
		<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>
</body>
<script type="text/javascript">
$(document).ready(function(){
	var userid = '<?php echo @$userid; ?>';
	var t = $('#datatableid').DataTable( {
	rowReorder: true,
	"order": [[ 10, "desc" ]],
    columnDefs: [
        { orderable: true, targets: '_all' }
        
    ]
	} );

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

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

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

		var exportId = datatb[0].trim();
		if (confirm("Are You Sure?")) {
			$.ajax( {
		        url: '../controller/stock_controller.php',
		        method: 'POST',
		        data:'type=exportDelete&exportId='+exportId+'&userId='+userid,
		        
		        success: function(data2){
		          console.log('Msg',data2);
		          if(data2.status == true){
		          	alert('Product deleted Successfully and reverted to Stock!'); 
		          	window.location.reload();
		      	  }else{
		      	  	alert('Failed To Delete Product'); 
		      	  }
		        },
		        error: function(r) {
		          alert('Unable To Delete Product'); 
		        }
		    } );
	    
		}
	});

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

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

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

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

	     		var finalqty = 0;
	     		if(item.qtytypeId == '1' || item.qtytypeId == '3'){
	     			finalqty = item.quantity/1000;
	     		}else{
	     			finalqty = item.quantity;
	     		}
	     		
	     		var rowNode = t1
			    .row.add( [item.id, item.invoice_no,item.invoice_dt,item.item,finalqty,item.q_name,item.no_of_boxes,item.created_at,item.qtytypeId,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();
			
		    });

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

				$('#tableModal').modal('show');

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

	//this is box wise delete funtion
	$('#datatableid1').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[3].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[6].trim());
				
		var editSendQty = data[4].trim();	
		
		$('#totqty').val(editSendQty);
				
		$('#totqtytype').html(data[5].trim());
						
		
	});


	$("#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{
				var formData = new FormData(this);
				
				formData.append('type','exportBoxDelete');
				formData.append('userId',userid);
					
			    $.ajax( {
			        url: '../controller/stock_controller.php',
			        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;
			        }
			    } );
			}
	});
});

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

}
</script>
</html>