<?php
//load the database configuration file
include 'dbConfig.php';

if(isset($_POST['importSubmit'])){
    
    //validate whether uploaded file is a csv file
    $csvMimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
    if(!empty($_FILES['file']['name']) && in_array($_FILES['file']['type'],$csvMimes)){
        if(is_uploaded_file($_FILES['file']['tmp_name'])){
            
            //open uploaded csv file with read only mode
            $csvFile = fopen($_FILES['file']['tmp_name'], 'r');
            
            //skip first line
            fgetcsv($csvFile);
            //$delQuery = "DELETE FROM Products";
			//$delResult = $db->query($delQuery);
			//if($delResult){
			//parse data from csv file line by line
            while(($line = fgetcsv($csvFile)) !== FALSE){
                //check whether member already exists in database with same email
                $prevQuery = "SELECT id FROM products WHERE name = '".$line[0]."'";
                $prevResult = $db->query($prevQuery);
                if($prevResult->num_rows > 0){
                    //update member data
                    $db->query("UPDATE products SET name = '".$line[0]."' WHERE name = '".$line[0]."'");
                }else{
                    //insert member data into database
                    $db->query("INSERT INTO products (name) VALUES ('".$line[0]."')");
                }
            }
            //}
            //close opened csv file
            fclose($csvFile);
            $qstring = '?status=succ';
			echo '<script language="javascript">';
			echo 'alert("Uspesno ucitan fajl");';
			echo 'window.location.href = "http://service.poolteam.rs/";';
			echo '</script>';
        }else{
            $qstring = '?status=err';
			echo '<script language="javascript">';
			echo 'alert("Desila se greska, probajte ponovo!");';
			echo 'window.location.href = "http://service.poolteam.rs/";';
			echo '</script>';
        }
    }else{
        $qstring = '?status=invalid_file';
			echo '<script language="javascript">';
			echo 'alert("Niste ucitali fajl, probajte ponovo!");';
			echo 'window.location.href = "http://service.poolteam.rs/";';
			echo '</script>';
    }
}

//header('Content-type: application/javascript');
//$some_variable = 'whatever';



