<?php

/******************************************************************************
 *  
 *  PROJECT: Flynax Classifieds Software
 *  VERSION: 4.5.2
 *  LICENSE: FL4HLD2A8696 - http://www.flynax.com/license-agreement.html
 *  PRODUCT: Real Estate Classifieds
 *  DOMAIN: savingrack.com
 *  FILE: RLLOCATIONFINDER.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 rlLocationFinder extends reefless
{
    /**
     * general url of loading google map
     *
     * @since 3.1.3
     * @var string
     */
    public $google_map_src = '';

    /**
    * class construct
    * 
    */
    public function __construct()
    {
        global $config;

        $this->google_map_src = '//maps.googleapis.com/maps/api/js?libraries=places&language=' . RL_LANG_CODE . '&key=' . $config['google_map_key'];
    }

	/**
	* clear session data
	*
	* @hook - seoBase
	*
	**/
	public function clear()
	{
		if ($_POST['xjxfun'] != 'ajaxBuild') {
			unset($_SESSION['locationFinder']['previousKey']);
		}
	}

	/**
	* assign location data
	**/
	public function assignLocation()
	{
		global $lf_listing_id;

        $use_module = $GLOBALS['listing_type']['Location_finder'];

        // admin panel, edit listing mode
        if (defined('REALM') && REALM == 'admin') {
            $use_module = $GLOBALS['rlListingTypes']->types[$GLOBALS['listing']['Listing_type']];
        }

		if (!$use_module) {
			return;
		}

		if (!$lf_listing_id) {
			return;
		}

		$this->loadClass('Actions');
		$data = $_POST['f']['lf'];
		
		if ($data['use'] && $data['lat'] != '' && $data['lng'] != '') {
			$update = array(
				'fields' => array(
					'Loc_latitude' => $data['lat'],
					'Loc_longitude' => $data['lng'],
					'lf_zoom' => $data['zoom'],
					'lf_use' => $data['use']
				),
				'where' => array(
					'ID' => $lf_listing_id
				)
			);
			
			$GLOBALS['rlActions']->updateOne($update, 'listings');
		} else if (!$data['use']) {
			$update = array(
				'fields' => array(
					'lf_zoom' => '',
					'lf_use' => '0'
				),
				'where' => array(
					'ID' => $_SESSION['add_listing']['listing_id']
				)
			);
			
			$GLOBALS['rlActions']->updateOne($update, 'listings');
		}
	}

	/**
	* re-define multifield data to build dropdowns depends of location finder map location  
	*
	* @hook - multifieldBuild
	*
	* @param array $params - array of hook related method parameters
	**/
	public function multifieldBuild(&$params){
		// exit if the previous key is the same
		$check_alt = $params[0] ? $params[0] : $params[6];
		if ($check_alt && $check_alt == $_SESSION['locationFinder']['previousKey']) {
			$params[7]->flExit = true;
			$params[7]->script("console.log('same')");
			return;
		}

		if ($params[6] && $this->getRow("SHOW TABLES LIKE '".RL_DBPREFIX."geo_mapping'")) {
			// save prev key
			$_SESSION['locationFinder']['previousKey'] = $check_alt;

			preg_match('/f\[(.*([0-9]+))\]/', $params[1], $matches);
			$params[1] = $matches[1];
			$params[3] = $matches[2]+1;

			// $params[7]->script("console.log('{$params[6]}')");
			// $params[7]->script("console.log('{$params[0]}')");
			// $params[7]->script("console.log('{$params[1]}')");

			// new database version check
			if ($this->getOne("SHOW COLUMNS FROM `".RL_DBPREFIX."geo_mapping` LIKE 'Verified'")) {
				$add_where = " AND `Verified` = '1'";
			}

			// alernative neighborhood search
			if ($params[0] && $add_where) {
				$params[0] = $this->getOne('Format_key', "`Google_key` = '{$params[0]}' AND `Neighborhood` = '1'" . $add_where, 'geo_mapping');
			}
			
			// standard region/city search
			if (!$params[0]) {
				$params[0] = $this->getOne('Format_key', "`Google_key` = '{$params[6]}'" . $add_where, 'geo_mapping');
			}

			if (!$params[0]) {
				$params[7]->script("if (typeof lfHighlightFields == 'function') { lfHighlightFields() }");
				$params[7]->flExit = true;
			}
		}
	}

    /**
     * @hook tplFooter
     * @since 3.1.3
     */
    public function hookTplFooter()
    {
        global $page_info;

        if ($GLOBALS['listing_type']['Location_finder']
            && !is_object($GLOBALS['rlStatic']) 
            && in_array($page_info['Key'], array('add_listing','edit_listing'))
        ) {
            echo '<script src="' . $this->google_map_src . '"></script>';
        }
    }

    /**
     * @hook boot
     * @since 3.1.3
     */
    public function hookBoot()
    {
        global $page_info, $rlListingTypes, $listing_type;

        if (!is_object($GLOBALS['rlStatic'])) {
            return;
        }

        if (!in_array($page_info['Controller'], array('add_listing', 'edit_listing'))) {
            return;
        }

        if ($listing_type['Location_finder']) {
            $GLOBALS['rlStatic']->addJS($this->google_map_src, array('add_listing','edit_listing'));
        }
    }
}