<?php
class SableImport
{
	//protected
	public $fileName, $hasHeader, $delimeter, $tableName, $fieldNames = [], $error, $errorMessage, $neatenValues = false;
	private $filePtr, $counter, $sql, $fields, $sqlStarted, $data, $lineCount;
	
	// constructor method
	function __construct()
	{
		$lineCount = 0;
	}
	
	private function validate()
	{
		$this->error 		= false;
		$this->delimeter 	= empty($this->delimeter) ? ',' : $this->delimeter;
		$this->data 		= []; //reset array
		if (!is_file($this->fileName)) 
		{
			$this->SetError($this->fileName.' is missing.');
		}
		else
		{
			$this->filePtr = fopen($this->fileName, "r") or $this->SetError($this->fileName.' cannot be opened.');
			if (filesize($this->fileName) > 0) 
			{
				if (empty($this->tableName))
				{
					$this->SetError('A table name has not been specified.');
				}
				else
				{
					if (!is_array($this->fieldNames) || empty($this->fieldNames))
					{
						$this->SetError('Field names for table '.$this->tableName.' have not been specified.');
					}				
				}
				
			}
			else
			{
				$this->SetError($this->fileName.' is empty.');
			}
		}		
	}
	
	private function SetError($detail)
	{
		$this->error = true;
		$this->errorMessage = $detail;
	}
	
	private function GetFieldNames()
	{
		$this->fields = implode(',', $this->fieldNames);	
	}
	
	private function PrepSQL()
	{
		$this->sqlStarted 	= 0;
		$this->sql 			= '';
		$this->GetFieldNames();
		$this->sql 			= 'insert into '.$this->tableName.' ('.$this->fields.') values ';
	}
	
	
	private function Neaten($value)
	{
		if ($this->neatenValues)
		{
			$work = strtolower(trim($value));
			$tmp = explode(' ', $work);
			$res = '';
			$c = 0;
			if (is_array($tmp))
			{
				foreach ($tmp as $v) 
				{
					$s = $c ? ' ' : '';
					$res .= $s.ucfirst($v);
					$c++;
				}
				return $res;
			} else return ucfirst(trim($work));
		} else return trim($value);
	}
	
	private function AddLineToArray($line)
	{
		if (!empty($line))
		{
			$vals = [];
			$vals = explode($this->delimeter, $line);
			$this->data[$this->counter] = [];
			$iter = 0;
			$c = $this->lineCount ? ', ' : '';
			$this->sql .= $c.'(';
			foreach($vals as $val) 
			{
				$ic = $iter ? ', ' : '';
				$this->sql .= $ic.'"'.$this->Neaten($val).'"';
				$this->data[$this->counter][$this->fieldNames[$iter]] = $val;
				$iter++;
			}
			$this->sql .= ')';
			$this->lineCount++;
		}
		/*
			Now we have all of the data stored in an associative array, something like this:
			[0] => Array
				(
					[company_name] => Company A
					[user_title] => Mr.
					[user_name] => Piet
					[user_surname] => Skiet
					[company_phone] => 821 115 555
					[company_email] => piet@skiet.com
					[company_address] => 123 Road A, Gauteng, 0163
					[company_reg_no] => 2004/852258/07
					[company_vat_no] => 4035287465
					[company_url] => http://www.sony.com
		
				)			
		*/
	}
	
	private function ProcessFile()
	{
		$ln = '';
		$this->counter = $this->hasHeader ? -1 : 0;
		$this->PrepSQL();
		while (!feof($this->filePtr)) 
		{
			$ln = fgets($this->filePtr);
			if ($this->counter === -1)
			{
				//$ln is the header row at this point.
			}
			else
			{
				$this->AddLineToArray(trim($ln));
			}
			$this->counter++;
		}
		$this->RunQuery();
	}
	
	private function RunQuery()
	{
		$sdb = new SableDB;
		$res = $sdb->updateQuery($this->sql);		
		unset($sdb);
		if ($res !== $this->counter) 
			$this->SetError('Out of '.$this->counter.' entries, '.$res.' were successfully imported.');
	}
	
	public function ImportFile()
	{
		$this->validate();
		if (!$this->error) $this->ProcessFile();
	}
	
	public function ValidateFile()
	{
		$this->validate();
	}	
	
	public function GetLinesAsArray()
	{
		$this->validate();
		if (!$this->error) $this->ProcessFile();
		return $this->data;		
	}
	
	// desctructor method
	function __destruct()
	{
		if (isset($this->filePtr)) fclose($this->filePtr);
	}
}