<?php 
	include("_dirinfo.php");
	include (PATH_TO_ROOT."init.php");
	include_once (PATH_TO_ROOT."/TGI/init.php");
	include_once (PATH_TO_ROOT."_class/class.ConvertCodepage.php");

	$db->LogWrite(DB_WARPIT_TGI,false,"database name for TGI");
		

	$db->ChangeDatabase(DB_WARPIT_TGI);

	$uploadFile_array = explode(".", $_FILES['csvfilepath']['name']);
	$uploadFileType = strtolower(array_pop($uploadFile_array));
	
	if ($uploadFileType == "csv") {
		
		// convert to utf-8
		$cc = new ConvertCodepage();
		if($cc->convert_file($_POST['encoding'],'utf-8',$_FILES['csvfilepath']['tmp_name']) === false)
		{
			echo "{success:false,error:'Unable to convert'}";
			exit;
		}
		
		$fh = fopen($_FILES['csvfilepath']['tmp_name'], 'rb');
		//get the first line to determine delimiter
		$ddfFile = fgets($fh);
		$lastLine = mb_substr($ddfFile,-2);
		if ($lastLine == "\r\n")
			$lineDelimiter = $lastLine;
		else 
			$lineDelimiter = "\n";
	
		$ddfFile = trim($ddfFile);
		fclose($fh);
	
		$$ddfFile = str_replace('"','˝',$ddfFile);
		$$ddfFile = str_replace("'",'´',$ddfFile);
	
		// make sure that utf-8 is without BOM
		if( mb_check_encoding($ddfFile,'UTF-8' ) )
		{
			ini_set('default_charset', 'UTF-8');
			mb_internal_encoding('UTF-8');
			$ddfFile = mb_substr($ddfFile, mb_strpos($ddfFile,'H,') );
			
		}
	
		// check if file is DDF 
		if(mb_substr($ddfFile,0,2) != 'H,') {
			echo  '{success:false,error:"Incorrect DDF file!"}';
			exit;
		}
		
		// set DDF delimiter for fields
		$fieldDelimiter = ","; 
		
		$tmp = explode(".",$_FILES['csvfilepath']['name'],2);
		$ddfTableName = $tmp[0];
		
		// fill the MySQL
		$sql = "CREATE TABLE IF NOT EXISTS `".$ddfTableName."___import` ( 
				  `id` int(5) NOT NULL AUTO_INCREMENT,
				  `category` varchar(1) DEFAULT NULL,
				  `controlCode_label` text,
				  `longer_description` text,
				  `change` varchar(255) DEFAULT NULL,
				  `variable` varchar(255) DEFAULT NULL,
				  `position` varchar(255) DEFAULT NULL,
				  `volumetrics` tinyint(1) DEFAULT NULL,
				  PRIMARY KEY (`id`),
				  KEY `category` (`category`)
				) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
		$db->LogWrite($sql,false,"create table sql");
		if(!$db->SQLexecute($sql)) {
			echo '{success:false,error:"'.$db->GetError().'"}';
			exit;
		} else {
			$sql = "TRUNCATE TABLE ".$ddfTableName."___import";
			$db->SQLexecute($sql);
			
			$sql = "LOAD DATA LOCAL INFILE '".$_FILES['csvfilepath']['tmp_name']."' 
					INTO TABLE ".$ddfTableName."___import 
					CHARACTER SET utf8 
					FIELDS TERMINATED BY '$fieldDelimiter' 
					ENCLOSED BY '\"' 
					LINES TERMINATED BY '$lineDelimiter' 
					(`category`,`controlCode_label`,`longer_description`,`change`,`variable`,`position`,`volumetrics`)";
			$db->LogWrite($sql,true,"load data sql");
			if(!$db->SQLexecute($sql)) {
				$db->LogWrite($db->GetError(),false,"load data ERROR");
				echo '{success:false,error:"'.$db->GetError().'"}';
				exit;
			} else {
				// check if exist
				$getID = $db->get("TGI_projects","name='$ddfTableName'",id);
				
				if (count($getID)>0) {
					$idActiveProject = $getID[0];
					$db->LogWrite($idActiveProject,false,"idActiveProject through GET");
				} else {
					$sql = "INSERT INTO TGI_projects SET name='$ddfTableName'";
					$db->SQLexecute($sql);
					$idActiveProject = $db->GetLastInsertId();
					$db->LogWrite($sql." --- idActiveProject:".$idActiveProject,false,"idActiveProject through insert SQL");
				}
				// update active to 1
				$sql = "UPDATE TGI_projects SET active=0";
				$db->SQLexecute($sql);
				
				$sql = "UPDATE TGI_projects SET active=1 WHERE id=".$idActiveProject;
				$db->SQLexecute($sql);
			}
		}
		
		echo "{success:true}";
	} else {
		echo "{success:false,error:'Wrong file type, only CSV allowed!'}";
	}
	

?>