<?php
/**
* @copyright (C) 2013 iJoomla, Inc. - All rights reserved.
* @license GNU General Public License, version 2 (http://www.gnu.org/licenses/gpl-2.0.html)
* @author iJoomla.com <webmaster@ijoomla.com>
* @url https://www.jomsocial.com/license-agreement
* The PHP code portions are distributed under the GPL license. If not otherwise stated, all images, manuals, cascading style sheets, and included JavaScript *are NOT GPL, and are released under the IJOOMLA Proprietary Use License v1.0
* More info at https://www.jomsocial.com/license-agreement
*/

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;
use Joomla\Registry\Registry;

// no direct access
defined('_JEXEC') or die('Restricted access');
require_once(COMMUNITY_COM_PATH.'/libraries/fields/profilefield.php');
class CFieldsLocation extends CProfileField
{

    public function getFieldData($field)
    {
        $fieldValue = json_decode(html_entity_decode($field['value']), true);

        if (empty($field['value'])) {
            return $field['value'];
        }

        return $fieldValue['name'] . (!empty($fieldValue['desc']) ? ' ('.$fieldValue['desc'].')' : '');
    }

    public function getFieldHTML($field, $required)
    {
        $params = new CParameter($field->params);
        $readonly = $params->get('readonly') && !COwnerHelper::isCommunityAdmin() ? ' readonly=""' : '';
        $required = ($field->required == 1) ? ' data-required="true"' : '';
        $style = $this->getStyle() ? ' style="' .$this->getStyle() . '"' : '';

        // reformat value

        $fieldName = '';
        $fieldDesc = '';
        $fieldLat = '';
        $fieldLng = '';

        try {
            $fieldValue = new Registry(htmlspecialchars_decode($field->value));
            $fieldName = $fieldValue->get('name', '');
            $fieldDesc = $fieldValue->get('desc', '');
            $fieldLat = $fieldValue->get('lat', '');
            $fieldLng = $fieldValue->get('lng', '');
        } catch (Exception $e) {
            $app = Factory::getApplication();
            $app->enqueueMessage('Field location value error. Id: '. $field->id, 'error');
        }

        $html  = '<div class="joms-location__wrapper">';
        $html .= '<input type="text" value="' . htmlspecialchars($fieldName) . '" id="field' . $field->id . '" name="field' . $field->id . '[name]" class="joms-input joms-input--location" autocomplete="off" '. $readonly . $required . $style .' />';
        $html .= '<input type="hidden" class="js-desc" name="field' . $field->id . '[desc]" value="' . htmlspecialchars($fieldDesc) . '"  />';
        $html .= '<input type="hidden" class="js-lat" name="field' . $field->id . '[lat]" value="' . htmlspecialchars($fieldLat) . '" />';
        $html .= '<input type="hidden" class="js-lng" name="field' . $field->id . '[lng]" value="' . htmlspecialchars($fieldLng) . '" />';
        $html .= '<div class="joms-location__description" data-tips="' . Text::_('COM_COMMUNITY_LOCATION_FIELD_DESCRIPTION', true) . '">' . ( $fieldDesc ? htmlspecialchars($fieldDesc) : Text::_('COM_COMMUNITY_LOCATION_FIELD_DESCRIPTION') ) . '</div>';
        $html .= '<div class="joms-location__dropdown">';
        $html .= '<div class="joms-location__loading"><img src="' . Uri::root(true) . '/components/com_community/assets/ajax-loader.gif" alt="loader"></div>';
        $html .= '<div class="joms-location__result">';
        $html .= '<div class="joms-location__header">' . Text::_('COM_COMMUNITY_SELECT_YOUR_LOCATION') . '</div>';
        $html .= '<div class="joms-location__map"></div>';
        $html .= '<div class="joms-location__list"></div>';
        $html .= '<div class="joms-location__close">&times;</div>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '</div>';

        $config = CFactory::getConfig();
        $document = Factory::getDocument();
        $document->addScriptDeclaration("joms_maps_api = '" . $config->get('maps_api', '') . "';");
        if ($config->get('maps_api', '') == "googlemap") {
            if (!$config->get('googleapikey', '')) {
                $html = Text::_("COM_COMMUNITY_FIELD_NO_API_KEY", true);
            } else {
                $document->addScriptDeclaration("joms_gmap_key = '" . $config->get('googleapikey', '') . "';");
            }
        } else {
            $path = Uri::root() . 'components/com_community/assets/source/js/utils/openstreet.js';

            
            
            $document->addScript($path);
            //test;
        }
        

        return $html;
    }

    public function isValid($value, $required)
    {
        $config = CFactory::getConfig();
        if (!$config->get('googleapikey', '')) {
            return true;
        }

        if ($required) {
            if (empty($value)) {
                return false;
            }
            $value = json_decode($value, true);
            $name = trim($value['name']);
            if (empty($name)) {
                return false;
            }
        }

        return true;
    }

    public function formatdata($value)
    {
        if ($value) {
            $finalvalue = array(
                'name' => $value['name'],
                'desc' => isset($value['desc']) ? $value['desc'] : '',
                'lat'  => isset($value['lat']) ? $value['lat'] : '',
                'lng'  => isset($value['lng']) ? $value['lng'] : ''
            );
        } else {
            $finalvalue = array();
        }

        return json_encode($finalvalue);
    }
}
