<?php

/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.X
 *	LICENSE: FL4HLD2A8696 - http://www.flynax.com/license-agreement.html
 *	PRODUCT: Real Estate Agency
 *	DOMAIN: gevimmo.com
 *	FILE: RLDATAENTRIESIMPORT.CLASS.PHP
 *
 *	The software is a commercial product delivered under single, non-exclusive,
 *	non-transferable license for one domain or IP address. Therefore distribution,
 *	sale or transfer of the file in whole or in part without permission of Flynax
 *	respective owners is considered to be illegal and breach of Flynax License End
 *	User Agreement.
 *
 *	You are not allowed to remove this information from the file without permission
 *	of Flynax respective owners.
 *
 *	Flynax Classifieds Software 2017 |  All copyrights reserved.
 *
 *	http://www.flynax.com/
 *
 ******************************************************************************/

class rlDataEntriesImport extends reefless
{
	/**
	* tmp file locate
	**/
	var $tmpFile;

	/**
	* Default delimiters
	**/
	var $delimiters = array(
		'new_line' => "\n",
		'tab' => "\t",
		'comma' => ','
	);

	/**
	* Set delimiter
	**/
	var $delimiter;

	/**
	* Parent ID
	**/
	var $parentID;

	/**
	* Parent Key
	**/
	var $parentKey;

	/**
	* 
	**/
	var $data = array();

	/**
	* Class constructor
	**/
	function rlDataEntriesImport()
	{
		$this -> tmpFile = RL_UPLOAD .'dataEntriesImport.tmp';
	}

	/**
	* Main import function
	**/
	function import( $ext = false, $delimiter = false )
	{
		switch ($ext)
		{
			case 'csv':
			case 'txt':
				$handle = fopen($this -> tmpFile, 'r');
				while ( ($data = fgetcsv($handle)) !== false ) {
				    $source[] = $data;
				}
				break;

			case 'xls':
				require_once(RL_PLUGINS .'dataEntriesImport'. RL_DS .'phpExcel'. RL_DS .'PHPExcel'. RL_DS .'IOFactory.php');
				$objPHPExcel = PHPExcel_IOFactory::load($this -> tmpFile);
				$source = $objPHPExcel -> getActiveSheet() -> toArray('', true, true, false);
				break;
		}

		//
		if ( !empty($source) )
		{
			if ( $delimiter == 'another' )
				$this -> delimiter = $delimiter;
			else
				$this -> delimiter = $this -> delimiters[$delimiter];

			// get max position
			$sql = "SELECT MAX(`position`) AS `max` FROM `". RL_DBPREFIX ."data_formats` WHERE `Parent_ID` = '{$this -> parentID}'";
			$position = $this -> getRow($sql);
			$position = (int)$position['max'] + 1;

			// add item to storage
			foreach($source as $key => $item)
			{
				$item_name = trim($item[0]);
				$item_key = $this -> uniqKeyByName($item_name);
				$this -> addItem($item_key, $item_name, $position);

				//
				$position++;
			}

			//
			return $this -> save();
		}
		return false;
	}

	/**
	* Unique key by name
	*
	* recurcive method
	**/
	function uniqKeyByName( $name = false )
	{
		global $rlValid;

		// load the utf8 lib
		if ( false === function_exists('utf8_is_ascii') )
		{
			loadUTF8functions('ascii', 'utf8_to_ascii', 'unicode');
		}

		if ( !utf8_is_ascii( $name ) )
		{
			$name = utf8_to_ascii( $name );
		}
		$name = $rlValid -> str2key( $name );

		// check on exists key
		$exists = $this -> getRow("SELECT COUNT(`Key`) AS `count` FROM `". RL_DBPREFIX ."data_formats` WHERE `Key` REGEXP '^{$name}(_[0-9]+)*$'");
		if ( $exists['count'] > 0 )
		{
			return "{$name}_". (int)($exists['count'] + 1);
		}
		return $name;
	}

	/**
	* Add item to tmp storage
	**/
	function addItem( $dfKey = false, $dfName = false, $dfPosition = false )
	{
		$dfKey = $this -> parentKey .'_'. $dfKey;

		$this -> data['formats'][] = array(
			'Key' => $dfKey,
			'Parent_ID' => $this -> parentID,
			'Position' => $dfPosition
		);

		foreach( $GLOBALS['languages'] as $key => $language )
		{
			$this -> data['lang_keys'][] = array(
				'Key' => "data_formats+name+{$dfKey}",
				'Value' => $dfName,
				'Code' => $language['Code'],
				'Module' => 'common'
			);
		}
	}

	/**
	* Save to database
	**/
	function save()
	{
		global $rlActions;

		if ( $rlActions -> insert($this -> data['formats'], 'data_formats') )
		{
			$affectedRows = mysql_affected_rows();
			$res = $rlActions -> insert($this -> data['lang_keys'], 'lang_keys');

			return $affectedRows;
		}
		return false;
	}

	/**
	 * 
	 */
	 function ajaxGetDFLevel($parent = false, $df_level = false)
	 {
		 global $_response, $rlLang;

		$parent = (int)$parent;

		$sql = "SELECT `T1`.`ID`, `T1`.`Key`, `T2`.`Value` AS `name` FROM `". RL_DBPREFIX ."data_formats` AS `T1`";
		$sql .= "LEFT JOIN `". RL_DBPREFIX ."lang_keys` AS `T2` ON CONCAT('data_formats+name+',`T1`.`Key`) = `T2`.`Key` AND `T2`.`Code` = '". RL_LANG_CODE ."' ";
		$sql .= "WHERE `T1`.`Status` <> 'trash' AND `T1`.`Parent_ID` = {$parent} ";

		$df = $this -> getAll($sql);

		if ( !empty($df) )
		{
			$this -> loadClass('Json');
			$_response -> script("tmp_df_list[{$parent}] = ". $GLOBALS['rlJson'] -> encode($df) .";");
			$_response -> script("dfLevelHandler({$df_level});");
			unset($df);
		}
		else
		{
			$_response -> script("clearDfLevels({$df_level});");
		}

		return $_response;
	 }
}