<?php 
require_once("../includes/config.php");
//////////////// after hitting upload button

$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);
@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 = "";
			
				
	
	
	$browserid=session_id();
	$req_res=mysqli_query($link1,"delete from temp_disp_upd where userid='".$_SESSION['userid']."' and browserid='".$browserid."'");
	//// check if query is not executed
	if (!$req_res) {
		$flag = false;
		$err_msg = "Error Code1.1:". mysqli_error($link1);
	}
	
              for($row =2 ;$row <= $highest;$row++){
					
                $item = trim($sheet->getCellByColumnAndRow(0,$row)->getValue());
            $quan = trim($sheet->getCellByColumnAndRow(1,$row)->getValue());
            $rate = trim($sheet->getCellByColumnAndRow(2,$row)->getValue());
            $val =$quan*$rate;
            $schedule =trim($sheet->getCellByColumnAndRow(3,$row)->getValue());
            $production_rmk = trim($sheet->getCellByColumnAndRow(4,$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 from partcode_master where   partcode='".$item."'  and status='1'");
									if(mysqli_num_rows($part_check)>0){
									    ///fetch  data form partcode master 		
										$partcode_check=mysqli_fetch_assoc($part_check);
										$tot_val=$post_price*$post_dispqty;
												 $add_po_temp="INSERT INTO temp_disp_upd set from_location='".$from_code."',to_location='".$to_code."',partcode='".$item."',qty='".$quan."',price='".$rate."',value='".val."',challan_no='".$grnno."',file_name='".$filename."',doc_type='".$doc_type."',entry_date='".$today."',userid='".$_SESSION['userid']."',browserid='".$browserid."',schedule_date='".$schedule."',pro_rmk='".$production_rmk."'";
												$result_add_po_temp=mysqli_query($link1,$add_po_temp);	
												//// check if query is not executed
												if (!$result_add_po_temp) {
													$flag = false;
													$err_msg= "Error Fail_add_po_temp: " . mysqli_error($link1) . ".";
												}
									}////partcode check
									else {
									   $flag = false;
					                    $err_msg= "Partcode is not available in Partcode Master-".$part_code;
									     }
									     			 
								 
										
					
					 
				
				}////qty check
				else {
						$flag = false;
					  $err_msg= "Qty Zero and Empty in Excel file for this partcode-:".$part_code;
				     }	 				 
			
					
       		}////// end of for loop 
				
					  
					
		///////////Close Document type
	   if ($flag) {
        mysqli_commit($link1);
		$cflag = "success";
		$cmsg = "Success";
        $msg = "Successfully Uploaded ";
    } else {
		mysqli_rollback($link1);
		$cflag = "danger";
		$cmsg = "Failed";
		$msg = "Request could not be processed.Please try again.".$err_msg;
	} 
    mysqli_close($link1);
	   ///// move to parent page
header("location:show_po_temp_data.php?msg=".$msg."&chkflag=".$cflag."&chkmsg=".$cmsg."".$pagenav);
  exit;
            
}///// end of if condition



?>
<!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="26%"><div><select name="partcode['+num+']" id="partcode['+num+']" class="form-control required selectpicker show-tick" required data-width="350px" onChange="getunit(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 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="10%"><input type="text" name="req_qty['+num+']" class="form-control number required" required id="req_qty['+num+']" value="0" onKeyUp="getValue('+num+')" /></td><td width="10%"><input type="text" name="price['+num+']" class="form-control number required" required id="price['+num+']" value="0" onKeyUp="getValue('+num+')"/></td><td width="12%"><input type="text" name="value['+num+']" class="form-control number required" required id="value['+num+']" readonly="readonly"/></td><td width="10%"><span id="unit'+num+'"></span></td><td width="12%"><input type="text" class="form-control  required span2" required name="schedule_date['+num+']"  id="schedule_date'+num+'" value=""></td><td width="20%"><input type="text" name="rmk['+num+']" class="form-control addressfield" id="rmk['+num+']"/> </td></tr>';
			$('#itemsTable1').append(r);
			makedropdown();
			makeCalDOP(num);
		}
	});
});
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]);
}
$(document).ready(function() {
    $("#request_type").change(function() {
        if(this.value == "JC"){
			$("#job_no").show();
			$("#ref_no").hide();
		}else{
			$("#job_no").hide();
			$("#ref_no").show();
		}
    });
});

//// make dynamic calender
function makeCalDOP(ind){
	$('#schedule_date'+ind).datepicker({
		format: "yyyy-mm-dd",
		startDate: "<?=$today?>",
		todayHighlight: true,
		autoclose: true,
	});
}
$(document).ready(function () {
	$('#schedule_date0').datepicker({
		format: "yyyy-mm-dd",
		startDate: "<?=$today?>",
		todayHighlight: true,
		autoclose: true
	});
});
/////// get billing and shipping address ////////////
function getAddress(val){
	$.ajax({
		type:'post',
		data:{get_address:val,fields:"locationaddress,deliveryaddress"},
		url:'../includes/getAzaxFields.php',
		success:function(data){
			var addr = data.split("~");
			document.getElementById("bill_address").value = addr[0];
			document.getElementById("ship_address").value = addr[1];
		}
	});
}
//////// calculate value ///////////
function getValue(indx){
	var req_qty = document.getElementById('req_qty['+indx+']').value;
	var price = document.getElementById('price['+indx+']').value;
	if(req_qty!='' && price!=''){
		document.getElementById('value['+indx+']').value = (req_qty*price);
	}else{
		document.getElementById('value['+indx+']').value = 0.00;
	}
}

///// 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;
		 }
		}
}
</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"/>
<!-- Include Date Picker -->
<link rel="stylesheet" href="../css/datepicker.css">
<script src="../js/bootstrap-datepicker.js"></script>
</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 Raise PO</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">Raise 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="getAddress(this.value);" >
                    <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']." (".$row1['location_code'].")";?></option>
                    <?php }?>
                  </select>
                </div>
              </div>
              <div class="col-md-6">
                <label class="col-md-6 control-label">Raise 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 >
                    <option value="">--Please Select--</option>
                    <?php
					$sql1 = "SELECT vendor_code,vendor_name 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(isset($_REQUEST['request_to'])){if($_REQUEST['request_to']==$row1['vendor_code']){ echo "selected";}}?>><?php echo $row1['vendor_name']." (".$row1['vendor_code'].")"; ?></option>
                    <?php }?>
                  </select>
                </div>
              </div>
            </div>
            
            <div class="form-group">
             <div class="col-md-6">
                <label class="col-md-6 control-label">Billing Address<span class="red_small">*</span></label>
                <div class="col-md-6">
                  <textarea name="bill_address" id="bill_address" class="form-control addressfield required" style="resize:none" required></textarea>
                </div>
              </div>
              <div class="col-md-6">
                <label class="col-md-6 control-label">Shipping Address<span class="red_small">*</span></label>
                <div class="col-md-6">
                  <textarea name="ship_address" id="ship_address" class="form-control addressfield required" style="resize:none" required></textarea>
                </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:none"></textarea>
                </div>
              </div>
            </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>
                                   
                                </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-4" style="display:inline-block; float:left">
               
                <input type="hidden" name="rowno" id="rowno" value="0"/>
           </div>
           <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>