<?php
require_once("../includes/config.php");
$get_opr_rgts = getOprRights($_SESSION['userid'],$_REQUEST['pid'],$link1);
/////////check approval is applicable or not
$apply_app = getAnyDetails(base64_decode($_REQUEST['pid']),"apply_approval","tabid","tab_master",$link1);
///// get access location details
$access_loc = getAccessLocation($_SESSION['userid'],$link1);
if(isset($_REQUEST['request_from'])){$selrf=$_REQUEST['request_from'];}else{$selrf="";}
if(isset($_REQUEST['request_to'])){$selrt=$_REQUEST['request_to'];}else{$selrt="";}
if(isset($_REQUEST['entry_against'])){$selreftype=$_REQUEST['entry_against'];}else{$selreftype="";}
////// if we want to Add Gate Entry
if(isset($_POST['saveButton'])){
	if ($_POST['saveButton']=='Save'){
		$entry_in = base64_decode($_POST['entryin']);
		$entry_from = base64_decode($_POST['entryfrom']);
		$vendor_name = base64_decode($_POST['vendorname']);
		///// make a string token
		$messageIdent = md5($_POST['saveButton'] . $entry_in . $entry_from);
		//and check it against the stored value:
    	$sessionMessageIdent = isset($_SESSION['gateEntrySession'])?$_SESSION['gateEntrySession']:'';
    	if($messageIdent!=$sessionMessageIdent){//if its different: 
			///// check user has entered valid no. of invoices 
			if($_POST['no_of_inv']!="" && $_POST['no_of_inv']!=0){        
				//save the session var:
				$_SESSION['gateEntrySession'] = $messageIdent;
				//// check if approval is applicable then status will set to 3(PFA) otherwise 10 (Received)
				if($apply_app=="Y"){ $current_status = 3;}else{ $current_status = 10;}
				//// initialize transaction parameters
				$flag = true;
				mysqli_autocommit($link1, false);
				$err_msg = "";
				////// make po no. and po date string from post ref no. variable
				$po_numb = "";
				$po_date = "";
				foreach($_POST['ref_no'] as $po_det){
					$split_po = explode("~",$po_det);
					if($po_numb==""){
						$po_numb = $split_po[0];
						$po_date = $split_po[1];
					}else{
						$po_numb .= ",".$split_po[0];
						$po_date .= ",".$split_po[1];
					}
				}
				////// make gate entry no.
				$sql1 = "select max(temp_no) as no from gate_entry where location_code = '".$entry_in."'";
				$res1 = mysqli_query($link1,$sql1)or die("ER1".mysqli_error($link1));
				$row1 = mysqli_fetch_assoc($res1);
				$req_no = $row1['no'] + 1;
				$pad = str_pad($req_no,3,"0",STR_PAD_LEFT);
				$request_no = "GENT/".$entry_in."/".$pad;
				// insert in gate entry table \\
				$res2 = mysqli_query($link1,"INSERT INTO gate_entry set system_ref_no='".$request_no."',temp_no='".$req_no."',entry_date='".$today."',entry_time='".$currtime."',entry_by='".$_SESSION['userid']."',entry_ip='".$ip."',location_code='".$entry_in."',vendor_code='".$entry_from."',vendor_name='".$vendor_name."',vendor_address='".$_POST['vendor_address']."',ref_no='".$po_numb."',ref_date='".$po_date."',entry_against='".$_POST['entry_against']."',lr_no='".$_POST['lr_no']."',no_of_inv='".$_POST['no_of_inv']."',vehicle_no='".$_POST['vehicle_no']."',driver_name='".$_POST['driver_name']."',unload_date='".$_POST['unload_date']."',transport_name='".$_POST['transport_name']."',contact_person='".$_POST['contact_person']."',pallet_weight='".$_POST['pallet_weight']."',no_of_box='".$_POST['no_of_box']."',carton_weight='".$_POST['carton_weight']."',status='".$current_status."',remark='".$_POST['remark']."'");
				//// check if query is not executed
				if (!$res2) {
					$flag = false;
					$err_msg = "Error Code1: ".mysqli_error($link1);
				}
				///// check no. of invoice entered
				//// check if approval is applicable then status will set to 3(PFA) otherwise 6 (Pending)
				if($apply_app=="Y"){ $grn_status = 3;}else{ $grn_status = 6;}
				for($i = 1; $i <= $_POST['no_of_inv']; $i++){
					$sql_grn = "select max(temp_no) as no from grn_inv_master where location_code = '".$entry_in."'";
					$res_grn = mysqli_query($link1,$sql_grn)or die("ER2".mysqli_error($link1));
					$row_grn = mysqli_fetch_assoc($res_grn);
					$req_no_grn = $row_grn['no'] + 1;
					$pad = str_pad($req_no_grn,4,"0",STR_PAD_LEFT);
					$grn_no = "GRN/".$entry_in."/".$pad;
					////// entry in grn table
					$res3 = mysqli_query($link1,"INSERT INTO grn_inv_master set vendor_code='".$entry_from."',vendor_name='".$vendor_name."',vendor_address='".$_POST['vendor_address']."',location_code='".$entry_in."', system_ref_no='".$grn_no."',temp_no='".$req_no_grn."',entry_date='".$today."',entry_time='".$currtime."',entry_by='".$_SESSION['userid']."',entry_ip='".$ip."',po_no='".$po_numb."',po_date='".$po_date."',gate_entry_no='".$request_no."',status='".$grn_status."'");
					//// check if query is not executed
					if (!$res3) {
						$flag = false;
						$err_msg = "Error Code2: ".mysqli_error($link1);
					}
				}//////close for loop
				////// insert in activity table////
				$flag =	dailyActivity($_SESSION['userid'],$request_no,"GATE ENTRY","ADD",$ip,$link1,$flag);
				///// check both master and data query are successfully executed
				if ($flag) {
					mysqli_commit($link1);
					$msg = "Gate Entry is created with ref. no. ".$request_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 = "You have not entered no. of invoice.";
				$cflag="warning";
				$cmsg = "Warning";
			}
		}else {
        	//you've sent this already!
  			$msg = "Re-submission is not allowed";
			$cflag="warning";
			$cmsg = "Warning";
    	}
		///// move to parent page
    	header("location:gate_entry_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>
$(document).ready(function(){
	var spinner = $('#loader');
    $("#frm2").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;
			}
		}
	});
	$('#unload_date').datepicker({
		format: "yyyy-mm-dd",
		startDate: "<?=$today?>",
        //endDate: "<?//=$today?>",
        todayHighlight: true,
		autoclose: true
	});
	$('#po_no').multiselect({
		includeSelectAllOption: false,
		enableCaseInsensitiveFiltering: true,
		buttonWidth:"200",
		buttonClass: "form-control required custom-select"   
	});
});
////// change select ref no. dropdown on the basis of entry against field
$(document).ready(function(){
	$('#entry_against').change(function(){
	var reqtype = $("#entry_against").val();
	if(reqtype == "PO"){
		$("#pono").show();
		$("#po_no").removeAttr("disabled");
		$("#refno").hide();
		$("#ref_no").attr("disabled","disabled");
	}else{
		$("#pono").hide();
		$("#po_no").attr("disabled","disabled");
		$("#refno").show();
		$("#ref_no").removeAttr("disabled");
	}
	});
});
</script>
<!-- Include multiselect -->
<script type="text/javascript" src="../js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="../css/bootstrap-multiselect.css" type="text/css"/>
<style type="text/css">
.multiselect-container {
	width: 100% !important;
}
</style>
<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> Add Gate Entry</h2>
        		<div class="form-group"  id="page-wrap" style="margin-left:10px;">
                	<div class="panel-group">
    					<div class="panel panel-success">
                            <div class="panel-heading"><i class="fa fa-truck fa-lg"></i>&nbsp;&nbsp;Gate Entry Details</div>
         					<div class="panel-body">
                            <form id="frm1" name="frm1" class="form-horizontal" action="" method="post">
             					<div class="form-group">
                 					<div class="col-md-6"><label class="col-md-5 control-label">Location Name <span class="red_small">*</span></label>	  
                    					<div class="col-md-6" align="left">
                                            <select name="request_from" id="request_from" class="form-control custom-select required" onChange="document.frm1.submit();">
                                                <option value=''>--Select Location--</option>
                                                <?php
                                                $res_maploc = mysqli_query($link1,"select location_code,locationname from location_master where statusid='1' and location_code in (".$access_loc.") order by locationname "); 
                                                while($row_maploc = mysqli_fetch_assoc($res_maploc)){
                                                    ?>
                                                <option value="<?=$row_maploc['location_code']?>" <?php if($selrf == $row_maploc['location_code']) { echo 'selected'; }?>><?=$row_maploc['locationname']." (".$row_maploc['location_code'].")"?></option>
                                                <?php } ?>
                                            </select>
                    					</div>
                  					</div>
                  					<div class="col-md-6"><label class="col-md-5 control-label">Vendor Name <span class="red_small">*</span></label>
                                        <div class="col-md-6" align="left">
                                            <select name="request_to" id="request_to" class="form-control custom-select required" onChange="document.frm1.submit();">
                                                <option value="">--Select Vendor--</option>
                                                <?php
                                                $sql1 = "SELECT vendor_code,vendor_name,billing_address FROM vendor_master where status = '1' order by vendor_name";
                                                $res1 = mysqli_query($link1,$sql1);
                                                while($row1 = mysqli_fetch_array($res1)){
                                                ?>
                                                <option value="<?=$row1['vendor_code']?>"<?php if($selrt==$row1['vendor_code']){ echo "selected";}?>><?php echo $row1['vendor_name']." (".$row1['vendor_code'].")"; ?></option>
                                                <?php }?>
                                           </select>
                    					</div>
                  					</div>
            					</div><!--close form group-->
                            </form>
        					</div><!--close panel body-->
    					</div><!--close panel-->
                        <?php 
						if($selrf!="" && $selrt!=""){
							///// get vendor name and address
							$vend_det = mysqli_fetch_assoc(mysqli_query($link1,"SELECT vendor_name,billing_address FROM vendor_master where vendor_code = '".$selrt."'"));
						?>
    					<div class="panel panel-success table-responsive">
        					<div class="panel-heading"><i class="fa fa-newspaper-o fa-lg"></i>&nbsp;&nbsp;Document Details</div>
         					<div class="panel-body">
                            	<form id="frm2" name="frm2" class="form-horizontal" action="" method="post">
                                <div class="form-group">
                                     <div class="col-md-6"><label class="col-md-5 control-label">Entry Against <span class="red_small">*</span></label>	  
                                        <div class="col-md-6" align="left">
                                           <select name="entry_against" id="entry_against" class="form-control custom-select required">
                                                <option value="">--Select Entry Against--</option>
                                                <option value="PO"<?php if($selreftype=="PO"){ echo "selected";}?>>PO</option>
                                           </select>
                                        </div>
                                      </div>
                                      <div class="col-md-6"><label class="col-md-5 control-label">Ref. No. <span class="red_small">*</span></label>
                                        <div class="col-md-6" align="left" style="display:none" id="pono">
                                            <select name="ref_no[]" id="po_no" class="form-control required custom-select" multiple="multiple">
                                               <!-- <option value="" selected="selected">--Please Select--</option>-->
                                                <?php 
                                                $sql_chl="select system_ref_no,entry_date from  po_master where status in ('6','17') and to_location='".$selrt."'";
                                                $res_chl=mysqli_query($link1,$sql_chl);
                                                while($result_chl=mysqli_fetch_array($res_chl)){
                                                ?>
                                                <option value="<?=$result_chl['system_ref_no']."~".$result_chl['entry_date']?>" <?php if(isset($_REQUEST['ref_no'])){if($result_chl['system_ref_no']."~".$result_chl['entry_date']==$_REQUEST['ref_no']){echo "selected";}}?> ><?=$result_chl['system_ref_no']?></option>
                                                <?php }?>
                                              </select>
                                        </div>
                                        <div class="col-md-6" align="left" style="display:none" id="refno">
                                              <select name="ref_no" id="ref_no" class="form-control required custom-select">
                                                <option value="" selected="selected">--Please Select--</option>
                                              </select>
                                        </div>
                                      </div>
                                </div><!--close form group-->
                            	<div class="form-group">
                 					<div class="col-md-6"><label class="col-md-5 control-label">No. Of Invoices <span class="red_small">*</span></label>	  
                    					<div class="col-md-6" align="left">
                                            <input name="no_of_inv" id="no_of_inv" type="text" class="form-control digits required alert-warning"/>
                    					</div>
                  					</div>
                  					<div class="col-md-6"><label class="col-md-5 control-label">Unload Date <span class="red_small">*</span></label>
                                        <div class="col-md-6" align="left">
                                            <div style="display:inline-block;float:left;"><input type="text" class="form-control span2 required" name="unload_date"  id="unload_date" style="width:150px;" required value="<?php if(isset($_POST['unload_date'])){ echo $_POST['unload_date'];}?>"></div><div style="display:inline-block;float:left;">&nbsp;<i class="fa fa-calendar fa-lg"></i>
                      </div>
                    					</div>
                  					</div>
            					</div><!--close form group-->
                                <div class="form-group">
                 					<div class="col-md-6"><label class="col-md-5 control-label">LR No. <span class="red_small">*</span></label>	  
                    					<div class="col-md-6" align="left">
                                            <input name="lr_no" id="lr_no" type="text" class="form-control entername required"/>
                    					</div>
                  					</div>
                  					<div class="col-md-6"><label class="col-md-5 control-label">Vehicle No. <span class="red_small">*</span></label>
                                        <div class="col-md-6" align="left">
                                            <input name="vehicle_no" id="vehicle_no" type="text" class="form-control entername required"/>
                    					</div>
                  					</div>
            					</div><!--close form group-->
                                <div class="form-group">
                 					<div class="col-md-6"><label class="col-md-5 control-label">Transport Name <span class="red_small">*</span></label>	  
                    					<div class="col-md-6" align="left">
                                            <input name="transport_name" id="transport_name" type="text" class="form-control entername required"/>
                    					</div>
                  					</div>
                  					<div class="col-md-6"><label class="col-md-5 control-label">No. Of Boxes</label>
                                        <div class="col-md-6" align="left">
                                            <input name="no_of_box" id="no_of_box" type="text" class="form-control digits"/>
                    					</div>
                  					</div>
            					</div><!--close form group-->
                                <div class="form-group">
                 					<div class="col-md-6"><label class="col-md-5 control-label">Pallet Weight</label>	  
                    					<div class="col-md-6" align="left">
                                            <input name="pallet_weight" id="pallet_weight" type="text" class="form-control entername"/>
                    					</div>
                  					</div>
                  					<div class="col-md-6"><label class="col-md-5 control-label">Carton Weight</label>
                                        <div class="col-md-6" align="left">
                                        	<input name="carton_weight" id="carton_weight" type="text" class="form-control entername"/>
                    					</div>
                  					</div>
            					</div><!--close form group-->
                                <div class="form-group">
                 					<div class="col-md-6"><label class="col-md-5 control-label">Driver Name <span class="red_small">*</span></label>	  
                    					<div class="col-md-6" align="left">
                                            <input name="driver_name" id="driver_name" type="text" class="form-control entername required"/>
                    					</div>
                  					</div>
                  					<div class="col-md-6"><label class="col-md-5 control-label">Contact Person</label>
                                        <div class="col-md-6" align="left">
                                        	<input name="contact_person" id="contact_person" type="text" class="form-control entername"/>
                    					</div>
                  					</div>
            					</div><!--close form group-->
                                <div class="form-group">
                 					<div class="col-md-6"><label class="col-md-5 control-label">Vendor Address <span class="red_small">*</span></label>	  
                    					<div class="col-md-6" align="left">
                                            <textarea name="vendor_address" id="vendor_address" class="form-control addressfield required" style="resize:none" required><?=$vend_det['billing_address']?></textarea>
                    					</div>
                  					</div>
                                    <div class="col-md-6"><label class="col-md-5 control-label">Remark</label>
                                        <div class="col-md-6" align="left">
                                        	<textarea name="remark" id="remark" class="form-control addressfield" style="resize:none"></textarea>
                    					</div>
                  					</div>
            					</div><!--close form group-->
                                <div class="form-group">
                                	<div class="col-md-12" align="center">
                                    	<span class="red_small"><em>NOTE : The no. of invoices you enter , system will generate the same no. of GRN entries.</em></span>
                                    </div>
                                </div>    
                                <div class="form-group">
                                	<div class="col-md-12" align="center">
                                    	<?php if($get_opr_rgts['add']=="Y"){ ?>
                                      	<button class='btn<?=$btncolor?>' id="saveButton" type="submit" name="saveButton" value="Save"><i class="fa fa-save fa-lg"></i>&nbsp;&nbsp;Save</button>
                                        <input name="entryin" id="entryin" type="hidden" value="<?=base64_encode($selrf)?>"/>
                                      	<input name="entryfrom" id="entryfrom" type="hidden" value="<?=base64_encode($selrt)?>"/>
                                        <input name="vendorname" id="vendorname" type="hidden" value="<?=base64_encode($vend_det['vendor_name'])?>"/>
                                      	<?php }?>
                                      	<button title="Back" type="button" class="btn<?=$btncolor?>" onClick="window.location.href='gate_entry_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>
                                	</div>
                            	</div>
                            </form>
        					</div><!--close panel body-->
    					</div><!--close panel-->
                        <?php
						}
						else{
						?>
                        <div class="form-group">
                            <div class="col-md-12" align="center"><br/>
                                <button title="Back" type="button" class="btn<?=$btncolor?>" onClick="window.location.href='gate_entry_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>
                            </div>
                        </div>
                        <?php
						}
						?>
					</div><!--close panel group-->
				</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>
