<?php
require_once("../includes/config.php");
/////////check approval is applicable or not
$apply_app = getAnyDetails(base64_decode($_REQUEST['pid']),"apply_approval","tabid","tab_master",$link1);
//////////////// after hitting upload button
@extract($_POST);
if($_POST){
	if($_POST['Submit']=="Upload"){
		mysqli_autocommit($link1, false);
		$flag = true;
		$error_msg = "";
		if($apply_app=="Y"){ $current_status = 3; }else{ $current_status = 1; }
		
		if ($_FILES["attchfile"]["error"] > 0){
			$code = $_FILES["attchfile"]["error"];
		}else{
			// Rename file
			$file_ext = substr($_FILES["attchfile"]["name"], strripos($_FILES["attchfile"]["name"], '.')); // get file name
			$newfilename = $todayt.$now.$file_ext;
			move_uploaded_file($_FILES["attchfile"]["tmp_name"],"../ExcelExportAPI/upload_partcode/".$newfilename);
			$filename="../ExcelExportAPI/upload_partcode/".$newfilename;
			chmod ($filename, 0755);
		}
		////////////////////////////////////////////////// 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);
		$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
		$one_record = 0;
		//importing files to the database
		for($row =2 ;$row <= $highest; $row++){
			$hsncode = $sheet->getCellByColumnAndRow(0,$row)->getValue();
			$vendorcode = $sheet->getCellByColumnAndRow(1,$row)->getValue();
			$vendorname = $sheet->getCellByColumnAndRow(2,$row)->getValue();
			$partname = $sheet->getCellByColumnAndRow(3,$row)->getValue();
            $material = $sheet->getCellByColumnAndRow(4,$row)->getValue();
			$bomunit = $sheet->getCellByColumnAndRow(5,$row)->getValue();
			$purchaseunit = $sheet->getCellByColumnAndRow(6,$row)->getValue();
            $goodtype = $sheet->getCellByColumnAndRow(7,$row)->getValue();
			$serialize = $sheet->getCellByColumnAndRow(8,$row)->getValue();
			$l = $sheet->getCellByColumnAndRow(9,$row)->getValue();
			$w = $sheet->getCellByColumnAndRow(10,$row)->getValue();
			$h = $sheet->getCellByColumnAndRow(11,$row)->getValue();
			$diame = $l."x".$w."x".$h;
			
			if($_POST['parttype']!='' && $_POST['brandname']!='' && $_POST['prod_cat']!='' && $_POST['product_sub_cat']!=''){
			
            	if(mysqli_num_rows(mysqli_query($link1,"select partid from partcode_master where part_name='".$partname."'"))==0){
				
					$usr_add="INSERT INTO partcode_master set brandid='".$brandname."',itemtypeid='".$parttype."',vendor_code='".$vendorcode."', vendor_part_name = '".$vendorname."',hsn_code='".$hsncode."', productid='".$prod_cat."',psubcatid ='".$product_sub_cat."',part_name='".$material."',bom_unit ='".$bomunit."',purchase_unit ='".$purchaseunit."',	material  ='".ucwords($partname)."',goods_type ='".$goodtype."',serialized ='".$serialize."',status='".$current_status."', pro_dimension = '".$diame."',createdate='".$datetime."',createby='".$_SESSION['userid']."'";
					
					$res_add=mysqli_query($link1,$usr_add)or die("error3".mysqli_error($link1));
					$insid = mysqli_insert_id($link1);
					/// make 5 digit padding

					$pad=str_pad($insid,5,"0",STR_PAD_LEFT);
					//// make logic of partcode code
					$newpartcode="P".$pad;	                    
					////////////// insert in bom master
					$res_part = mysqli_query($link1 , "UPDATE partcode_master set partcode='".$newpartcode."' where partid='".$insid."'");
					//// check if query is not executed
					if (!$res_part) {
						$flag = false;
						$error_msg = "Error 1: " . mysqli_error($link1) . ".";
					}
					$one_record++;
					////// insert in activity table////
					$flag = dailyActivity($_SESSION['userid'],$newpartcode,"PARTCODE","ADD",$_SERVER['REMOTE_ADDR'],$link1,$flag);
					////// return message
					$msg="You have successfully created a part like ".ucwords($partname);
					$cflag="success";
					$cmsg = "Success";
				}else{
					$msg = ucwords($partname)." is already exist";
					$cflag="warning";
					$cmsg = "Warning";
				}
			}
		}////// end of for loop 
		///// insert in upload table
		$re_inset = mysqli_query($link1,"INSERT INTO upload_file set ref_type='PARTCODE UPLOAD',file_name='".$filename."',updatedate='".$datetime."',updateby='".$_SESSION['userid']."'");
		//// check if query is not executed
		if (!$re_inset) {
			$flag = false;
			$error_msg = "Error 3: " . mysqli_error($link1) . ".";
		}
		////// insert in activity table////
		//$flag=dailyActivity($_SESSION['userid'],$partname,"BOM","ADD",$_SERVER['REMOTE_ADDR'],$link1,$flag);
		if ($flag) {
			if($one_record > 0){
				mysqli_commit($link1);
				$cflag = "success";
				$cmsg = "Success";
				$msg = "File is successfully Uploaded.";
			}else{
				$cflag = "warning";
				$cmsg = "Warning";
				$msg = "You are uploading blank file.";
			}
		} else {
			mysqli_rollback($link1);
			$cflag = "danger";
			$cmsg = "Failed";
			$msg = "Request could not be processed. Please try again.".$error_msg;
		} 
		mysqli_close($link1);
		///// move to parent page
		header("location:partcode_master.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({
		  liveSearch: true
		});
	});
  $(document).ready(function(){
	$('#prod_cat').change(function(){
	  var prod_catid=$('#prod_cat').val();
	  $.ajax({
	    type:'post',
		url:'../includes/getAzaxFields.php',
		data:{grt_sub_pro_cat:prod_catid},
		success:function(data){
	    $('#pscdiv').html(data);
		$('#product_sub_cat').addClass('required');
	    }
	  });
    });
  });
	</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"/>
    <script src="../js/fileupload.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-upload"></i> Upload Product & Components</h2>
       <div style="display:inline-block;float:right">
           <a href="../templates/partcodemaster.xlsx" title="Download Excel Template">
               <img src="../images/template.png" title="Download Excel Template"/></a>
       </div>
        <div class="form-group"  id="page-wrap" style="margin-left:10px;" >
	 <form  name="frm1"  id="frm1" class="form-horizontal" action="" method="post"  enctype="multipart/form-data">
             <div class="form-group">
              <div class="col-md-12">
                <label class="col-md-4 control-label">Brand <span class="red_small">*</span></label>
                <div class="col-md-4">
                  <select name="brandname" id="brandname" class="form-control required custom-select">
              			<option value="">Please Select</option>
						<?php 
						$sql ="select brand,brandid from brand_master where status='1' order by brand";
                        $qry = mysqli_query($link1,$sql) ;
                        while ($row=mysqli_fetch_array($qry)){?>    
              			<option value="<?php echo $row['brandid'];?>"<?php if(isset($_REQUEST['brandname'])){if($_REQUEST['brandname']==$row['brandid']){echo "selected";}}?>><?php echo $row['brand'];?></option>
              			<?php } ?>
              		</select>
                </div>
              </div>
             </div>
             <div class="form-group">
              <div class="col-md-12">
                <label class="col-md-4 control-label">Product Type <span class="red_small">*</span></label>
                <div class="col-md-4">
                  <select name="parttype" id="parttype" class="form-control required custom-select" >
              			<option value="">Please Select</option>
              			<?php 
						$sql ="select typeid,parttype from part_type_master where status='1' order by parttype";
			  			$qry = mysqli_query($link1,$sql) ;
			  			while ($row=mysqli_fetch_array($qry)){?>
              			<option value="<?php echo $row['typeid'];?>"<?php if(isset($_REQUEST['parttype'])){ if($_REQUEST['parttype']==$row['typeid']){echo"selected";}}?>><?php echo $row['parttype']?></option>
              			<?php } ?>
              		</select>
                </div>
              </div>
            </div>
            <div class="form-group">
              <div class="col-md-12">
                <label class="col-md-4 control-label">Product Category <span class="red_small">*</span></label>
                <div class="col-md-4">
                  <select name="prod_cat" id="prod_cat" class="form-control required custom-select">
              		<option value="">Please Select</option>
              		<?php 
					$sql ="select productid,product_name from product_master where status='1' order by product_name";
			  		$qry = mysqli_query($link1,$sql)or die (mysqli_error($link1));
			  		while ($row=mysqli_fetch_array($qry)){?>
              		<option value="<?php echo $row['productid'];?>"<?php if(isset($_REQUEST['prod_cat'])){ if($_REQUEST['prod_cat']==$row['productid']){echo "selected";}}?>><?php echo $row['product_name']?></option>
              		<?php } ?>
              	</select>
                </div>
              </div>
            </div>
             <div class="form-group">
              <div class="col-md-12">
                <label class="col-md-4 control-label">Product Sub Category <span class="red_small">*</span></label>
                <div class="col-md-4" id="pscdiv">
                  <?php if($_REQUEST['po']=='Upload'){ ?>
                  <select name="product_sub_cat" id="product_sub_cat" class="form-control required custom-select">
              		<option value="">Please Select</option>
              	  </select>
                  <?php }else{?>
                  <select name="product_sub_cat" class="form-control required custom-select" id="product_sub_cat">
                  	<option value=''>Please Select</option>
					<?php
                    $sql_psc = "select psubcatid,prod_sub_cat  from product_sub_category where productid='".$_REQUEST['prod_cat']."' order by prod_sub_cat";
					$res_psc = mysqli_query($link1,$sql_psc);
					while($row_psc = mysqli_fetch_array($res_psc)){
					?>	
					<option value="<?=$row_psc[0]?>"<?php if(isset($_REQUEST['product_sub_cat'])){ if($_REQUEST['product_sub_cat']==$row_psc[0]){ echo "selected";}}?>><?php echo $row_psc[1]?></option>
					<?php } ?>
				  </select>
                  <?php }?>
                </div>
              </div>
            </div>
          <div class="form-group">
            <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<?=$btncolor?>">
                            Browse&hellip; <input type="file" name="attchfile" id="attchfile" 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>
         <div class="form-group">
            <div class="col-md-12"><label class="col-md-4 control-label"></label>
              <div class="col-md-4">
              		<span class="red_small">NOTE: Attach only <strong>.xlsx (Excel Workbook)</strong> file<br/> Do not delete any column of excel sheet . Fill only appropriate columns.</span>
              </div>
            </div>
          </div> 
          <div class="form-group">
            <div class="col-md-12"><label class="col-md-4 control-label">Recommendation</label>
              <div class="col-md-8">
              		<span class="red_small">We have given the data format in attached template. Please follow the same.<br/>PART CODE must be entered as system generated.<br/>There should not be any special character in excel columns.<br/>You can fill BOM QTY and CONVERSION FACTOR up to 6 decimal places.</span>
              </div>
            </div>
          </div> 
         <div class="form-group">
            <div class="col-md-12" align="center">
              <button class='btn<?=$btncolor?>' id="save" type="submit" name="Submit" value="Upload" <?php if(isset($_POST['Submit'])){ if($_POST['Submit']=='Update'){?>disabled<?php }}?>><i class="fa fa-upload fa-lg"></i>&nbsp;&nbsp;Upload</button>
              &nbsp;&nbsp;
              <button title="Back" type="button" class="btn<?=$btncolor?>" onClick="window.location.href='partcode_master.php?<?=$pagenav?>'"><i class="fa fa-reply fa-lg"></i>&nbsp;&nbsp;Back</button>
            </div>
          </div> 
    </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>
