<?php
require_once("../includes/config.php");
$get_opr_rgts = getOprRights($_SESSION['userid'],$pidvar,$link1);
/////////check approval is applicable or not
$apply_app = getAnyDetails($pidvar,"apply_approval","tabid","tab_master",$link1);
///// get access location details
$access_loc = getAccessLocation($_SESSION['userid'],$link1);
if($apply_app=="Y"){ $current_status = 3;}else{ $current_status = 6;}
@extract($_POST);
if($_POST['Submit']=="Upload"){
   // echo "helllo";
mysqli_autocommit($link1, false);
$flag = true;
if ($_FILES["file"]["error"] > 0)
{
$code=$_FILES["file"]["error"];
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../ExcelExportAPI/upload/".$now.$_FILES["file"]["name"]);
$file="../ExcelExportAPI/upload/".$now.$_FILES["file"]["name"];
chmod ($file, 0755);
}

$filename=$file;
////////////////////////////////////////////////// code to import file/////////////////////////////////////////////////////////////
error_reporting(E_ALL ^ E_NOTICE);
 $path = '../ExcelExportAPI/Classes/';
        set_include_path(get_include_path() . PATH_SEPARATOR . $path);//we specify the path" using linux"
        function __autoload($classe)
        {
            $var = str_replace
            (
                '_', 
                DIRECTORY_SEPARATOR,
                $classe
            ) . '.php' ;
            require_once($var);
        }   

 $indentityType = PHPExcel_IOFactory::identify($filename);
                $object = PHPExcel_IOFactory::createReader($indentityType);
                $object->setReadDataOnly(true);
                $objPHPExcel = $object->load($filename);
               /*echo '<script>alert("le fichier a été chargé avec succes !");</script>';*/
                $sheet = $objPHPExcel->getSheet(0); //we specify the sheet to use
                $highestRow = $sheet->getHighestRow();//we select all the rows used in the sheet 
                $highestCol = $sheet->getHighestColumn();// we select all the columns used in the sheet
                $indexCol = PHPExcel_Cell::columnIndexFromString($highestCol); //////// count no. of column 
				$highest = $objPHPExcel->setActiveSheetIndex(0)->getHighestRow(); //////////////// count no of rows in excel
				//Checking data
				$part_count=0;
				$error_msg = "";
			
		
            
            ////// get address ////////////
				$from_addr = getAnyDetails($_POST['request_from'],"locationaddress","location_code","location_master",$link1);
				$to_addr = getAnyDetails($_POST['request_to'],"billing_address","vendor_code","vendor_master",$link1);
				
				/////// pick PO series from document counter
				$rs = mysqli_fetch_array(mysqli_query($link1,"SELECT doc_str,doc_count from document_counter where doc_type='SRS' and location_code='".$_POST['request_from']."'"));
				if($rs['doc_str']){
					$req_no = $rs['doc_count'] + 1;
					$request_no = $rs['doc_str'].str_pad($req_no,5,0,STR_PAD_LEFT);
					// insert request no detail in parent table \\					
					$req_res1 = mysqli_query($link1,"INSERT INTO requisition_master set request_from='".$_POST['request_from']."',request_to='".$_POST['request_to']."', system_ref_no='".$request_no."',temp_no='".$req_no."',entry_date='".$today."',entry_time='".$currtime."',entry_by='".$_SESSION['userid']."',entry_ip='".$ip."',status='".$current_status."',person_name='".$_POST['person_name']."',req_type='".$_POST['request_type']."',ref_no='".$_POST['job_no']."',remark='".$_POST['remark']."', planning_no = '".$planning."' ");
					//// check if query is not executed
					if (!$req_res1) {
						$flag = false;
						$err_msg = "Error Code1: ".mysqli_error($link1);
					}
    
	

	
              for($row =2 ;$row <= $highest;$row++){
					
                $item = trim($sheet->getCellByColumnAndRow(0,$row)->getValue());
            $quan = trim($sheet->getCellByColumnAndRow(1,$row)->getValue());
           
           
					$from_code=$_POST['request_from'];  /////
					$to_code=$_POST['request_to'];/////
	
				if($item!="" && $quan!="0")
				{
					//echo "select partcode,product_id,brand_id,model_id from partcode_master where   partcode='".$item."'  and status='1'";
								$part_check=mysqli_query($link1,"select partcode,purchase_unit from partcode_master where   partcode='".$item."'  and status='1'");
									if(mysqli_num_rows($part_check)>0){
                                        $row_chk=mysqli_fetch_assoc($part_check);
                                        $purchase_unit=$row_chk['purchase_unit'];
									    $req_res2 = mysqli_query($link1,"INSERT INTO requisition_data set system_ref_no='".$request_no."', partcode='".$item."', stock_type = '".$stock_type."' , req_qty='".$quan."',purchase_unit='". $purchase_unit."',remark='".$production_rmk."'");
							//// check if query is not executed
							if (!$req_res2) {
								$flag = false;
								$err_msg = "Error Code2: ".mysqli_error($link1);
							}}else{
                                  $flag = false;
								$err_msg = "Error Code3: Partcode not available in CRM";      
                                        }
							//$total_qty += $quan;
						}
					}// close for loop
				}else{
					$flag = false;
					$err_msg = "Error Code2.1 :Document series not found for request to location.";		
				}
		
		
		//update document count
		$req_res3 = mysqli_query($link1,"UPDATE document_counter set doc_count = doc_count+1 where doc_type='PO' and location_code='".$_POST['request_from']."'");
		if (!$req_res3) {
			$flag = false;
			$err_msg = "Error Code3: ".mysqli_error($link1);
		}
		////// insert in activity table////
		$flag =	dailyActivity($_SESSION['userid'],$request_no,"RAISE Requisition","ADD",$ip,$link1,$flag);
		///// check both master and data query are successfully executed
		if ($flag) {
			mysqli_commit($link1);
			$msg = "Raise Requisition 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);
		 	
		///// move to parent page
    	header("location:requisition_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");
 ?>
 <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;
			}
          }
		});
	$('.selectpicker').selectpicker({
	  //actionsBox: true,
	  //container: true,
      liveSearch: true
	});
	$('.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 makedropdown(){
	$('.selectpicker').selectpicker({
      liveSearch: true
	});
	$('.number').on('input', function() {
		match = (/(\d{0,6})[^.]*((?:\.\d{0,6})?)/g).exec(this.value.replace(/[^\d.]/g, ''));
		this.value = match[1] + match[2];
  	});
}
/////// add new row 
$(document).ready(function() {
	$("#add_row").click(function() {		
		var numi = document.getElementById('rowno');
		var itm = "partcode[" + numi.value+"]";
		var preno=document.getElementById('rowno').value;
		var num = (document.getElementById("rowno").value -1)+2;
		numi.value = num;
		if ((document.getElementById(itm).value != "") || ($("#addr1_" + numi.value + ":visible").length == 0)) {
			var r = '<tr id="addr1_'+num+'"><td width="40%"><div style="display:inline-block;float:right"><select name="partcode['+num+']" id="partcode['+num+']" class="form-control required selectpicker show-tick" required data-width="350px" onChange="getunit(this.value,'+num+');getAvlStock(this.value,'+num+');"><option value="">--Select Part--</option><?php $res_pro = mysqli_query($link1,"select partcode,part_name,bom_unit,purchase_unit,material from partcode_master where itemtypeid not in ('1') and status='1' order by part_name")or die(mysqli_error($link1));while($row_pro = mysqli_fetch_assoc($res_pro)){?><option value="<?=$row_pro['partcode']."~".$row_pro['purchase_unit']?>"><?=$row_pro['part_name']." | ".$row_pro['material']." | ".$row_pro['partcode']?></option><?php } ?></select></div><div style="display:inline-block;float:left;"><i class="fa fa-close fa-lg" onClick="fun_remove('+num+');"></i></div></td><td width="15%"><input type="text" name="req_qty['+num+']" class="form-control number required" id="req_qty['+num+']" onBlur="checkMaxQty('+num+',this.value)" value="" /></td><td width="15%"><input type="text" name="abl_qty['+num+']" class="form-control number" id="abl_qty['+num+']" readonly="readonly"/></td><td width="15%"><span id="unit'+num+'"></span></td><td width="30%"><input type="text" name="rmk['+num+']" class="form-control addressfield" id="rmk['+num+']"/></td></tr>';
			$('#itemsTable1').append(r);
			makedropdown();
		}
	});
});
function fun_remove(con){
	var c = document.getElementById('addr1_' + con);
	c.parentNode.removeChild(c);
	con--;
	document.getElementById('rowno').value = con;
}
function getunit(val,indx){
	var split_val = val.split("~");
	document.getElementById("unit"+indx).innerHTML = split_val[1];
	checkDuplicatePart(indx,split_val[0]);
}
function checkRefNo(){
	var reqtype = $("#request_type").val();
	if(reqtype == "JC"){
		$("#job_no").show();
		$("#job_no").removeAttr("disabled");
		$("#ref_no").hide();
		$("#ref_no").attr("disabled","disabled");
	}else{
		$("#job_no").hide();
		$("#job_no").attr("disabled","disabled");
		$("#ref_no").show();
		$("#ref_no").removeAttr("disabled");
	}
}
///// check request to and request from should not be same
function checkFromTo(){
	var reqfrom = $("#request_from").val();
	var reqto = $("#request_to").val();
	if(reqfrom == reqto){
		$("#error_msg").html("Request To and Request From can not be same.");
		$("#request_to").val("");	
	}else{
		$("#error_msg").html("");	
	}
}

/////////////// Check stock  avl or not ////////////////////////////
function getAvlStock(val,indx){
	var stockType = document.getElementById("stock_type").value;
	var split_val = val.split("~");
	var locationcode = document.getElementById("request_to").value;
	$.ajax({
		type:'post',
		url:'../includes/getAzaxFields.php',
		data:{avl_stock_new:split_val[0],indx:indx,loc:locationcode,stocktype:stockType},
		//data:{avl_stock:split_val[0],indx:indx,loc:locationcode},
		success:function(data){
			//alert(data);
			var avl = data.split("~");
			document.getElementById("abl_qty["+avl[0]+"]").value = avl[1];
		}
	});
	checkDuplicatePart(indx,split_val[0]);
}
////// check input qty /////
function checkMaxQty(indx, val){
	var ablval = document.getElementById("abl_qty["+indx+"]").value;
	if(parseFloat(val)<=parseFloat(ablval)){
	}else{
		alert("Request Qty is not greater then available qty.");
		document.getElementById("req_qty["+indx+"]").value = 0.000000;
	}
}

///// function for checking duplicate partcode
function checkDuplicatePart(fldIndx1,val){
  if(val!=''){
     var check2="partcode["+fldIndx1+"]";
	 var flag=1;
	 for(var i=0;i<=fldIndx1;i++){
	  	 var check1="partcode["+i+"]";
		 if(fldIndx1!=i && document.getElementById(check2).value!='' && document.getElementById(check1).value!=''){
		    if((document.getElementById(check2).value==document.getElementById(check1).value) ){
			    document.getElementById("error_msg").innerHTML="Duplicate Part selection";
				document.getElementById(check2).value="";
			    //document.getElementById(check2).className="form-control required selectpicker show-tick alert-danger";
				flag*=0;
			}
		    else{
				document.getElementById("error_msg").innerHTML="";
			    //document.getElementById(check2).className="form-control required selectpicker show-tick";
				flag*=1;
			 ///do nothing
			}
		 }
	 }//// close for loop
	 if(flag==0){ 
	 	return false;
	 }else{ 
	 	return true;
	 }
  }
}

////////////////// Calculate Tax/////////////////////
function checkAllRows(){
	var rowno1 = document.getElementById("rowno").value;
	var flag=1;
	if(rowno1 > 0){
		for(var j=0;j<rowno1;j++){
        	var check2="partcode["+j+"]";
				for(var i=0;i<=rowno1;i++){
					if(j!=i){
						var check1="partcode["+i+"]";
						var rqty="req_qty["+i+"]";
						var runit="unit"+i+"";
						var rrmk="rmk["+i+"]";
		 				if(document.getElementById(check2).value==document.getElementById(check1).value){
			 				document.getElementById("error_msg").innerHTML="Duplicate Part selection";
							document.getElementById(check1).value="";
							document.getElementById(rqty).value='';
							document.getElementById(runit).innerHTML='';
							document.getElementById(rrmk).value="";
							flag*=0;
						}
		 				else{
			 			//document.getElementById(defQty).value='1';
						flag*=1;
						}
					}
				}
		}
		//////////
		if(flag==0){ 
			return false;
		 }else{ 
			return true;
		 }
		}
}

////// disable qty type dropdown /////
function getDisable(val){
	document.getElementById("stock_type").value = document.getElementById("stock_type1").value;
	document.getElementById("stock_type1").disabled = true;
}

</script>
<script src="../js/bootstrap-select.js"></script>
<link href="../css/bootstrap-select.css" rel="stylesheet"/>
<script src="../js/jquery.validate.js"></script>
<link href="../css/loader.css" rel="stylesheet"/>
</head>
<body onLoad="checkRefNo();">
<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 Requisition</h2><br/>
      <h4 align="center"><span id="error_msg" class="red_small" style="text-align:center"></span></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="form-group">
              <div class="col-md-6">
                <label class="col-md-6 control-label">Requisition From <span class="red_small">*</span></label>
                <div class="col-md-6">
                  <select name="request_from" id="request_from" class="form-control required custom-select" required onChange="checkFromTo();">
                    <option value="">--Please Select--</option>
                    <?php
					$sql1 = "SELECT location_code,locationname FROM location_master where statusid= '1' and location_code in (".$access_loc.") order by locationname";
					$res1 = mysqli_query($link1,$sql1);
					while($row1 = mysqli_fetch_array($res1)){
					?>
                    <option value="<?=$row1['location_code']?>"<?php if(isset($_REQUEST['request_from'])){if($_REQUEST['request_from']==$row1['location_code']){ echo "selected";}}?>><?php echo $row1['locationname']?></option>
                    <?php }?>
                  </select>
                </div>
              </div>
              <div class="col-md-6">
                <label class="col-md-6 control-label">Requisition To <span class="red_small">*</span></label>
                <div class="col-md-6">
                  <select name="request_to" id="request_to" class="form-control required custom-select" required onChange="checkFromTo();">
                    <option value="">--Please Select--</option>
                    <?php
					$sql1 = "SELECT location_code,locationname FROM location_master where statusid = '1' and location_code in (".$access_loc.")  order by locationname";
					$res1 = mysqli_query($link1,$sql1);
					while($row1 = mysqli_fetch_array($res1)){
					?>
                    <option value="<?=$row1['location_code']?>"<?php if(isset($_REQUEST['request_to'])){if($_REQUEST['request_to']==$row1['location_code']){ echo "selected";}}?>><?php echo $row1['locationname']?></option>
                    <?php }?>
                  </select>
                </div>
              </div>
            </div>
            <div class="form-group">
              <div class="col-md-6">
                <label class="col-md-6 control-label">Requisition Type <span class="red_small">*</span></label>
                <div class="col-md-6">
                  <select name="request_type" id="request_type" class="form-control required custom-select" required onChange="checkRefNo();">
                    <option value="">--Please Select--</option>
                    <option value="JC"<?php if(isset($_REQUEST['request_type'])){if($_REQUEST['request_type']=="JC"){ echo "selected";}}?>>Against Job Card</option>
                    <option value="GR"<?php if(isset($_REQUEST['request_type'])){if($_REQUEST['request_type']=="GR"){ echo "selected";}}?>>General Request</option>
                  </select>
                </div>
              </div>
              <div class="col-md-6">
                <label class="col-md-6 control-label">Reference No. <span class="red_small">*</span></label>
                <div class="col-md-6">
                  <select name="job_no" id="job_no" class="form-control required custom-select" style="display:none">
                    <option value="" selected="selected">--Please Select--</option>
                    <?php 
					$sql_chl="select system_ref_no from  jobcard_master where status!='13'";
					$res_chl=mysqli_query($link1,$sql_chl);
					while($result_chl=mysqli_fetch_array($res_chl)){
					?>
                    <option value="<?=$result_chl['system_ref_no']?>" <?php if(isset($_REQUEST['job_no'])){if($result_chl['system_ref_no']==$_REQUEST['job_no']){echo "selected";}}?> >
                      <?=$result_chl['system_ref_no']?>
                      </option>
                    <?php }?>
                  </select>
                  <input name="job_no" id="ref_no" type="text" class="form-control required mastername"/>
                </div>
              </div>
            </div>
            <div class="form-group">
              <div class="col-md-6">
                <label class="col-md-6 control-label">Stock Type <span class="red_small">*</span></label>
                <div class="col-md-6">
                  <select name="stock_type1" id="stock_type1" class="form-control custom-select required" onChange="getDisable(this.value)" required>
					<option value='' <?php if($_REQUEST['stock_type1'] == ""){ echo "selected"; } ?> > -- Please Select -- </option>
					<option value='ok_qty' <?php if($_REQUEST['stock_type1'] == "ok_qty"){ echo "selected"; } ?> >Ok</option>
					<option value='damage_qty' <?php if($_REQUEST['stock_type1'] == "damage_qty"){ echo "selected"; } ?> >IQC Rejection</option>
					<option value='faulty_qty' <?php if($_REQUEST['stock_type1'] == "faulty_qty"){ echo "selected"; } ?> >Vender Rejection</option>
					<option value='p_rejected_qty' <?php if($_REQUEST['stock_type1'] == "p_rejected_qty"){ echo "selected"; } ?> >Process Rejection</option>
				  </select>
				  
				  <input type="hidden" name="stock_type" id="stock_type" value="" />
                </div>
              </div>
			  <div class="col-md-6">
                <label class="col-md-6 control-label">Person Name</label>
                <div class="col-md-6">
                  <input name="person_name" type="text" class="entername form-control" id="person_name">
                </div>
              </div>
            </div>
			<div class="form-group">
			  <div class="col-md-6">
                <label class="col-md-6 control-label">Remark</label>
                <div class="col-md-6">
                  <textarea name="remark" id="remark" class="form-control addressfield" style="resize:vertical"></textarea>
                </div>
              </div>
              <div class="col-md-6">
                <label class="col-md-6 control-label">Planning No</label>
                <div class="col-md-6">
                	<select name="planning" id="planning" class="form-control" >
						<option value="" > -- Please Select -- </option>
						<?php 
							$qrrr = mysqli_query($link1, "SELECT system_ref_no FROM request_production_p  WHERE  1 ");
							if(mysqli_num_rows($qrrr)>0){
							while($pn = mysqli_fetch_array($qrrr)){
						?>
						<option value="<?=$pn['system_ref_no']?>" > <?=$pn['system_ref_no']?> </option>
						<?php }} ?>
					</select>
                </div>
              </div>
            </div>
   




<div style="display:inline-block;float:right">
           <a href="../templates/Request_UPLOAD.xlsx" title="Download Excel Template">
               <img src="../images/template.png" title="Download Excel Template"></a>
       </div>





 <div class="col-md-12"><label class="col-md-4 control-label">Attach File<span class="red_small">*</span></label>
                            <div class="col-md-4">
                                <div class="input-group">
                                    <label class="input-group-btn">
                        <span class="btn btn-primary">
                            Browse… <input type="file" name="file" id="file" class="form-control required" required="" style="display:none;" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
                        </span>
                                    </label>
                                    <input type="text" class="form-control" name="billfile" id="billfile" readonly="">
                                </div>
                            </div>
                            <div class="col-md-4" align="right"><span class="red_small">NOTE: Attach only <strong>.xlsx (Excel Workbook)</strong> file</span></div>
                        </div>

          <div class="form-group">
          
           <div class="col-md-8" style="display:inline-block; float:right" align="left">
           	   <input type="submit" class="btn<?=$btncolor?>" name="Submit" id="save" value="Upload" title="" <?php if($_POST['Submit']=='Update'){?>disabled<?php }?>>
              <button title="Back" type="button" class="btn<?=$btncolor?>" onClick="window.location.href='raise_po_list.php?status=<?=$statusvar?>&request_from=<?=$request_fromvar?>&request_to=<?=$request_tovar?>&daterange=<?=$daterangevar?><?=$pagenav?>'"><i class="fa fa-reply fa-lg"></i>&nbsp;&nbsp;Back</button>
            </div>
          </div>
    </form>
      </div>
    </div>
  </div>
</div>
<div id="loader"></div>
<?php
include("../includes/footer.php");
include("../includes/connection_close.php");
?>
</body>
</html>