<!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://cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">
<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://cdn.datatables.net/1.10.4/js/jquery.dataTables.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>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.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;
}
</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>Multiple Product Send To Export</b></h3>
</div>
 <div class="card-body" style="background-color:#F0FFFF;overflow: auto;">
 <form action="" method="post" enctype='multipart/form-data' id="stockForm">
<div class="row" style="margin-left: 0 !important;width: 111%;">
	<div class="form-group col-2">
	    <label style="width:100px;" for="no">Invoice No. :</label>
	    <input type="text" style="width:150px;" id="inv_no" class="rounded" placeholder="Invoice no" name="inv_no" required>
	</div>
	<div class="form-group col-2">
	    <label style="width:100px;" for="dat">Invoice Date :</label>
		
	    <input style="width:150px;" class="rounded" type="date" id="invdat" name="invdat"  required>
	</div>
	<div class="form-group col-3">
	    <label>Buyer's Name :</label>
	    <select style="width:250px;" class="rou" id="buyrname" name="buyrname" required>
	    <option value="" disabled selected hidden>Please Choose a Buyer...</option>
		   <?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 col-5">
	    <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>
<table id="item_table" class="table table-condensed">
<tr id="row0">
	<td>
		<div class="form-group">
		    <label  style="width:120px;"for="finalProdct"><b>Final Product:</b></label>
		    <input style="width:200px;" type="text" class="rounded" id="finalProdctVal0" name="finalProdctVal[]" readonly required>
		    <input type="hidden" class="rounded" style="width:100px;"  id="adminId0" name="adminId[]">
			<input type="hidden" class="rounded" style="width:100px;"  id="is_single0" name="is_single[]">
			<button id="opentablbtn0" onclick="openTableM(0)" type="button" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Add Final Product" style="background-color: #b134eb;"><i class="ace-icon fa fa-plus bigger-130"></i></button>
		</div>
	</td>
	<td>
		<div class="form-group">
				<input type="hidden" class="rounded" id="boxescat0" name="boxescat[]">
			 	<label for="boxescatval">Available Boxes/Quantity :</label>
        <select style="width:150px;" class="rou" id="boxescatval0" name="boxescatval[]" onchange="setQauntityPerBox(0)" required>
        </select>
		</div>
	</td>
	<td>
		<div class="form-group">
		    <label>Quantity Per Box:</label>
		    <select style="width:150px;" class="rou" id="totalQty0" disabled>
        </select>
		    <label id="totalQtyType0"></label>
		</div>
	</td>
	<td>
		<div class="form-group">
			<label style="width:105px;" for="qty">No. of Boxes to Send:</label>
			<input type="text" style="width:150px;" maxlength="6" class="rounded" id="totalBoxes0" name="totalBoxes[]" pattern="^(0|[1-9][0-9]*)$" value ="0">
		</div>
	</td>
	<td><button type="button" name="addpp" id="addpp" class="btn btn-success" style="margin-top: 25%;">Add More</button></td>
	
</tr>
</table>
    <button type="submit"  class="btn btn-primary" id = "stockSubmit" name="submit">Submit</button>
    <!-- <button class="btn btn-danger">Cancel</button> -->
</form>
</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>

<!-- 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">Select Final Product</h4>
		 <button type="button" class="close" data-dismiss="modal">&times;</button>
       	<input type="hidden" id="maintablerow" readonly>
      </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 class="center">
						
					</th>
					<th>Sr. No</th>
					<th>Sent From</th>
					<th>Final Product</th>
					<th>Quantity</th>	
					<th>Quantity Type</th>
					<th>#Total Boxes</th>
					<th>Select</th>
					<th style="display: none;"></th>
					<th style="display: none;"></th>
					<th style="display: none;"></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 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
				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 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 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
				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 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" id="t<?php echo $row['ids'];?>">
				<td class="center">
					
					<p style="display: none"><?php echo $row['ids'];?></p>
				</td>
				<td>
					<p><?php echo $row['id'];?></p>
				</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>
					<button type="button" class="btn btn-primary sendbtn"><i class="ace-icon fa fa-check bigger-130"></i></button>
				</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>
				
			</tr>
			<?php
					}
				}

			?>
			</tbody>
		</table>
	  </div>
      <div class="modal-footer">
       
      </div>
    </div>

  </div>
</div>

</body>

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

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

	addMoreItems(t);

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

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

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

		var mainrowId = $('#maintablerow').val();
		if($('#adminId'+mainrowId).val() !=''){
			var tablerow = document.getElementById('t'+$('#adminId'+mainrowId).val())
			
			if(!$('#t'+$('#adminId'+mainrowId).val()).is(':visible')){
				tablerow.style.display = "revert";
			}
			
		}

		var adminIds = data[0].trim();
		$('#adminId'+mainrowId).val(adminIds);
		$('#finalProdctVal'+mainrowId).val(data[3].trim());
		$('#is_single'+mainrowId).val(data[10].trim());
		
		$.ajax( {
    url: '../controller/stock_controller.php',
    type: 'POST',
    data: 'id='+adminIds+'&type=viewStock',

    success: function(data){
    	
	    if(data.status == true){
	    	$('#boxescatval'+mainrowId).empty();
	    	$('#totalQty'+mainrowId).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;
	     		}
	     		
			    $('#boxescatval'+mainrowId).append($("<option />").val(item.ids).text(item.totalBoxs));
					$('#totalQty'+mainrowId).append($("<option />").val(item.ids).text(finalqty));
		    });


	  	}
      
    },
    error: function(r) {
      console.log(r);
      $('#boxescatval'+mainrowId).empty();
      $('#totalQty'+mainrowId).empty();
    }
   });

		
		$('#totalQtyType'+mainrowId).html(data[5].trim());
		
		$('#tableModal').modal('hide');	

	});

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

		var rowid =$("#item_table").find("tr").last().attr('id').replace("row", "");
	
		if(parseInt($('#totalBoxes'+rowid).val()) == 0){
			alert('Boxes cannot be 0');
			document.getElementById("stockSubmit").disabled=false;
		}else if(parseInt($('#totalBoxes'+rowid).val()) > parseInt($("#boxescatval"+rowid+" option:selected").text())){
			alert('Sending boxes cannot exceed available amount of boxes');
			document.getElementById("stockSubmit").disabled=false;
		}else{
		$('#boxescat'+rowid).val($('#boxescatval'+rowid).val());
		var formData = new FormData(this);
		formData.append('type','multiStockSend');
		formData.append('userId',userid);

		var url='../controller/stock_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(data.msg); 
		        window.location.reload();
	      	  }else{
	      	  	alert(data.msg); 
	      	  	document.getElementById("stockSubmit").disabled=false;
	      	  }
	        },
	        error: function(r) {
	          alert('Unable to Add Items'); 
	          document.getElementById("stockSubmit").disabled=false;
	        }
	      } );
	}
   	
	});

	$("#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');
				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 openTableM(rowid){
	$('#maintablerow').val(rowid);
	$('#tableModal').modal('show');

}


function disableDivs(rowid) {
	console.log('disableRowId',rowid);
	
	$('#totalBoxes'+rowid).prop('readonly',true);
	document.getElementById('boxescatval'+rowid).disabled=true;
}

function enableDivs(rowid) {
	console.log('enableRowId',rowid);
	
	$('#totalBoxes'+rowid).prop('readonly',false);
	document.getElementById('boxescatval'+rowid).disabled=false;
}

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

	if(formname == 'user_form'){
		$('#mesg').text('');
		$('#add_product').show();
	}else if(formname == 'user_form2'){
		$('#mesg2').text('');
		$('#productype').show();
	}
}

function addMoreItems(table){
	var i=1;
	$('#addpp').click(function(){
		var rowid =$("#item_table").find("tr").last().attr('id').replace("row", "");
		if($('#totalQty'+rowid).val() ==''){
			alert('First please select a final product to add more');
		}else{

			if(parseInt($('#totalBoxes'+rowid).val()) == 0){
				alert('Boxes cannot be 0');
				
			}else if(parseInt($('#totalBoxes'+rowid).val()) > parseInt($("#boxescatval"+rowid+" option:selected").text())){
				alert('Sending boxes cannot exceed available amount of boxes');
			}else{
				var tablerow = document.getElementById('t'+$('#adminId'+rowid).val())
				if(tablerow != null){
					tablerow.style.display ="none";
				}
				$('#boxescat'+rowid).val($('#boxescatval'+rowid).val());
				i++;                                                
				$('#item_table').append('<tr id="row'+i+'"><td><div class="form-group"> <label style="width:120px;"for="finalProdct"><b>Final Product:</b></label> <input style="width:200px;" type="text" class="rounded" id="finalProdctVal'+i+'" name="finalProdctVal[]" readonly required> <input type="hidden" class="rounded" style="width:100px;" id="adminId'+i+'" name="adminId[]"><input type="hidden" class="rounded" style="width:100px;"  id="is_single'+i+'" name="is_single[]"><button id="opentablbtn'+i+'" onclick="openTableM('+i+')" type="button" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Add Final Product" style="background-color: #b134eb;"><i class="ace-icon fa fa-plus bigger-130"></i></button></div></td><td><div class="form-group"> <input type="hidden" class="rounded" id="boxescat'+i+'" name="boxescat[]"><label for="boxescat">Available Boxes/Quantity :</label> <select style="width:150px;" class="rou" id="boxescatval'+i+'" name="boxescatval[]" onchange="setQauntityPerBox('+i+')" required> </select></div></td><td><div class="form-group"> <label>Quantity Per Box:</label> <select style="width:150px;" class="rou" id="totalQty'+i+'" disabled></select><label id="totalQtyType'+i+'"></label></div></td><td><div class="form-group"><label style="width:105px;" for="qty">No. of Boxes to Send:</label><input type="text" style="width:150px;" maxlength="6" class="rounded" id="totalBoxes'+i+'" name="totalBoxes[]" pattern="^(0|[1-9][0-9]*)$" value ="0"></div></td><td><button name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');

				/*var balqty = totalqt - totalsendngQty;
				
				if(balqty != 0 && confirm('Do you want to send remaining balance quantity?')){
					if(selectedValue == "1" || selectedValue == "3")
					{
						balqty = balqty/1000;
					}
					$('#adminId'+i).val($('#adminId'+rowid).val());
					$('#finalProdctVal'+i).val($('#finalProdctVal'+rowid).val());
					var totalBoxsmore = parseFloat($('#totalBoxes'+rowid).val());
					if(totalBoxsmore > 0){
						var balboxes = outofboxes - totalBoxsmore;
						$('#outofboxes'+i).html('out of '+balboxes);
					}
					$('#totalQty'+i).val(balqty);

					$('#totalQtyType'+i).html($('#totalQtyType'+rowid).html());
					
					$('#qtytypeId'+i).val($('#qtytypeId'+rowid).val());

					document.getElementById('opentablbtn'+i).disabled = true;
					
					changefunc(i);
				}*/
				document.getElementById('opentablbtn'+rowid).disabled = true;
				disableDivs(rowid);
				
			}
			
		}
		 
	});
	$(document).on('click','.btn_remove',function(){
		var button_id=$(this).attr("id");

		var adminId = 't'+$('#adminId'+button_id).val();
		
		$("#row"+button_id+"").remove();

		var table = document.getElementById('item_table');	

		var rowLength = table.rows.length;

		var isPresent = false;

		for(var i=0; i<rowLength; i+=1){
			var row = table.rows[i];

			var rowid = row.id.replace("row", "");
			
			if('t'+$('#adminId'+i).val() == adminId){
				isPresent =true;
				break;
			}
		}

		console.log('Ispresent',isPresent);
		if(!isPresent){
			document.getElementById(adminId).style.display ="revert";
		}
		
		var lastrowid =$("#item_table").find("tr").last().attr('id').replace("row", "");
		
		enableDivs(lastrowid);
		document.getElementById('opentablbtn'+lastrowid).disabled = false;

	});
}

function setQauntityPerBox(rowid){
	$('#totalQty'+rowid).val($('#boxescatval'+rowid).val());
}

</script>
</html>