<?php

	class numbersImport {
		private $db;
		public $structure;
		public $delimiter;
		public $fieldDifference;
		public $TempTableSQL;
		public $rowImportError;
		public $fieldImportError;
		public $MySQLmethod;


		public function __construct($db) {
			$this->db=$db;
		}


		public function getDelimiter() {
			return $this->delimiter;
		}

		public function getFieldDifference() {
			return $this->fieldDifference;
		}

		public function getTempTableSQL() {
			return $this->TempTableSQL;
		}


		public function getStructure() {
			return $this->structure;
		}


		public function getRowImportError() {
			return $this->rowImportError;
		}


		public function getFieldImportError() {
			return $this->fieldImportError;
		}


		public function getValueImportError() {
			return $this->valueImportError;
		}

		public function check_iconv() {
			if (function_exists('iconv')) {
				return true;
			} else {
				return false;
			}
		}


		public function check_mb() {
			if (function_exists('mb_get_info')) {
				return true;
			} else {
				return false;
			}
		}


		public function checkBOMinUTF8($structure) {
			if(mb_check_encoding($structure,'UTF-8' )) {
				ini_set('default_charset', 'UTF-8');
				mb_internal_encoding('UTF-8');
				$structure = mb_substr($structure, mb_strpos($structure,'tdisable'));
			}
			return $structure;
		}


		public function checkHeader($structure) {

				//print "tukaj sem";
			//echo mb_substr($structure,0,8);


			if(mb_substr($structure,0,8) != 'tdisable') {
				if(mb_substr($structure,1,8) != 'tdisable') {
					return false;
				} else {
					$this->delimiter = mb_substr($structure,10,1);
				}
			} else {
				$this->delimiter = mb_substr($structure,8,1);
			}

			return true;
		}


		public function checkFields($fields,$telTablePrefix,$tableName) {
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			$testTableFields = $this->db->GetFields($telTablePrefix.$tableName);
			$diff = array_diff($fields,$testTableFields);
			if(count($diff)) {
				$this->fieldDifference = $diff;
				return count($diff);
			}
			return 0;
		}


		public function cleanFields($fields,$requiredFields,$fieldPrefix) {
			foreach ($fields as $key=>&$val) {
				$val = trim($val);
				if($key > $requiredFields) $val = $fieldPrefix.$val;
				if($val == 'oms')
					$sqlTmp[] = $val." VARCHAR ( 10 ) NOT NULL";
				elseif($val == "telephone")
					$sqlTmp[] = $val." VARCHAR ( 20 ) NOT NULL";
				else
				 	$sqlTmp[] = $val." VARCHAR( 255 ) NOT NULL ";
			}

			$this->TempTableSQL = $sqlTmp;
			return $fields;
		}


		public function getLineDelimiter($tmpImportFile) {
			$fh = fopen($tmpImportFile, 'r');
			$structure = fgets($fh);

			file_put_contents("/tmp1/test.txt", "-->".$tmpImportFile."\n" );

			$lastLine = mb_substr($structure,-2);
			if($lastLine == "\r\n") {
				$lineDelimiter = $lastLine;
			} else {
				$lineDelimiter = "\n";
			}
			fclose($fh);



			$structure = str_replace('"','',$structure);
			$structure = str_replace("'",'',$structure);
			$this->structure = trim($structure);
			return $lineDelimiter;
		}


		public function getAllIntegerFields($tableName,$TablePrefix,$telbazaId,$fieldPrefix,$fields,$idBaseTable,$projectTablePrefix,$capi=0) {
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			$sql = "SELECT name FROM $TablePrefix"."TablesAddon WHERE $idBaseTable = $telbazaId AND type = 4";
			if(!$rs = $this->db->SQLexecute($sql)) {
				return false;
			}

			//echo "/*tableName:$tableName,TablePrefix:$TablePrefix,telbazaId:$telbazaId,fieldPrefix:$fieldPrefix,fields:$fields,idBaseTable:$idBaseTable,projectTablePrefix:$projectTablePrefix,capi:$capi*/";

			if ($capi) {
				$intFields = array("id_municipality","id_settlement","id_street","address","zip","id_region","type_settlement");
			} else {
				$intFields = array("tdisable","region","zip");
				$td = $this->db->describe($projectTablePrefix.$tableName);
				// check if telephone and oms are declared as integers
				if(substr($td['telephone']['type'],0,3) == 'int')
				{
					$intFields[] = "telephone";
					$intFields[] = "oms";
				}
			}

			// add also addon telephone or capi fields
			while ($row = $this->db->fetchArray($rs)) {
				$fld = $fieldPrefix.$row['name'];
				if(!array_search( $fld,$fields ) === false) {
					$intFields[] = $fld;
				}
			}


			return $intFields;
		}


		public function setMySQLmethod($method) {
			$this->MySQL_method = $method;
			return true;
		}


		public function getMySQLmethod() {
			return $this->MySQL_method;
		}

		public function importData($tmpImportFile,$tmpName,$delimiter,$lineDelimiter) {
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);

			$method = $this->getMySQLmethod();
			// bacause of windows path I add escape \
			$tmpImportFile = addslashes($tmpImportFile);
			// importing raw data into table
			$sql = "LOAD DATA ".$method." INFILE '".$tmpImportFile."'
					IGNORE INTO TABLE  $tmpName CHARACTER SET utf8
					FIELDS TERMINATED BY '$delimiter'
					ENCLOSED BY '\"'
					LINES TERMINATED BY '$lineDelimiter'
					IGNORE 1 LINES ";
			if(!$this->db->SQLexecute($sql)) {
				return false;
			}

			return true;
		}


		public function checkNumericField($tmpName,$intFields) {
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			// get all import records
			$sql = "SELECT * FROM $tmpName";
			if(!$rs = $this->db->SQLexecute($sql)){
				return -1;
			}

			$rowCnt=1;
			while ($row = $this->db->fetchArray($rs)) {
				//for each field declared earlier I check if it is a number!
				foreach ($intFields as $fld) {
					$t = $row[$fld];
					if(!is_numeric($row[$fld]) ){
						$this->fieldImportError = $fld;
						$this->valueImportError = $t;
						return -2;
					}
				}
				$this->rowImportError = $rowCnt;
				$rowCnt++;
			}

			return 1;
		}

		//Delete numbers that are already in the FROM black_list table
		public function dropFromBlackList($tmpName){
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			$this->db->SQLbegin();

			$sql = "DELETE a FROM $tmpName AS a, _Telephone_black_list AS b WHERE a.oms = b.oms AND a.telephone = b.tel";
			if(!$this->db->SQLexecute($sql)) return false;

			return true;
		}


		public function importFinalChecked($tmpName,$telTablePrefix,$tableName,$fields) {
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			$this->db->SQLbegin();

			$sql = "INSERT IGNORE INTO $telTablePrefix$tableName (".implode(',',$fields). ") SELECT * FROM $tmpName ";
			echo "/*$sql*/";
			if(!$this->db->SQLexecute($sql)) {
				$this->db->SQLrollback();
				return false;
			}

			// time import, new column, check if exist, old tables did not have this info...
			$timeImport = "";
			$sql = "SHOW COLUMNS FROM $telTablePrefix$tableName LIKE 'time_import'";
			echo "/*$sql*/";
			$res = $this->db->SQLexecute($sql);
			if ($this->db->numRows($res) > 0) $timeImport = ", time_import=UNIX_TIMESTAMP(NOW())";


			$sql = "SELECT max(id_import) FROM $telTablePrefix$tableName";
			$maxImport = $this->db->fetchArray( $this->db->SQLexecute($sql) );
			$maxImport = $maxImport[0] +1;

			$sql = "UPDATE $telTablePrefix$tableName set id_import = $maxImport $timeImport WHERE id_import = 0";
			$this->db->SQLexecute($sql);

			$this->db->SQLcommit();

			return true;
		}


		public function tmpFileDelete($tmpFile) {
			if (file_exists($tmpFile))
				if (!unlink($tmpFile))
					$this->db->LogWrite($tmpFile,true,"WARNING: Attemp to delete upload file from the disk failed");
		}


	}

?>
