<?php

include 'db.php';
include 'dbconfig.php';

require_once("conn.php");
require 'vendor2/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;

if(isset($_POST["Import"])){

		 $filename=$_FILES["file"]["tmp_name"];

		
		 if($_FILES["file"]["size"] > 0)
		 {
			$spreadsheet = IOFactory::load($filename);
			$sheet = $spreadsheet->getActiveSheet();
			$rows = $sheet->toArray();

		  //	$file = fopen($filename, "r");	
			$c=1;
			foreach ($rows as $emapData) 
	         //while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
	         {
				 
				$stmt = $DB_con->prepare('SELECT IFNULL(MAX(prid)+1,1) AS prid FROM `mobileproducts`');								
				$stmt->execute();								
				while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
				extract($row);			
				$prcode = $row['prid'];
				}
				
				$pname = mb_convert_encoding($emapData[1], "UTF-8", "auto");								

	            //It wiil insert a row to our subject table from our csv file`
			    if(mysqli_num_rows(mysqli_query($conn, "SELECT * FROM mobileproducts WHERE proname='$pname'")) == 0){

	            $sql = "INSERT into mobileproducts(`prcode`,`itemcode`,`proname`,`category`,`subcategory`,`supplier`,`unit`,`mqty`,`qty`,`price`,`sellprice`,`producttype`,`market_price`,`status`) 
	            values('0000$prcode','$emapData[0]','$pname','1','1','1','2','5','$emapData[3]','$emapData[4]','$emapData[5]','None','$emapData[5]','1')";
					
				//we are using mysql_query function. it returns a resource on true else False on error
				if($c!=1){
	            $result = mysqli_query( $conn, $sql );
			    $last_id = mysqli_insert_id($conn);
					
					$sql2 = "INSERT into tbl_stock(`prid`,`branch_id`,`qty`) 
	            	values('$last_id','1','$emapData[3]')";
					 $result2 = mysqli_query( $conn, $sql2 );
				if(! $result )
				{
					
				//	echo "<script type=\"text/javascript\">
				//			alert(\"Invalid File:Please Upload CSV File.\");
				//			window.location = \"importproduct.php\"
				//		</script>";
				
				}
			   }
				
			}


				$c++;
	         }
	        // fclose($file);
	         //throws a message if data successfully imported to mysql database from excel file
	         echo "<script type=\"text/javascript\">
						alert(\"CSV File has been successfully Imported.\");
						window.location = \"importproduct.php\"
					</script>";
	        
			 

			 //close of connection
			mysqli_close($conn); 
				
		 	
			
		 }
	}	 
?>		 