<?php

	session_start();
	require('dbConfig.php');
	if(isset($_POST['import'])){
		//check if input file is empty
		if(!empty($_FILES['file']['name'])){
			$filename = $_FILES['file']['tmp_name'];
			$fileinfo = pathinfo($_FILES['file']['name']);
			//check file extension
			if(strtolower($fileinfo['extension']) == 'csv'){
				//check if file contains data
				if($_FILES['file']['size'] > 0){
                    $sql = "delete from venkat";
					$query = $conn->query($sql);
					$file = fopen($filename, 'r');
	                //while(($impData	= fgetcsv($file)) !== FALSE){
					while(($impData = fgetcsv($file, 10000, ',')) !== FALSE){
						$sql = "INSERT INTO venkat (Edit,PART_NUMBER,PART_DESCRIPTION,LIST,MOQ,LYSALES,CYSALES,TO_ORDER,STOCK,COST,RATE,OPENING,RECEIVED,PENDING,DISPATCH,AAL_PO,PY_STK,TOD_COST,GP,SEGMENT) VALUES ('.$impData[0].', '.$impData[1].', '.$impData[2].', '.$impData[3].', '.$impData[4].', '.$impData[5].', '.$impData[6].', '.$impData[7].', '.$impData[8].', '.$impData[9].', '.$impData[10].', '.$impData[11].', '.$impData[12].', '.$impData[13].', '.$impData[14].', '.$impData[15].', '.$impData[16].', '.$impData[17].', '.$impData[18].', '.$impData[19].')";
						$query = $conn->query($sql);

						if($query){
							$_SESSION['message'] = "Data imported successfully";
						}
						else{
							$_SESSION['message'] = "Cannot import data. Something went wrong";
						}
					}
					header('location: index.php');
					
				}
				else{
					$_SESSION['message'] = "File contains empty data";
					header('location: index.php');
				}
			}
			else{
				$_SESSION['message'] = "Please upload CSV files only";
				header('location: index.php');
			}
		}
		else{
			$_SESSION['message'] = "File empty";
			header('location: index.php');
		}

	}

	else{
		$_SESSION['message'] = "Please import a file first";
		header('location: index.php');
	} 
 
?>