<?php
require_once("../includes/config.php");
$arrstatus = getFullStatus("",$link1);
$docid=base64_decode($_REQUEST['id']);
//// grn details
$sql_grn = "SELECT * FROM grn_inv_master where system_ref_no='".$docid."'";

$res_grn = mysqli_query($link1,$sql_grn);
$row_grn = mysqli_fetch_assoc($res_grn);
///// make po no string
$makepostr = "'".str_replace(",","','",$row_grn['po_no'])."'";
////// hit receive button
if(isset($_POST['receivebtn'])){
	if ($_POST['receivebtn']=='Receive'){
		///// make a string token
		$messageIdent = md5($_POST['receivebtn'] . $docid);
		//and check it against the stored value:
    	$sessionMessageIdent = isset($_SESSION['grnSession'])?$_SESSION['grnSession']:'';
    	if($messageIdent!=$sessionMessageIdent){//if its different: 
			//save the session var:
			$_SESSION['grnSession'] = $messageIdent;
			//// initialize transaction parameters
			$flag = true;
			$partial_flag = true;
			mysqli_autocommit($link1, false);
			$err_msg = "";
			$qtyflag=0;
			$totalqty=0;
			$totalpoqty=0;
			////// pick selected po items 
			
			$result_po = mysqli_query($link1,"SELECT id,system_ref_no,partcode,req_qty,pending_qty,purchase_unit FROM po_data where system_ref_no in (".$makepostr.")");
			while($post_po = mysqli_fetch_assoc($result_po)){
				
				$enteredqty = "rcv_qty".$post_po['id'];
				$invoiceqty = "inv_qty".$post_po['id'];
				
				$enteredrate = "price".$post_po['id'];
				$enteredamount = "sub_total".$post_po['id'];

				$ent_taxper = "tax_per".$post_po['id'];
				$ent_taxamt = "tax_total".$post_po['id'];
				
				$enteredlinetot = "line_total".$post_po['id'];
				$totalpoqty += $post_po['req_qty'];
				if($_POST[$enteredqty]!="0.00" && $_POST[$enteredqty]!="" && $_POST[$enteredqty]!="0"){
					$totalqty+=$_POST[$enteredqty];
					//// insert in grn inv data
										
					$req_res=mysqli_query($link1,"insert into grn_inv_data set system_ref_no='".$docid."',po_no='".$post_po['system_ref_no']."',inv_no='".$_POST['invoice_no']."',partcode='".$post_po['partcode']."',price='".$_POST[$enteredrate]."',po_qty='".$post_po['req_qty']."',inv_qty='".$_POST[$invoiceqty]."',receive_qty='".$_POST[$enteredqty]."',purchase_unit='".$post_po['purchase_unit']."',sub_total='".$_POST[$enteredamount]."',tax_per='".$_POST[$ent_taxper]."',tax_amount='".$_POST[$ent_taxamt]."',grand_total='".$_POST[$enteredlinetot]."'");
					
					//// check if query is not executed
					if (!$req_res) {
						$flag = false;
						$err_msg = "Error Code1: " . mysqli_error($link1) . ".";
					}			
					//// Update Local Purchase Data
					
					if($_POST[$enteredqty] < $post_po['pending_qty']){ 
						$sts=",pending_qty = pending_qty -'".$_POST[$enteredqty]."'";
						$partial_flag = false;
					}else{ 
						$sts=" ,pending_qty = '0'";
					}
					
					$req_res=mysqli_query($link1,"UPDATE po_data set inv_qty = inv_qty + '".$_POST[$invoiceqty]."',rec_qty = rec_qty+'".$_POST[$enteredqty]."' ".$sts." where id='".$post_po['id']."'");
					
					//// check if query is not executed
					if (!$req_res) {
						$flag = false;
						$err_msg = "Error Code2: " . mysqli_error($link1) . ".";
					}
					$qtyflag++;
				}///close if condition of engtered receive qty
			}////close while loop
			if($qtyflag!=0){
				////////////////upload file
				$filename = "attchfile";
				$file_name = $_FILES[$filename]["name"];
				//$file_basename = substr($file_name, 0, strripos($file_name, '.')); // get file extention
				$file_ext = substr($file_name, strripos($file_name, '.')); // get file name
				//////upload file
				if ($_FILES[$filename]["error"] > 0){
					$code=$_FILES[$filename]["error"];
				}
				else{
					// Rename file
					$newfilename = "grn_".$todayt.$now.$file_ext;
					move_uploaded_file($_FILES[$filename]["tmp_name"],"../doc_attach/grn/".$newfilename);
					$file="../doc_attach/grn/".$newfilename;
					chmod ($file, 0755);
				}	
				
				$req_res=mysqli_query($link1,"update grn_inv_master set inv_no='".$_POST['invoice_no']."',inv_date='".$_POST['inv_date']."',sub_total='".$_POST['sub_total']."',discount='".$_POST['discount']."',total_tax='".$_POST['tax_total']."',other_charge='".$_POST['other_charges']."',grand_total='".$_POST['grand_total']."',attach_inv='".$file."',status='15',remark='".$_POST['rcv_rmk']."',receive_date='".$today."',receive_time='".$currtime."',receive_by='".$_SESSION['userid']."',receive_ip='".$ip."' where system_ref_no='".$docid."'");
				
				//// check if query is not executed
				if (!$req_res) {
					$flag = false;
					$err_msg = "Error Code3: " . mysqli_error($link1) . ".";
				}
			}else{
				/// no receive qty
				$flag = false;
				$err_msg = "Error Code3.1: You have not received any qty.";
			}
			////Update Local Purchase master when qty is meet otherwise we have to go to close this PO manually
			/****if($totalpoqty == $totalqty){***********/
			if($partial_flag){
			
			   $req_res=mysqli_query($link1,"Update po_master set status='10' where system_ref_no in (".$makepostr.")");
			   
			   //// check if query is not executed
				if (!$req_res) {
					$flag = false;
					$err_msg = "Error Code4: " . mysqli_error($link1) . ".";
				}
			}else{
				
			   $req_res1=mysqli_query($link1,"Update po_master set status='17' where system_ref_no in (".$makepostr.")");
			   
			   //// check if query is not executed
				if (!$req_res1) {
					$flag = false;
					$err_msg = "Error Code5: " . mysqli_error($link1) . ".";
				}
			}
			////// transaction history
			
			$flag =	dailyActivity($_SESSION['userid'],$docid,"GRN","RECEIVE",$ip,$link1,$flag);
			
			///// check both master and data query are successfully executed
			if ($flag) {
				mysqli_commit($link1);
				$msg = "GRN is sucessfully processed with ref. ".$docid;
				$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";
    	}  
		///// move to parent page
    	header("location:grn_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 src="../js/jquery.validate.js"></script>
<link rel="stylesheet" href="../css/datepicker.css">
<script src="../js/bootstrap-datepicker.js"></script>
<script type="text/javascript">
$(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;
			}
		}
	});
	$('#inv_date').datepicker({
		format: "yyyy-mm-dd",
		endDate: "<?=$today?>",
        //endDate: "<?//=$today?>",
        todayHighlight: true,
		autoclose: true
	});
});
/// fill line wise value
function fillCost(indx){
	if(document.getElementById("rcv_qty"+indx+"").value){ 
		var enteredqty = document.getElementById("rcv_qty"+indx+"").value;
	}else{ 
		var enteredqty = 0.00;
	}
	if(document.getElementById("price"+indx+"").value){ 
		var enteredrate = document.getElementById("price"+indx+"").value;
	}else{ 
		var enteredrate = 0.00;
	}
	var totalamt = parseFloat(enteredqty) * parseFloat(enteredrate);
	document.getElementById("sub_total"+indx+"").value = formatCurrency(totalamt);
 	///check which tax is applicable
 	if(document.getElementById("tax_per"+indx+"").value){ 
		var igsttax = document.getElementById("tax_per"+indx+"").value;
	}else{ 
		var igsttax = 0.00;
	}
	var igsttaxamt = ( (parseFloat(igsttax) * parseFloat(totalamt) ) / 100).toFixed(2);
	var linetotal = parseFloat(totalamt)+parseFloat(igsttaxamt);
	document.getElementById("tax_total"+indx+"").value = igsttaxamt;
	document.getElementById("line_total"+indx+"").value = linetotal.toFixed(2);
	calculatetotal();
}
function calculatetotal(){
	var rowno = document.getElementById("theValue").value;
	var sum_qty = 0;
	var sum_tot = 0.00; 
	var sum_tax = 0.00; 
	var sum_base = 0.00;
	for(var i = 1; i < rowno; i++){
    	var temp_qty = "rcv_qty"+i;
		var temp_total = "line_total"+i;
		var temp_tax = "tax_total"+i;
		var temp_basetotal = "sub_total"+i;
		sum_qty += parseFloat(document.getElementById(temp_qty).value);
		sum_tot += parseFloat(document.getElementById(temp_total).value);
		sum_tax += parseFloat(document.getElementById(temp_tax).value);
		sum_base += parseFloat(document.getElementById(temp_basetotal).value);
	}
  	//document.getElementById("subtotal2").innerHTML = "<strong>"+formatCurrency(sum_base)+"&nbsp;&nbsp;</strong>";
  	/*document.getElementById("total_qty").value=sum_qty;*/
  	//document.getElementById("subtotal1").innerHTML = "<strong>"+formatCurrency(sum_tot)+"&nbsp;&nbsp;</strong>";
  	document.getElementById("sub_total").value = formatCurrency(sum_base);
  	document.getElementById("tax_total").value = formatCurrency(sum_tax);
  	if(document.getElementById("other_charges").value){
		var othchg=document.getElementById("other_charges").value;
	}else{
		var othchg=0.00;
	}
  	if(document.getElementById("discount").value){
		var tot_dscount=document.getElementById("discount").value;
	}else{ 
		var tot_dscount=0.00;
	}
	document.getElementById("grand_total").value = formatCurrency(parseFloat(sum_tot)-parseFloat(tot_dscount)+parseFloat(othchg));
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	signt = (num == (num = Math.abs (num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) 
	num = num.substring(0,num.length-(4*i+3))+''+
	num.substring(num.length-(4*i+3));
	return (((signt)?'':'-') + '' + num + '.' + cents);
}

function checkPriceInvRcb(indx){
	var inv_qty_data = document.getElementById("inv_qty"+indx).value;
	var rcb_qty_data = document.getElementById("rcv_qty"+indx).value;
	if(parseInt(rcb_qty_data) > parseInt(inv_qty_data)){
		alert("Invoice Qty is greater then Receive Qty. ");
		document.getElementById('rcv_qty'+indx).value = 0.000000;
	}else{
	
	}
}

</script>
<script src="../js/fileupload.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> GRN Details</h2>
      			<h4 align="center"><?php echo "( ".$row_grn['system_ref_no']." )"; ?></h4>
        		<div class="form-group"  id="page-wrap" style="margin-left:10px;" >
	  				<form id="frm1" name="frm1" class="form-horizontal" action="" method="post" enctype="multipart/form-data">
   					<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;GRN Details</div>
                            <div class="panel-body">
                              <table class="table table-bordered" width="100%">
                                <tbody>
                                  <tr>
                                    <td width="20%"><label class="control-label">Vendor Name</label></td>
                                    <td width="30%"><?php echo $row_grn['vendor_name']." (".$row_grn['vendor_code'].")"; ?></td>
                                    <td width="20%"><label class="control-label">Location Name</label></td>
                                    <td width="30%"><?php echo getAnyDetails($row_grn['location_code'],"locationname","location_code","location_master",$link1)." (".$row_grn['location_code'].")"; ?></td>
                                  </tr>
                                  <tr>
                                    <td width="20%"><label class="control-label">Vendor Address</label></td>
                                    <td width="30%"><?=$row_grn['vendor_address']?></td>
                                    <td width="20%"><label class="control-label">Status</label></td>
                                    <td width="30%"><?=$arrstatus[$row_grn['status']];?></td>
                                  </tr>
                                  <tr>
                                    <td width="20%"><label class="control-label">Create By</label></td>
                                    <td width="30%"><?=getAnyDetails($row_grn['entry_by'],"name","username","admin_users",$link1)." (".$row_grn['entry_by'].")";?></td>
                                    <td width="20%"><label class="control-label">Create Date</label></td>
                                    <td width="30%"><?=dt_format($row_grn['entry_date'])." | ".time_format($row_grn['entry_time']);?></td>
                                  </tr>
                                  <tr>
                                    <td width="20%"><label class="control-label">Gate Entry No.</label></td>
                                    <td width="30%"><?=$row_grn['gate_entry_no'];?></td>
                                    <td width="20%"><label class="control-label">PO No./Ref. No.</label></td>
                                    <td width="30%"><?=$row_grn['po_no']?></td>
                                  </tr>                                  
                                </tbody>
                              </table>
                           </div><!--close panel body-->
                        </div><!--close panel-->
                        <div class="panel panel-success table-responsive">
                        	<div class="panel-heading"><i class="fa fa-shopping-cart fa-lg"></i>&nbsp;&nbsp;PO Details</div>
                            <div class="panel-body">
                       			<table class="table table-bordered" width="100%">
                                    <thead>
                                        <tr class="<?=$tableheadcolor?>">
                                            <th width="16%" style="text-align:center;">Part Name</th>
                                            <th width="10%" style="text-align:center;">PO No.</th>
                                            <th width="10%" style="text-align:center;">PO Qty</th>
                                            <th width="10%" style="text-align:center;">Invoice Qty</th>
                                            <th width="10%" style="text-align:center;">Receive Qty</th>
                                            <th width="8%" style="text-align:center;">Price</th>
                                            <th width="10%" style="text-align:center;">Amount</th>
                                            <th width="8%" style="text-align:center;">Tax %</th>
                                            <th width="8%" style="text-align:center;">Tax Amount</th>
                                            <th width="10%" style="text-align:center;">Total</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php
									/// fetch selected PO items
									$i=1;
									$res_po = mysqli_query($link1,"SELECT id,system_ref_no,partcode,req_qty FROM po_data where system_ref_no in (".$makepostr.")");
									while($row_po = mysqli_fetch_assoc($res_po)){
										$partdet = explode("~",getAnyDetails($row_po['partcode'],"part_name,hsn_code","partcode","partcode_master",$link1));
									?>
                                    	<tr>
                							<td><?php echo $partdet[0]." (".$row_po['partcode'].")";?></td>
                                            <td><?=$row_po['system_ref_no']?></td>
                                            <td align="right"><?=$row_po['req_qty']?></td>
                                            <td><input name="inv_qty<?=$row_po['id']?>" id="inv_qty<?=$i?>" type="text" class="form-control number required" style="width:90px; text-align:right"/></td>
                                            <td><input name="rcv_qty<?=$row_po['id']?>" onBlur="checkPriceInvRcb(<?=$i?>);" id="rcv_qty<?=$i?>" type="text" class="form-control number required" onKeyUp="fillCost(<?=$i?>)" style="width:90px;text-align:right"/></td>
                                            <td><input name="price<?=$row_po['id']?>" id="price<?=$i?>" type="text" class="form-control number required" onKeyUp="fillCost(<?=$i?>)" style="width:80px;text-align:right"/></td>
                                            <td><input name="sub_total<?=$row_po['id']?>" id="sub_total<?=$i?>" type="text" class="form-control" readonly style="width:120px;text-align:right"/></td>
                                            <td><select name="tax_per<?=$row_po['id']?>" id="tax_per<?=$i?>" class="form-control" onChange="fillCost(<?=$i?>);" style="width:120px;">
                                                    <option value="">--Please Select--</option>
                                                    <?php 
													$res_tax=mysqli_query($link1,"select sgst,igst,cgst from tax_hsn_master where status='1' and hsn_code='".$partdet[1]."'");
                                                    while($row_tax=mysqli_fetch_assoc($res_tax)){ ?>
                                                    <option  value="<?=$row_tax['igst']?>"><?=$row_tax['igst']?></option>
                                                    <?php } ?>
                                                </select></td>
                                            <td><input name="tax_total<?=$row_po['id']?>" id="tax_total<?=$i?>" type="text" class="form-control" readonly style="width:90px;text-align:right"/></td>
                                            <td><input name="line_total<?=$row_po['id']?>" id="line_total<?=$i?>" type="text" class="form-control" readonly style="width:120px;text-align:right"/></td>
                                        </tr>
                                    <?php
									$i++;
									}
									?>
                                    </table>
                                    <table class="table table-bordered" width="100%"> 
                                    	<tr>
                                            <td width="20%" align="right"><strong>Invoice No.</strong>&nbsp;</td>
                                            <td width="30%"><input name="invoice_no" id="invoice_no" type="text" class="form-control mastername required" required/></td>
                                            <td align="right" width="25%"><strong>Sub Total</strong>&nbsp;</td>
                                            <td width="25%"><input name="sub_total" id="sub_total" type="text" class="form-control number required" style="text-align:right" readonly/></td>
                                        </tr>
                                    	<tr>
                                    	  <td width="20%" align="right"><strong>Invoice Date</strong>&nbsp;</td>
                                    	  <td width="30%"><div style="display:inline-block;float:left;"><input type="text" class="form-control span2 required" name="inv_date"  id="inv_date" style="width:150px;" required></div><div style="display:inline-block;float:left;">&nbsp;<i class="fa fa-calendar fa-lg"></i>
                      </div></td>
                                    	  <td align="right"><strong>Discount</strong>&nbsp;</td>
                                    	  <td><input name="discount" id="discount" type="text" class="form-control number" style="text-align:right" onKeyUp="calculatetotal();"/></td>
                                  	  </tr>
                                    	<tr>
                                    	  <td width="20%" align="right"><strong>Attach Invoice Copy&nbsp;</strong></td>
                                    	  <td width="30%">
                                          	<div class="input-group">
                    							<label class="input-group-btn">
                        							<span class="btn<?=$btncolor?>">Browse&hellip; <input type="file" name="attchfile" id="attchfile" class="form-control required" required style="display:none;" accept="image/*,.doc, .docx,.ppt, .pptx,.txt,.pdf"></span>
                    </label>
                    <input type="text" class="form-control" name="billfile"  id="billfile" readonly>
              </div></td>
                                    	  <td align="right"><strong>Tax Total</strong>&nbsp;</td>
                                    	  <td><input name="tax_total" id="tax_total" type="text" class="form-control number required" style="text-align:right" readonly/></td>
                                  	  </tr>
                                    	<tr>
                                    	  <td width="20%" rowspan="2" align="right"><strong>Receive Remark </strong></td>
                                    	  <td width="30%" rowspan="2"><textarea name="rcv_rmk" id="rcv_rmk" class="form-control addressfield" style="resize:none;width:250px;"></textarea></td>
                                    	  <td align="right"><strong>Other Charges</strong>&nbsp;</td>
                                    	  <td><input name="other_charges" id="other_charges" type="text" class="form-control number" style="text-align:right" onKeyUp="calculatetotal();"/></td>
                                  	  </tr>
                                    	<tr>
                                    	  <td align="right"><strong>Grand Total</strong>&nbsp;</td>
                                    	  <td><input name="grand_total" id="grand_total" type="text" class="form-control number required" style="text-align:right" readonly/></td>
                                  	  </tr>
                                        <tr>
                                            <td align="center" colspan="4">
                                              <button class='btn<?=$btncolor?>' id="receivebtn" type="submit" name="receivebtn" value="Receive"><i class="fa fa-check-circle fa-lg"></i>&nbsp;&nbsp;Receive</button><input name="theValue" type="hidden" id="theValue" value="<?=$i?>"/>
                                              <button title="Back" type="button" class="btn<?=$btncolor?>" onClick="window.location.href='grn_list.php?status=<?php if(isset($_REQUEST['status'])){ echo $_REQUEST['status'];}?>&request_from=<?php if(isset($_REQUEST['request_from'])){ echo $_REQUEST['request_from'];}?>&request_to=<?php if(isset($_REQUEST['request_to'])){ echo $_REQUEST['request_to'];}?>&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>
