<?php
require_once("../includes/config.php");
$arrstatus = getFullStatus("",$link1);
$docid=base64_decode($_REQUEST['id']);
 
//// Requisition details
$sql_locdet="SELECT * FROM requisition_master where system_ref_no='".$docid."'";
$res_locdet=mysqli_query($link1,$sql_locdet);
$row_locdet=mysqli_fetch_assoc($res_locdet);
@extract($_POST);
////// if we want to save allocate Qty.
if($_POST){

	///// make a string token
	$messageIdent = md5($docid . $row_locdet['request_to'] . $row_locdet['request_from']);
	//and check it against the stored value:
	$sessionMessageIdent = isset($_SESSION['allocatestock'])?$_SESSION['allocatestock']:'';
	if($messageIdent!=$sessionMessageIdent){//if its different:          
		//save the session var:
		$_SESSION['allocatestock'] = $messageIdent;
	if($_POST['save']=="Save"){///////////////// If we want to save ////////////////////////////////
		////// INITIALIZE PARAMETER/////////////////////////
	    mysqli_autocommit($link1, false);
	    $flag = true;
	    $err_msg = "";
		////// Create document no for allocate master ////
		
		$row_doc = mysqli_fetch_array(mysqli_query($link1, "SELECT doc_str,doc_count FROM document_counter where  doc_type='AS' and location_code='".$row_locdet['request_to']."'"));
		if($row_doc['doc_str']){
			$doc_no = $row_doc['doc_count'] + 1;
			$document_no = $row_doc['doc_str'].str_pad($doc_no,5,0,STR_PAD_LEFT);
			////// Insert details into allocate master table ///// 
			
			$req_res1 = mysqli_query($link1,"INSERT INTO allocate_master set document_type='SRS',document_no='".$document_no."', document_date='".$today."',document_time='".$currtime."',to_location='".$row_locdet['request_from']."',from_location='".$row_locdet['request_to']."',ref_no='".$row_locdet['system_ref_no']."',entry_by='".$_SESSION['userid']."',status='9', planning_no = '".$planning."' ");
			//// check if query is not executed
			if (!$req_res1) {
				$flag = false;
				$err_msg = "Error Code1: ".mysqli_error($link1);
			}
			//update document count
			
			$req_res5 = mysqli_query($link1,"UPDATE document_counter set doc_count = doc_count+1 where doc_type='AS' and location_code='".$row_locdet['request_to']."'");
			
			if (!$req_res5) {
				$flag = false;
				$err_msg = "Error Code5: ".mysqli_error($link1);
			}
			$tot_reqqty=0;
			$tot_aloqty=0;
			$tot_qty=0;
			///// Insert in item data by picking each data row one by one
			
			$res_rqd = mysqli_query($link1,"SELECT id,req_qty,allocate_qty,purchase_unit FROM requisition_data where system_ref_no='".$docid."'");
			while($row_rqd = mysqli_fetch_assoc($res_rqd)){
				$part = "partcode".$row_rqd['id'];
				$aloc_qty = "allocate_qt_val".$row_rqd['id'];
				/////check inventory again
				$avlqty = getInventory($row_locdet['request_to'],$_POST[$part],$st1,$link1);
				if($avlqty){}else{ $avlqty=0;}
				if($avlqty >= $_POST[$aloc_qty]){
				// insert details into allocate data table 
				if($_POST[$aloc_qty]>0){
				$qr_flag = "";
				if($st1=='ok_qty'){
					$qr_flag = " allocate_qty='".$_POST[$aloc_qty]."', ";
				}else if($st1=='damage_qty'){
					$qr_flag = "  allocate_dmgqty='".$_POST[$aloc_qty]."',  ";
				}else if($st1=='faulty_qty'){
					$qr_flag = "  allocate_faultyqty='".$_POST[$aloc_qty]."',  ";
				}else{
					$qr_flag = "  allocate_prejqty='".$_POST[$aloc_qty]."',  ";
				}
				
				$req_res2 = mysqli_query($link1,"INSERT INTO allocate_data set document_no='".$document_no."', partcode='".$_POST[$part]."',    $qr_flag   purchase_unit='".$row_rqd['purchase_unit']."',conversion_factor='".$row_rqd['conversion_factor']."' ");
				//// check if query is not executed
				if (!$req_res2) {
					$flag = false;
					$err_msg = "Error Code2: ".mysqli_error($link1);
				}
				}
				////////////// update in requisition data
				
				$req_res21 = mysqli_query($link1,"UPDATE requisition_data set allocate_qty = allocate_qty+'".$_POST[$aloc_qty]."' where id='".$row_rqd['id']."'");
				
				//// check if query is not executed
				if (!$req_res21) {
					$flag = false;
					$err_msg = "Error Code21: ".mysqli_error($link1);
				}
				//----------------------------- inventory upadate------------------------//
    			$sql_invt = "UPDATE inventory_status set $st1 = $st1 - '".$_POST[$aloc_qty]."',updatedate='" . $datetime . "' where partcode='".$_POST[$part]."' and location_code='".$row_locdet['request_to']."' and  $st1 >= '".$_POST[$aloc_qty]."'";
				
   				$res_invt = mysqli_query($link1,$sql_invt);
			  	//// check if query is not executed
			  	if (!$res_invt) {
					$flag = false;
					$err_msg = "Error details5: " . mysqli_error($link1) . ".";
				}
				////check if requisition is against a job no.
				if($row_locdet['req_type']=="JC"){
					////////////// update in job card data
					
					$req_res_job = mysqli_query($link1,"UPDATE jobcard_data set allocate_qty = allocate_qty+'".$_POST[$aloc_qty]."',balance_qty = balance_qty-'".$_POST[$aloc_qty]."' where system_ref_no='".$row_locdet['ref_no']."' and partcode='".$_POST[$part]."'");
					
					//// check if query is not executed
					if (!$req_res_job) {
						$flag = false;
						$err_msg = "Error Code51: ".mysqli_error($link1);
					}
				}
				////// insert in stock ledger table////
				if($_POST[$aloc_qty]>0){
				$result = stockLedger($document_no,$row_locdet['entry_date'],$_POST[$part],$row_locdet['request_to'],$row_locdet['request_from'],"OUT","OK","ALLOCATE","ADD",$_POST[$aloc_qty],"0.00",$_SESSION['userid'],$today,$currtime,$ip,$link1,$flag);
				$expld = explode("~",$result);
				$flag = $expld[0];
				$err_msg = $expld[1];
				}
				$tot_reqqty += $row_rqd['req_qty'];
				$tot_aloqty += $row_rqd['allocate_qty']+$_POST[$aloc_qty];
				$tot_qty +=$_POST[$aloc_qty];
				}else{
					$flag = false;
					$err_msg = "Error details 51_1: Qty is not available as you entered for ".$_POST[$part]."";
				}
			}///// close while loop
			//// check dispatch qty should not be zero
			if($tot_qty == 0){
				$flag = false;
				$err_msg = "Error details 5.1: You are dispatch 0 qty";
			}
			/////// Upadate status in allocation master table///////
			if($tot_reqqty == $tot_aloqty){
			
				$req_res3 = mysqli_query($link1,"UPDATE requisition_master set status = '9' where system_ref_no='".$docid."' ");
			}else{
			
				$req_res3 = mysqli_query($link1,"UPDATE requisition_master set status = '8' where system_ref_no='".$docid."' ");
			}
			if (!$req_res3) {
				$flag = false;
				$err_msg = "Error Code3: ".mysqli_error($link1);
			}
		}else{
			$flag = false;
			$err_msg = "Error Code2.1 :Document series not found for location.";		
		}
		////// insert in activity table////
		$flag =	dailyActivity($_SESSION['userid'],$document_no,"ALLOCATE","ADD",$ip,$link1,$flag);
		///// check both master and data query are successfully executed
		if ($flag) {
			mysqli_commit($link1);
			$msg = "Stock is allocated with ref. no. ".$document_no;
			$cflag="success";
			$cmsg = "Success";
		} else {
			mysqli_rollback($link1);
			$msg = "Request could not be processed ".$err_msg.". Please try again.";
			$cflag="danger";
			$cmsg = "Failed";
		} 
		mysqli_close($link1);
	}
	 if($_POST['save_and_close']=="Save and Close"){///////////////// If we want to save and close ////////////////////////////////
		////// INITIALIZE PARAMETER/////////////////////////
	    mysqli_autocommit($link1, false);
	    $flag = true;
	    $err_msg = "";
		////// Create document no for allocate master ////
		
		$row_doc = mysqli_fetch_array(mysqli_query($link1, "SELECT doc_str,doc_count FROM document_counter where  doc_type='AS' and location_code='".$row_locdet['request_to']."'"));
		if($row_doc['doc_str']){
			$doc_no = $row_doc['doc_count'] + 1;
			$document_no = $row_doc['doc_str'].str_pad($doc_no,5,0,STR_PAD_LEFT);
			////// Insert details into allocate master table ///// 
			
			$req_res1 = mysqli_query($link1,"INSERT INTO allocate_master set document_type='SRS',document_no='".$document_no."', document_date='".$today."',document_time='".$currtime."',to_location='".$row_locdet['request_from']."',from_location='".$row_locdet['request_to']."',ref_no='".$row_locdet['system_ref_no']."',entry_by='".$_SESSION['userid']."',status='9' ");
			
			//// check if query is not executed
			if (!$req_res1) {
				$flag = false;
				$err_msg = "Error Code1: ".mysqli_error($link1);
			}
			//update document count
			
			$req_res5 = mysqli_query($link1,"UPDATE document_counter set doc_count = doc_count+1 where doc_type='AS' and location_code='".$row_locdet['request_to']."'");
			
			if (!$req_res5) {
				$flag = false;
				$err_msg = "Error Code5: ".mysqli_error($link1);
			}
			$tot_qty=0;
			///// Insert in item data by picking each data row one by one
			
			$res_rqd = mysqli_query($link1,"SELECT id,req_qty,allocate_qty,purchase_unit FROM requisition_data where system_ref_no='".$docid."'");
			while($row_rqd = mysqli_fetch_assoc($res_rqd)){
				$part = "partcode".$row_rqd['id'];
				$aloc_qty = "allocate_qt_val".$row_rqd['id'];
				/////check inventory again
				$avlqty = getInventory($row_locdet['request_to'],$_POST[$part],$st1,$link1);
				if($avlqty){}else{ $avlqty=0;}
				if($avlqty >= $_POST[$aloc_qty]){
				// insert details into allocate data table
				if($_POST[$aloc_qty]>0){
				
				$qr_flag = "";
				if($st1=='ok_qty'){
					$qr_flag = " allocate_qty='".$_POST[$aloc_qty]."', ";
				}else if($st1=='damage_qty'){
					$qr_flag = "  allocate_dmgqty='".$_POST[$aloc_qty]."',  ";
				}else if($st1=='faulty_qty'){
					$qr_flag = "  allocate_faultyqty='".$_POST[$aloc_qty]."',  ";
				}else{
					$qr_flag = "  allocate_prejqty='".$_POST[$aloc_qty]."',  ";
				}
				
				$req_res2 = mysqli_query($link1,"INSERT INTO allocate_data set document_no='".$document_no."', partcode='".$_POST[$part]."',    $qr_flag  purchase_unit='".$row_rqd['purchase_unit']."',conversion_factor='".$row_rqd['conversion_factor']."' ");
				//// check if query is not executed
				if (!$req_res2) {
					$flag = false;
					$err_msg = "Error Code2: ".mysqli_error($link1);
				}
				}
				////////////// update in requisition data
				
				$req_res21 = mysqli_query($link1,"UPDATE requisition_data set allocate_qty = allocate_qty+'".$_POST[$aloc_qty]."' where id='".$row_rqd['id']."'");
				//// check if query is not executed
				if (!$req_res21) {
					$flag = false;
					$err_msg = "Error Code21: ".mysqli_error($link1);
				}
				//----------------------------- inventory upadate------------------------//
    			$sql_invt = "UPDATE inventory_status set $st1 = $st1 - '".$_POST[$aloc_qty]."',updatedate='" . $datetime . "' where partcode='".$_POST[$part]."' and location_code='".$row_locdet['request_to']."' and  $st1 >= '".$_POST[$aloc_qty]."'";
				
   				$res_invt = mysqli_query($link1,$sql_invt);
			  	//// check if query is not executed
			  	if (!$res_invt) {
					$flag = false;
					$err_msg = "Error details5: " . mysqli_error($link1) . ".";
				}
				////check if requisition is against a job no.
				if($row_locdet['req_type']=="JC"){
					////////////// update in job card data
					
					$req_res_job = mysqli_query($link1,"UPDATE jobcard_data set allocate_qty = allocate_qty+'".$_POST[$aloc_qty]."',balance_qty = balance_qty-'".$_POST[$aloc_qty]."' where system_ref_no='".$row_locdet['ref_no']."' and partcode='".$_POST[$part]."'");
					//// check if query is not executed
					if (!$req_res_job) {
						$flag = false;
						$err_msg = "Error Code 51: ".mysqli_error($link1);
					}
				}
				////// insert in stock ledger table////
				if($_POST[$aloc_qty]>0){
				$result = stockLedger($document_no,$row_locdet['entry_date'],$_POST[$part],$row_locdet['request_to'],$row_locdet['request_from'],"OUT","OK","ALLOCATE","ADD",$_POST[$aloc_qty],"0.00",$_SESSION['userid'],$today,$currtime,$ip,$link1,$flag);
				$expld = explode("~",$result);
				$flag = $expld[0];
				$err_msg = $expld[1];
				}
				//$tot_reqqty += $row_rqd['req_qty'];
				//$tot_aloqty += $row_rqd['allocate_qty']+$_POST[$aloc_qty];
				}else{
					$flag = false;
					$err_msg = "Error details 51_2: Qty is not available as you entered for ".$_POST[$part]."";
				}
				$tot_qty += $_POST[$aloc_qty];
			}//// close for loop
			//// check dispatch qty should not be zero
			if($tot_qty == 0){
				$flag = false;
				$err_msg = "Error details5.1: You are dispatch 0 qty";
			}
			/////// Upadate status in allocation master table///////
			$req_res3 = mysqli_query($link1,"UPDATE requisition_master set status = '9' where system_ref_no='".$docid."' ");
			if (!$req_res3) {
				$flag = false;
				$err_msg = "Error Code3: ".mysqli_error($link1);
			}
		}else{
			$flag = false;
			$err_msg = "Error Code2.1 :Document series not found for allocate stock.";		
		}
		////// insert in activity table////
		$flag =	dailyActivity($_SESSION['userid'],$document_no,"ALLOCATE","ADD",$ip,$link1,$flag);
		///// check both master and data query are successfully executed
		if ($flag) {
			mysqli_commit($link1);
			$msg = "Stock is allocated with ref. no. ".$document_no;
			$cflag="success";
			$cmsg = "Success";
		} else {
			mysqli_rollback($link1);
			$msg = "Request could not be processed ".$err_msg.". Please try again.";
			$cflag="danger";
			$cmsg = "Failed";
		} 
		mysqli_close($link1);
	}
	
	} else {
		//you've sent this already!
		$msg = "Re-submission is not allowed";
		$cflag="warning";
		$cmsg = "Warning";
	}
	
    header("location:allocate_stock_list.php?msg=".$msg."&chkflag=".$cflag."&chkmsg=".$cmsg."".$pagenav);
    exit;	
}
?>
<!DOCTYPE html>
<html>
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?=siteTitle?></title>
  <link rel="shortcut icon" href="../images/titleimg.png" type="image/png">
  <script src="../js/jquery.js"></script>
  <?php 
	 include("../includes/fontawesome.html");
	 include("../includes/main_css.html"); 
	 include("../includes/bootstrap.html");
	 include("../includes/datatables.html");
  ?>
  <script>
  $(document).ready(function(){
	var spinner = $('#loader');
        $("#frm1").validate({
		  submitHandler: function (form) {
			if(!this.wasSent){
				this.wasSent = true;
				$(':submit', form).val('Please wait...')
								  .attr('disabled', 'disabled')
								  .addClass('disabled');
				spinner.show();				  
				form.submit();
			} else {
				return false;
			}
          }
		});
	$('.number').on('input', function() {
		match = (/(\d{0,6})[^.]*((?:\.\d{0,6})?)/g).exec(this.value.replace(/[^\d.]/g, ''));
		this.value = match[1] + match[2];
  	});
  });
function checkMaxQty(indx){
	var max_cnt = document.getElementById("maxcnt").value;
	var flg=1;
	for(var i=1; i<max_cnt; i++){
		if(document.getElementById("rq_qt"+i).value){
			var rq_qt_dt = parseFloat(document.getElementById("rq_qt"+i).value,6);
		}else{
			var rq_qt_dt = 0;
		}
		if(document.getElementById("allocate_qt_val"+i).value){
			var val = parseFloat(document.getElementById("allocate_qt_val"+i).value,6);
		}else{
			var val = 0;
		}
		if(document.getElementById("avl_qty"+i).value){
			var avlqty = parseFloat(document.getElementById("avl_qty"+i).value,6);
		}else{
			var avlqty = 0;
		}
		//alert(rq_qt_dt +"<"+ val);
		if(rq_qt_dt < val){
			document.getElementById("error_msg"+i).innerHTML = "Allocate qty should not be more than requested qty.";
			document.getElementById("error_msg"+i).style.display = "block";
			flg *=0;
		}else if(avlqty < val){
			document.getElementById("error_msg"+i).innerHTML = "Stock is not available for this part.";
			document.getElementById("error_msg"+i).style.display = "block";
			flg *=0;
		}else{
			document.getElementById("error_msg"+i).innerHTML = "";
			document.getElementById("error_msg"+i).style.display = "none";	
			flg *=1;
		}
	}
	/////
	if(flg==1){
		document.getElementById("save").disabled = false;
		document.getElementById("save_and_close").disabled = false;
		checkMOQQty(indx);
	}else{
		document.getElementById("save").disabled = true;
		document.getElementById("save_and_close").disabled = true;
	}
}

	/////// check MOQ qty ///////
	function checkMOQQty(indx){
		var moq_qty = parseFloat(document.getElementById("moq[" + indx + "]").value);
		var req_qty = parseFloat(document.getElementById("allocate_qt_val" + indx).value);
		var abl_qty = parseFloat(document.getElementById("avl_qty" + indx).value);
		var part = document.getElementById("partcode" + indx).value;
				
		if(moq_qty >= (abl_qty - req_qty)){
			alert("Are you sure? You reached your 15 Days MSL Mount Qty for Partcode = " + part + " and MSLQ = "+moq_qty);
		}else{
		}
	}
				
  </script>
  <script src="../js/jquery.validate.js"></script>
  <link href="../css/loader.css" rel="stylesheet"/>
  </head>
  <body>
  <div class="container-fluid">
    <div class="row content">
    <?php 
    include("../includes/leftnav_admin.php");
    ?>
      <div class="<?=$screenwidth?>">
        <h2 align="center"><i class="fa <?=$fa_icon?>"></i> Allocate Stock Against Requisition</h2>
      	<h4 align="center"><?php echo "( ".$row_locdet['system_ref_no']." )"; ?></h4>
        <?php if($_REQUEST['msg']!=''){?>
        <div class="alert alert-<?php echo $_REQUEST['chkflag'];?> alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            <strong><?php echo $_REQUEST['chkmsg'];?>!</strong>&nbsp;&nbsp;<?=$_REQUEST['msg']?>.
        </div>
      <?php }?>
        <div class="form-group"  id="page-wrap" style="margin-left:10px;" >
	  <form id="frm1" name="frm1" class="form-horizontal" action="" method="post">
   <div class="panel-group">
    <div class="panel panel-success table-responsive">
        <div class="panel-heading"><i class="fa fa-newspaper-o fa-lg"></i>&nbsp;&nbsp;Requisition Details</div>
         <div class="panel-body">
          <table class="table table-bordered" width="100%">
            <tbody>
              <tr>
                <td width="20%"><label class="control-label">Request From</label></td>
                <td width="30%"><?php echo getAnyDetails($row_locdet['request_from'],"locationname","location_code","location_master",$link1)." (".$row_locdet['request_from'].")"; ?></td>
				<td width="20%"><label class="control-label">Request To</label></td>
                <td width="30%"><?php echo getAnyDetails($row_locdet['request_to'],"locationname","location_code","location_master",$link1)." (".$row_locdet['request_to'].")"; ?></td>
              </tr>
              <tr>
                <td width="20%"><label class="control-label">Create By</label></td>
                <td width="30%"><?=getAnyDetails($row_locdet['entry_by'],"name","username","admin_users",$link1)?></td>
                <td width="20%"><label class="control-label">Create Date</label></td>
                <td width="30%"><?=dt_format($row_locdet['entry_date'])?></td>
              </tr>
			  <tr>
                <td width="20%"><label class="control-label">Request Type</label></td>
                <td width="30%"><?=$row_locdet['req_type'];?></td>
                <td width="20%"><label class="control-label">Reference No.</label></td>
                <td width="30%"><?=$row_locdet['ref_no']?></td>
              </tr>
			  <tr>
                <td width="20%"><label class="control-label">Person Name</label></td>
                <td width="30%"><?=$row_locdet['person_name'];?></td>
				<td width="20%"><label class="control-label">Status</label></td>
                <td width="30%"><?=$arrstatus[$row_locdet['status']];?></td>
              </tr>
			  <tr>
			  	<td width="20%"><label class="control-label">Planning No.</label></td>
                <td width="30%"><?=$row_locdet['planning_no']?><input type="hidden" name="planning" id="planning" value="<?=$row_locdet['planning_no']?>" /> </td>
				<td width="20%"><label class="control-label">Remark</label></td>
                <td width="30%"><?=$row_locdet['remark']?></td>
              </tr>
              <?php if(isset($row_locdet['updateby'])){?>
              <tr>
                <td width="20%"><label class="control-label">Update By</label></td>
                <td width="30%"><?=getAnyDetails($row_locdet['updateby'],"name","username","admin_users",$link1)?></td>
                <td width="20%"><label class="control-label">Update Date</label></td>
                <td width="30%"><?=dt_format($row_locdet['updatedate'])?></td>
              </tr>
              <?php }?>
              <?php if(isset($row_locdet['cancel_by'])){?>
              <tr>
                <td width="20%"><label class="control-label">Cancel By</label></td>
                <td width="30%"><?=getAnyDetails($row_locdet['cancel_by'],"name","username","admin_users",$link1)?></td>
                <td width="20%"><label class="control-label">Cancel Date</label></td>
                <td width="30%"><?=dt_format($row_locdet['cancel_date'])?></td>
              </tr>
              <tr>
                <td width="20%"><label class="control-label">Cancel Remark</label></td>
                <td colspan="3"><?=$row_locdet['cancel_remark']?></td>
              </tr>
              <?php }?>
              <?php 
				$row_app = mysqli_fetch_assoc(mysqli_query($link1,"select action_by,action_taken,action_date,action_remark from  approval_activity where ref_no='".$docid."'"));
			   if($row_app['action_by']){
			   ?>
              <tr>
                <td width="20%"><label class="control-label">Approval By</label></td>
                <td width="30%"><?=getAnyDetails($row_app['action_by'],"name","username","admin_users",$link1)?></td>
                <td width="20%"><label class="control-label">Approval Date</label></td>
                <td width="30%"><?=dt_format($row_app['action_date'])?></td>
              </tr>
              <tr>
                <td width="20%"><label class="control-label">Approval Action</label></td>
                <td width="30%"><?=$arrstatus[$row_app['action_taken']]?></td>
                <td width="20%"><label class="control-label">Approval Remark</label></td>
                <td width="30%"><?=$row_app['action_remark']?></td>
              </tr>
              <?php }?>
            </tbody>
          </table>
        </div><!--close panel body-->
    </div><!--close panel-->
    <div class="panel panel-success table-responsive">
        <div class="panel-heading"><i class="fa fa-cubes fa-lg"></i>&nbsp;&nbsp;Allocate Stock</div>
         <div class="panel-body">
          <table class="table table-bordered" width="100%">
            <thead>
                <tr class="<?=$tableheadcolor?>">
                    <th width="28%">Part Name</th>
                    <th width="10%">Request Qty</th>
					<th width="10%">Stock Type</th>
                    <th width="10%">Pending Qty</th>
                    <th width="13%">Allocate Qty</th>
                    <th width="10%">Avl Qty</th>
					<th width="12%">Purchase Unit</th>
                    <th width="17%">Remark</th>
                    
                </tr>
            </thead>
            <tbody>
			<?php
			/// select requistion data table info
			$tot_req_qty=0;
			//$tot_allocate_qty=0;
			$k=1;
			$res_bom = mysqli_query($link1,"SELECT * FROM requisition_data where system_ref_no='".$docid."'");
			while($row_bom = mysqli_fetch_assoc($res_bom)){
			$row_locdet['request_to']; $getstock = getInventory($row_locdet['request_to'],$row_bom['partcode'],$row_bom['stock_type'],$link1);
			?>
              <tr>
                <td>
				<?php 
					$prt = explode("~",getAnyDetails($row_bom['partcode'],"part_name,moq","partcode","partcode_master",$link1)); echo $prt[0]." (".$row_bom['partcode'].")";
					///// find MSL Qty ////
					$sql_psc = "SELECT SUM(qty) AS tot FROM stock_ledger WHERE from_party = '".$row_locdet['request_to']."' and partcode = '".$row_bom['partcode']."'  and stock_transfer LIKE 'OUT' and (reference_no NOT LIKE 'GP/%' AND reference_no NOT LIKE 'RGP/%') and reference_date >= DATE_SUB(CURDATE(), INTERVAL 90 DAY) ";
					//echo $sql_psc;	
					$res_psc = mysqli_query($link1,$sql_psc) or die(mysqli_error($link1));
					$tt = mysqli_fetch_array($res_psc);
					
					//echo $sql_psc;
					$l = 0.00;
					$lll = 0.00;
					$mmm = 0.00;
					$nnn = 0.00;
					if($tt['tot']!=0 && $tt['tot']!=""){
						$lll = ($tt['tot']/90);
						$mmm = ($lll*30);
						$l = ($mmm/2);
					}else{
						$l = "";
					}
					
					
				?><input type="hidden" name="partcode<?=$row_bom['id']?>" id="partcode<?=$k?>" value="<?=$row_bom['partcode']?>"><input type="hidden" name="moq[<?=$k?>]" id="moq[<?=$k?>]" value="<?=$l;?>" /></td>
                <td align="right"><?=$row_bom['req_qty']?><input type="hidden" name="rq_qt<?=$row_bom['id']?>" id="rq_qt<?=$k?>" value="<?=($row_bom['req_qty']-$row_bom['allocate_qty'])?>"></td>
				<td align="center">
					<?php 
						$aaa = "";
						if($row_bom['stock_type'] == 'ok_qty'){
							$aaa = "OK";
						}else if($row_bom['stock_type'] == 'damage_qty'){
							$aaa = "IQC";
						}else if($row_bom['stock_type'] == 'faulty_qty'){
							$aaa = "VR";
						}else{
							$aaa = "PR";
						}
						echo $aaa;
					?>
					<input type="hidden" name="st1" id="st1" value="<?=$row_bom['stock_type']?>" /> 
				</td>	
                <td align="right"><?=getQtyFormate(($row_bom['req_qty']-$row_bom['allocate_qty']),6)?></td>				
                <td align="right"><input type="text" class="number form-control alert-success required" onKeyUp="checkMaxQty(<?=$k?>)" name="allocate_qt_val<?=$row_bom['id']?>" id="allocate_qt_val<?=$k?>" value="" style="text-align:right" required> <div id="error_msg<?=$k?>" style="text-align:center;display:none;color:#FF0000;"></div></td>
                <td align="right"><?php if($getstock){echo $avlstk=$getstock;}else{$avlstk=0.000000; echo getQtyFormate($avlstk,6);}?><input type="hidden" name="avl_qty<?=$row_bom['id']?>" id="avl_qty<?=$k?>" value="<?=$avlstk?>"></td>
				<td><?=$row_bom['purchase_unit']?></td>
                <td><?=$row_bom['remark']?></td>
                
              </tr>
			 <?php 
				$tot_req_qty+=$row_bom['req_qty'];
				//$tot_allocate_qty+=$row_bom['allocate_qty']; 
				$k++; 
			}
			?> 
			<tr>
				<td align="right"><label class="control-label">Total</label></td>
				<td align="right"><label class="control-label"><?php echo getQtyFormate($tot_req_qty,6); ?></label></td>
				<td align="right" colspan="6"><input type="hidden" name="maxcnt" id="maxcnt" value="<?=$k?>"></td>
			</tr>
            <tr>
                <td align="center" colspan="8">
				  <button title="Save" type="submit" name="save" id="save" class="btn<?=$btncolor?>" value="Save" ><i class="fa fa-save fa-lg"></i>&nbsp;&nbsp;Save</button>
				  <button title="Save and Close" type="submit" name="save_and_close" id="save_and_close" class="btn<?=$btncolor?>" value="Save and Close" ><i class="fa fa-save fa-lg"></i>&nbsp;&nbsp;Save and Close</button>
                  <button title="Back" type="button" class="btn<?=$btncolor?>" onClick="window.location.href='allocate_stock.php?status=<?php if(isset($_REQUEST['status'])){ echo $_REQUEST['status'];}?>&request_from=<?php if(isset($_REQUEST['request_from'])){ echo $_REQUEST['request_from'];}?>&daterange=<?php if(isset($_REQUEST['daterange'])){ echo $_REQUEST['daterange'];}?><?=$pagenav?>'"><i class="fa fa-reply fa-lg"></i>&nbsp;&nbsp;Back</button>
                 </td>
             </tr>  
            </tbody>
          </table>
        </div><!--close panel body-->
    </div><!--close panel-->    
    </div><!--close panel group-->
	</form>
            
   
        </div>
        <!--End form group--> 
      </div>
      <!--End col-sm-9--> 
    </div>
    <!--End row content--> 
  </div>
  <!--End container fluid-->
  <div id="loader"></div>
  <?php
include("../includes/footer.php");
include("../includes/connection_close.php");
?>
</body>
</html>
