<?php
include("../connect.php");
include("../session.php");
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["csv"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$target_file = $target_dir . $_REQUEST['for'] . ".csv";
$vendorID = $_REQUEST['vendor'];
// Check if image file is a actual image or fake image

if (strtolower($imageFileType) != "csv") {
	$data['error'] = "This file is not a CSV file, at least does not have the .csv extension.";
}else{

	if (move_uploaded_file($_FILES["csv"]["tmp_name"], $target_file)) {
	        $data['message'] = "The file ". basename( $_FILES["csv"]["name"]). " has been uploaded.";
	        $data['fileuploaded'] = true;
	    } else {
	        $data['error'] = "Sorry, there was an error uploading your file.";
	    }
}
$handle = fopen($target_file,'r');
$table = "SUPPLIER_INVENTORY";
$fields = ["SKU", "QtyAvailable", "AdditionalDate", "Volume", "Price", "AdditionalQty", "Discontinued"];
//var_dump($additionalParams);
if(!$handle) die('Cannot open uploaded file.');

ini_set("auto_detect_line_endings", "1");
	//Read the file as csv
$return['trueCount'] = 0;
$return['falseCount'] = 0;
$dateCols = array();
foreach($fields as $key =>$value){
if(stripos($value, "date") != false)
	array_push($dateCols, $key);
}
$data = fgetcsv($handle, 1000, ",",'"','"');
while (($data = fgetcsv($handle, 1000, ",",'"','"')) !== false) {
	if(count($fields) == 1){
		$sql_query = "INSERT INTO $table (`VendorID`, " . $fields[0] .") VALUES('$vendorID',";
	}else{
		$sql_query = "INSERT INTO $table (`VendorID`, ". implode(',',$fields) .") VALUES('$vendorID',";
	}

	$row_count++;
	$numcols = count($data);
	$correctNumCols = count($fields);
	if ($numcols > $correctNumCols) {
		for ($i = $numcols; $i >= $correctNumCols; $i--) {
			unset($data[$i]);
		}
	}
	if ($numcols > 0) {
		foreach($data as $key=>$value) {
			if(array_search($key,$dateCols) === false){
				$data[$key] = "'" . addslashes(str_replace(",","",$value)) . "'";
			}else{
				$oldDate = $data[$key];
				$newDate = date('Y-m-d', strtotime($oldDate));
				$data[$key] = "'" . addslashes($newDate) . "'";
			}
		}

		$row = implode(",",$data);
		$sql_query .= $row . ") ON DUPLICATE KEY UPDATE ";
		foreach ($fields as $key => $value) {
			$sql_query .= $value . " = VALUES(" . $value . "), ";
		}
		$sql_query = rtrim($sql_query,", ");
		//die($sql_query);
		$result[$row_count-1] = mysqli_query($con, $sql_query); // and insert the new ones.
		if (mysqli_error($con) == "" || mysqli_error($con) == null) {
		}else {
			$return['errors'][$row_count-1] = mysqli_error($con) . "\nQuery: " . $sql_query;
		}
		if ($result[$row_count-1]) {
			$return['trueCount']++;
		}else {
			$return['falseCount']++;
		}
	}
}
if($return['falseCount'] == 0){
	$return['fileuploaded'] = true;
}else{
	$return['fileuploaded'] = false;
}
echo json_encode($return);
?>
