<?php

/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.8.0
 *	LISENSE: FL4HLD2A8696 - https://www.flynax.com/flynax-software-eula.html
 *	PRODUCT: Real Estate Script
 *	DOMAIN : immofil.com
 *	FILE   : RLIMPORTEXPORTCATEGORIES.CLASS.PHP
 *
 *	This script is a commercial software and any kind of using it must be
 *	coordinate with Flynax Owners Team and be agree to Flynax License Agreement
 *
 *	This block may not be removed from this file or any other files with out
 *	permission of Flynax respective owners.
 *
 *	Copyrights Flynax Classifieds Software | 2020
 *	https://www.flynax.com
 *
 ******************************************************************************/

class rlImportExportCategories extends reefless
{
	/**
	* 
	*/
	var $tmp_file;

	/**
	* 
	*/
	var $fields_map = array(
        0 => 'name',
        1 => 'parent',
        2 => 'path',
        3 => 'level',
        4 => 'locked'
	);

	/**
	* 
	*/
	var $calc_rows = 0;

	/**
	* 
	*/
	var $last_import_count = 0;

	/**
	* Class constructor
	*/
	function __construct()
	{
		$this -> tmp_file = RL_TMP .'upload'. RL_DS .'impotr_export_categories.tmp';
	}

	/**
	* Get categories list
	*/
	function getCategories($start, $stop, $import = false)
	{
        global $lang;

        require_once(RL_PLUGINS .'importExportCategories'. RL_DS .'phpExcel'. RL_DS .'PHPExcel'. RL_DS .'IOFactory.php');

        try {
            PHPExcel_Settings::setZipClass(PHPExcel_Settings::PCLZIP);
            $type = PHPExcel_IOFactory::identify($this->tmp_file);
            $objReader = PHPExcel_IOFactory::createReader($type);
            $objReader->setReadDataOnly(true);
            $objPHPExcel = $objReader->load($this->tmp_file);
            $source = $objPHPExcel->getActiveSheet()->toArray('', true, true, false);
        }
        catch (Exception $e) {
            $GLOBALS['rlDebug']->logger('imExpCategories: '. __FUNCTION__ .'(), Got exception: '. $e->getMessage());
            return array();
        }

        $categories = array();

        if (!empty($source)) {
            $this->calc_rows = count($source);
            $ltype_key = $_SESSION['imex_plugin']['listing_type'];
            $limit = min($this->calc_rows, $stop);
            $index = 0;

            for ($row = $start; $row < $limit; $row++) {
                for ($col = 0; $col < count($this->fields_map); $col++) {
                    $value = trim($source[$row][$col]);

                    // deep checking ;)
                    if ($col == 0 && empty($value)) {
                        continue;
                    }

                    if ($value != "") {
                        if ($this->fields_map[$col] == 'path') {
                            
                            $value = $this->str2path($value, true);
                        }
                        $categories[$index][$this->fields_map[$col]] = $value;
                    }
                }

                if (true !== $import) {
                    $categories[$index]['type'] = $lang['listing_types+name+' . $ltype_key]; // listing type
                }
                $index++;
            }
        }
		return $categories;
	}

	/**
	 * str2path
	 */
	function str2path($str, $keep_slashes = false)
	{
		$rx = $keep_slashes ? '\/' : '';
		$str = preg_replace("/[^a-z0-9{$rx}\.]+/i", '-', $str);
		$str = preg_replace('/\-+/', '-', $str);
		$str = strtolower( $str );
		$str = trim($str, '-');
		$str = trim($str, '/');
		$str = trim($str);

		return empty($str) ? false : $str;
	}

	/**
	* Import categories
	**/
	function import($categories = false, $ltype = false)
    {
		global $lang, $config, $rlValid, $rlCache, $rlCategories;

		if ( !empty( $categories ) && $ltype )
		{
			$addedCategoryCount = 0;
			$langs_add = false;
			$maxPos = $this -> getRow("SELECT MAX(`Position`) AS `max` FROM `". RL_DBPREFIX ."categories`");
			$maxPos = (int)$maxPos['max'];
            $module = $GLOBALS['rlDb']->columnExists('Target_key', 'lang_keys') ? 'category' : 'common';

            // Load the utf8 lib functions
            loadUTF8functions('ascii', 'utf8_to_ascii', 'unicode');

			foreach( $categories as $iKey => $iCat )
			{
				$maxPos++;
				$path = trim(str_replace('//', '/', $iCat['path']), '/');
				$path = $this -> str2path($path, true);

				$parentInfo = $this -> getParentInfo($path);
				$parent_id = (int)$parentInfo['ID'];
                $key = utf8_is_ascii($iCat['name']) ? $iCat['name'] : utf8_to_ascii($iCat['name']);
				$key = $rlValid->str2key($key);

                if ($parentInfo['Key']) {
                    $parent_key = str_replace($ltype . '_', '', $parentInfo['Key']);
                    $key = $parent_key . '_' . $key;
                }

                $iCat['name'] = str_replace('&amp;', '&', $iCat['name']);
				$c_name = $rlValid -> xSql($iCat['name']);
				$cTree = $parent_id ? "{$parentInfo['Tree']}.{$maxPos}": $maxPos;
                $category_key = $ltype . '_' . $key;

				// prepare data
				$categoryInfo = array(
					'Key' => $category_key,
					'Parent_ID' => $parent_id,
					'Position' => $maxPos,
					'Path' => $path,
					'Type' => $ltype,
					'Lock' => (int)$iCat['locked'],
					'Modified' => date('Y-m-d h:i:s'),
					'Status' => 'active',
					'Level' => (int)$iCat['level'],
					'Tree' => $cTree
				);

				// get category parents id
				if ($rlCategories && method_exists($rlCategories, 'getParentIDs')) {
					$parent_ids = $rlCategories->getParentIDs($parent_id, array($parent_id));
					$categoryInfo['Parent_IDs'] = implode(',', $parent_ids);
				}

				// make sql query
				$sql  = "INSERT INTO `". RL_DBPREFIX ."categories` ( `". implode('`,`', array_keys($categoryInfo)) ."` ) VALUES ";
				$sql .= "( '". implode("','", array_values($categoryInfo)) ."' )";

				if ( $this -> query($sql) )
				{
					$addedCategoryCount++;
					foreach( $GLOBALS['languages'] as $lkey => $lvalue )
					{
						$lang_keys[] = array(
							'Code' => $lvalue['Code'],
							'Module' => $module,
							'Status' => 'active',
							'Key' => 'categories+name+'. $category_key,
							'Value' => $c_name,
						);
					}
				}
			}

			// save phrases
			if ( !empty( $lang_keys ) )
			{
				$this -> loadClass('Actions');
				$GLOBALS['rlActions'] -> insert($lang_keys, 'lang_keys');

				$this -> last_import_count = $addedCategoryCount;
				$_SESSION['imex_plugin']['ic_count'] = intval($_SESSION['imex_plugin']['ic_count']) + $addedCategoryCount;

				return true;
			}
		}
		return false;
	}

	/**
	* Get parent info by children path
	*
	* @param string $path - children path
	*/
	function getParentInfo($path = false)
	{
		if ( empty($path) )
			return false;

		$path = explode('/', $path);
		array_pop($path);
		$parentPath = implode('/', $path);

		$sql  = "SELECT `ID`, `Key`, `Position`, `Tree` FROM `". RL_DBPREFIX ."categories` ";
		$sql .= "WHERE `Path` = '{$parentPath}' AND `Status` = 'active' LIMIT 1";
		$info = $this -> getRow($sql);

		return $info;
	}

	/**
     * Export categories
     */
	function export()
	{
		global $lang, $config;

		if (isset($_POST['cat_sticky'])) {
			$categoriesExport = array();
			$tmpCategories = $this->getAll("SELECT `ID` FROM `" . RL_DBPREFIX . "categories`");

			foreach($tmpCategories as $key => $entry) {
				array_push($categoriesExport, $entry['ID']);
			}
			unset($tmpCategories);
		}
		else {
			$categoriesExport = $_POST['categories'];
		}

		if (!empty($categoriesExport)) {
            // load library
            require_once(RL_PLUGINS .'importExportCategories'. RL_DS .'phpExcel'. RL_DS .'PHPExcel'. RL_DS .'IOFactory.php');

            // create a phpExcel object
            $objPHPExcel = new PHPExcel();

            /* set document properties */
            $objPHPExcel->getProperties()->setCreator($config['owner_name'])
                                         ->setLastModifiedBy($config['owner_name'])
                                         ->setTitle($cat_key)
                                         ->setSubject($cat_key)
                                         ->setDescription()// set description here
                                         ->setKeywords() // set keywords here
                                         ->setCategory(); // set file category here
            /* set document properties END */
            $objPHPExcel->setActiveSheetIndex(0);

            // collect categories
            $col = 1;
			foreach($categoriesExport as $key => $id) {
				$sql = "SELECT `Key`, `Parent_ID`, `Path`, `Lock`, `Level` FROM `". RL_DBPREFIX ."categories` ";
                $sql .= "WHERE `ID` = " . intval($id);
				$catInfo = $this->getRow($sql);

				if ($catInfo['Parent_ID'] != 0) {
					$parent_key = $this->getOne('Key', "`ID` = " . $catInfo['Parent_ID'], 'categories');
					$catInfo['parent'] = $lang['categories+name+' . $parent_key];
				}
				else {
					$catInfo['parent'] = '';
				}

				$catInfo['name'] = $lang['categories+name+' . $catInfo['Key']];
                unset($catInfo['Parent_ID'], $catInfo['Key']);

                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $col, $catInfo['name']);
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, $col, $catInfo['parent']);
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, $col, $catInfo['Path']);
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, $col, intval($catInfo['Level']));
                $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, $col, intval($catInfo['Lock']));
                $col++;
			}

			// send necessary headers
            $file_name = 'categories-' . date('M\.j\-Y');
            header("Content-Disposition: attachment; filename={$file_name}.xls");
            header("Content-Type: application/vnd.ms-excel;");
            header("Cache-Control: max-age=0");

            // force download
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
            $objWriter->save('php://output');
			exit;
		}
		else {
			$errors[] = $lang['importExportCategories_empty'];
		}
	}
}
