<?php

namespace Modules\Admin\ImportEntities\Model\FileParser;

/**
 * Parses the CSV content and extracts an associative array of data.
 * @author Gabi
 *
 */
class Csv extends \Modules\Admin\ImportEntities\Model\FileParserAbstract
{

	/**
	 * The CSV delimiter.
	 * @var String
	 */
	public $delimiter=';';


	protected function getParsedContent()
	{

		$return = [];

		if (!$this->filePath) {
			return false;
		}

		//Open the file.
		$fileHandle = fopen($this->filePath, "r");

		// Get headers
		if (($data = fgetcsv($fileHandle, null, $this->delimiter, "\"", "")) !== FALSE) {
	        $this->fileHeader = array_map('trim',$data);
	    }
	    // remove BOM from the first column name
	    $this->fileHeader[0] = $this->removeUtf8Bom($this->fileHeader[0]);

		//Loop through the CSV rows.
		while (1) {

			// if the disk becomes full in the meantime, we lose the file handle - happened for FCM JP
			if (!$fileHandle) {
				break;
			}

			$row = fgetcsv($fileHandle, null, $this->delimiter, "\"", "");

			// if the end of file was reached
			if ($row===false) {
				break;
			}

			// skip empty or bad rows
			if (!$row or !array_filter($row)) {
				continue;
			}
			$row = array_map('trim', $row);
			if (count($this->fileHeader)==count($row)) {
				$return[] = array_combine($this->fileHeader, $row);
			}
		}

		$this->fileContent = $return;

	}

	public function getExistingColumns()
	{
		if (!$this->columnsFormat) {
			return null;
		}

		if (!$this->fileHeader) {
			$this->getParsedContent();
		}


		return array_intersect($this->columnsFormat, $this->fileHeader);


	}

	public function getFileContent()
	{
		if (!$this->fileContent) {
			$this->getParsedContent();
		}


		return $this->fileContent;
	}

	/**
	 * Removes the BOM char from the beginning of the file.
	 * @param String $text
	 * @return String
	 */
	private function removeUtf8Bom($text)
	{
		$bom = pack('H*','EFBBBF');
		$text = preg_replace("/^$bom/", '', $text);
		return $text;
	}

}