<?php

include("_dirinfo.php");
include (PATH_TO_ROOT."init.php");
include (PATH_TO_ROOT."_class/class.ConvertCodepage.php");
include (PATH_TO_ROOT."webcati/_class/class.numbersImport.php");

$db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
$tmpImportFile = $_FILES['csvfilepath']['tmp_name'];


if ($tmpImportFile) {
	$importer = new numbersImport($db);

	$importOption = configLoader::loadConfig('import_option');

	if (!$importer->check_iconv()) {
		echo "{success:false,error:'Can\'t find iconv functions!'}";
		exit;
	}
	if (!$importer->check_mb()) {
		echo "{success:false,error:'Can\'t find mb functions!'}";
		exit;
	}


	// prepare temporary table name for upload
	$tmpName = 'telManagerUpload_'.$_SESSION['UserInfo']['id'];


	// if I use keyword LOCAL I do not need to save file to server...
	// I also here prepare variable for LOCAL load with MySQL
	$importer->setMySQLmethod("LOCAL");


	if ($importOption['method'] != "LOCAL") {
		// prepare temporary file name for upload
		$saveImportFile = $importOption['tmp_folder'].'telFileUpload_'.$_SESSION['UserInfo']['id'].".csv";
		if (!move_uploaded_file($tmpImportFile, $saveImportFile)) {
			echo "{success:false,error:'Unable to save file to destination:  $saveImportFile!'}";
			exit;
		}
		$tmpImportFile = $saveImportFile;

		// I also here change variable for LOCAL load with MySQL
		$importer->setMySQLmethod(null);
	}


	// take care that file is uploaded always as utf-8
/*	$cc = new ConvertCodepage();
	if($cc->convert_file($_POST['encoding'],'utf-8',$tmpImportFile) === false) {
		echo "{success:false,error:'Unable to convert file to utf-8. Is iconv installed?'}";
		exit;
	}*/
	$lineDelimiter = $importer->getLineDelimiter($tmpImportFile);
	$structure = $importer->getStructure();

	// check if file is UTF-8 - BOM and remove leading characters for BOM from $structure
	$structure = $importer->checkBOMinUTF8($structure);

	// check if tdisable is present on first position
	if (!$importer->checkHeader($structure)) {
		echo  '{success:false,error:"Incorrect structure of fields! tdisable is missing or is not on first position!"}';
		exit;
	}
	// get field delimiter
	$delimiter = $importer->getDelimiter();


	$fields = explode($delimiter,$structure);
	$tableName = $_POST['tableSel'];
	$telbazaId = $_POST['tableId'];
	$requiredFields = 7;
	$fieldPrefix = 'tel_';
	$telTablePrefix = 'tel___';
	$TablePrefix = '_Telephone';
	$idBaseTable = "id_telbaza";

	// check if in the file I include at least all default fields
	if(count($fields) < $requiredFields) {
		echo '{success:false,error:"Not all basic fields included! Please recheck your file!"}';
		exit;
	}

	// fields array need to be clean of spaces
	$fields = $importer->cleanFields($fields,$requiredFields,$fieldPrefix);
	// get fields name and type for creating temporary table for test import
	$sqlTmp = $importer->getTempTableSQL();

	// check, if we want to upload some unknown fields
	$checkedFields = $importer->checkFields($fields,$telTablePrefix,$tableName);
	if ($checkedFields > 0) {
		$diff = $importer->getFieldDifference();
		echo "{success:false,error:'Unknown fields: ".implode(',',$diff). "'}";
		exit;
	}

	// let's try to import the file
	try {
		$sql = "DROP TEMPORARY TABLE IF EXISTS $tmpName";
		if(!$db->SQLexecute($sql)) {
			echo '{success:false,error:"'.$db->GetError().'", STATEMENT: "'.$sql.'"}';
			exit;
		}

		$sql = " CREATE TEMPORARY TABLE $tmpName (".implode(",",$sqlTmp).") ENGINE = MYISAM ;";
		if(!$db->SQLexecute($sql)) {
			echo '{success:false,error:"'.$db->GetError().'", STATEMENT: "'.$sql.'"}';
			exit;
		}
		$sql = "ALTER TABLE $tmpName ADD INDEX (oms, telephone);";
		if(!$db->SQLexecute($sql)) {
			echo '{success:false,error:"'.$db->GetError().'", STATEMENT: "'.$sql.'"}';
			exit;
		}

		$loadData = $importer->importData($tmpImportFile,$tmpName,$delimiter,$lineDelimiter);
		if (!$loadData) {
			echo '{success:false,error:"'.$db->GetError().'"}';
			exit;
		}

		// delete temporary file
		$importer->tmpFileDelete($tmpImportFile);

		// get all integer fields which I need in telephone table structure
		$intFields = $importer->getAllIntegerFields($tableName,$TablePrefix,$telbazaId,$fieldPrefix,$fields,$idBaseTable,$telTablePrefix,$capi);
		if (!$intFields) {
			echo '{success:false,error:"'.$db->GetError().'", STATEMENT: "'.$sql.'"}';
			exit;
		}


		// checks if all data for numeric fields are in integer format
		$notNumeric = $importer->checkNumericField($tmpName,$intFields);
		if ($notNumeric == -1) {
			echo '{success:false,error:"'.$db->GetError().'", STATEMENT: "'.$sql.'"}';
			exit;
		}
		if ($notNumeric == -2) {
			$rowCnt = $importer->getRowImportError();
			$fld = $importer->getFieldImportError();
			$t = $importer->getValueImportError();
			echo "{success:false,error:'$fld is not a number on row $rowCnt, value: $t'}";
			exit;
		}

		if(!$importer->dropFromBlackList($tmpName)){
			echo '{success:false,error:"'.$db->GetError()."\"}";
		}


		// try to insert clean and good records into mysql telephone table
		$goodImport = $importer->importFinalChecked($tmpName,$telTablePrefix,$tableName,$fields);
		if ($goodImport) {
			echo '{success:true}';
		} else {
			echo '{success:false,error:"'.$db->GetError()."\",test:$key}";
		}

	} catch(Exception $e) {
		echo "{success:false, error:".json_encode($db->GetError() )."}";
	}

} else {
	echo "{success:false,error:'Upload file is not in proper format, upload file is to big or some other upload error occure, please check your settings!'}";
}

?>
