<?php
/*------------------------------------------------------------------------
# com_zhosmmap - Zh OpenStreetMap
# ------------------------------------------------------------------------
# author:    Dmitry Zhuk
# copyright: Copyright (C) 2011 zhuk.cc. All Rights Reserved.
# license:   http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
# website:   http://zhuk.cc
# Technical Support Forum: http://forum.zhuk.cc/
-------------------------------------------------------------------------*/
namespace ZhukDL\Component\ZhOSMMap\Site\Model;

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\MVC\Model\ItemModel;
use Joomla\CMS\Factory;
use Joomla\Utilities\ArrayHelper;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\Input\Input;

use Joomla\CMS\Uri\Uri;

use Joomla\Registry\Registry;

use ZhukDL\Component\ZhOSMMap\Site\Helper\MapPlacemarksHelper;

/**
 * ZhOSMMarker Model
 */
class PlacemarkModel extends ItemModel
{


    var $currentplacemark;
	
	var $item;
	
    /**
     * Method to auto-populate the model state.
     *
     * Note. Calling getState in this method will result in recursion.
     *
     * @return    void
     * @since    1.6
     */
    protected function populateState()
    {
		$app = Factory::getApplication();
		
        // menu item parameters
        $pk = $app->input->getInt('id');
        $this->setState('placemark.id', $pk);
        
        $load_bootstrap = $app->input->get('load_bootstrap', '', "INT");
        $this->setState('placemark.load_bootstrap', $load_bootstrap);            

        $thumbnail = $app->input->get('thumbnail', '', "INT");
        $this->setState('placemark.thumbnail', $thumbnail);            

        $imagegalery = $app->input->get('imagegalery', '', "INT");
        $this->setState('placemark.imagegalery', $imagegalery);        

        $hidedescriptionhtml = $app->input->get('hidedescriptionhtml', '', "INT");
        $this->setState('placemark.hidedescriptionhtml', $hidedescriptionhtml);            

        $showdescriptionfullhtml = $app->input->get('showdescriptionfullhtml', '', "INT");
        $this->setState('placemark.showdescriptionfullhtml', $showdescriptionfullhtml);        

        
        parent::populateState();
        
        
    }        
    
    
    public function getItem($pk = null)
    {
        if (!isset($this->item))
        {
           
			$id = $this->getState('placemark.id');
			
			$db = Factory::getDBO();
			$query = $db->getQuery(true);
			
			$query->select('h.*, '.
				' c.title as category, g.icontype as groupicontype, g.overridemarkericon as overridemarkericon, g.published as publishedgroup, g.markermanagerminzoom as markermanagerminzoom, g.markermanagermaxzoom as markermanagermaxzoom, g.activeincluster as activeincluster, '.
				' mp.lang as maplang')
				->from('#__zhosmmaps_markers as h')
				->leftJoin('#__zhosmmaps_maps as mp ON h.mapid=mp.id')
				->leftJoin('#__categories as c ON h.catid=c.id')
				->leftJoin('#__zhosmmaps_markergroups as g ON h.markergroup=g.id')
				->where('h.id='.$id);
				
			$db->setQuery($query);

			$data = $db->loadObject();

			$db->setQuery($query);

			if (!$this->item = $db->loadObject()) 
			{
				$this->setError($db->getError());
			}
	

        }
        
        $this->currentplacemark = $this->item;
        
        return $this->item;        
    }


    
    public function getMapScriptHeader() 
    {
		$retval = "";

		if ($this->currentplacemark) {
				
			$currentmarker = $this->currentplacemark;
        
			$params = ComponentHelper::getParams( 'com_zhosmmap' );

			$apiversion = $params->get( 'map_api_version', '' );

			$httpsprotocol = $params->get( 'httpsprotocol', '' );
			$urlProtocol = 'http';
			if ($httpsprotocol != "")
			{
				if ((int)$httpsprotocol == 0)
				{
					$urlProtocol = 'https';
				}
			}    

                
			//$mainScriptBegin = $current_custom_js_path . 'leaflet/';
			$mainScriptBegin = "https://unpkg.com/leaflet";

			$mainScriptMiddle = "";

			$mainScriptEnd = "/dist/leaflet";

			/*
			if ($this->mapapiversion != "")
			{
				$mainScriptMiddle = $this->mapapiversion;
			}
			 else 
			{
				$mainScriptMiddle = '1.6.0';
			}
			*/

			$mainScriptMiddle = "@1.9.3";


			$mainScriptBegin .= $mainScriptMiddle;


			$mainScript = $mainScriptBegin . $mainScriptEnd;


                
			$retval = $mainScript;
		}
            
    return $retval;
        
    }     
    
    
    public function getMapScript() 
    {

        $retval = "";

        $params = ComponentHelper::getParams( 'com_zhosmmap' );

        $apiversion = $params->get( 'map_api_version', '' );

        $httpsprotocol = $params->get( 'httpsprotocol', '' );
        $urlProtocol = 'http';
        if ($httpsprotocol != "")
        {
            if ((int)$httpsprotocol == 0)
            {
                $urlProtocol = 'https';
            }
        }
        
        if ($this->currentplacemark)
        {
            $currentmarker = $this->currentplacemark;
            
            // Get global params
            $params = ComponentHelper::getParams( 'com_zhosmmap' );

            $loadtype = (int)$params->get( 'loadtype', '' );
                       
			$imgpathIcons = URI::root() .'components/com_zhosmmap/assets/icons/';
			$imgpathUtils = URI::root() .'components/com_zhosmmap/assets/utils/';
			$directoryIcons = 'components/com_zhosmmap/assets/icons/';
			$imgpath4size = JPATH_SITE .'/components/com_zhgooglemap/assets/icons/';
		  

            $retval .= 'var icoIcon=\''.$imgpathIcons.'\';'."\n";
            $retval .= 'var icoUtils=\''.$imgpathUtils.'\';'."\n";
            $retval .= 'var icoDir=\''.$directoryIcons.'\';'."\n";
            
            $retval .= 'function initialize() {'."\n";

            if ($currentmarker->latitude != "" && $currentmarker->longitude != "")
            {
                    if ($currentmarker->latitude != "" && $currentmarker->longitude != "")
                    {

                        $retval .= 'latlng = L.latLng('.$currentmarker->latitude.', ' .$currentmarker->longitude.');' ."\n";
                                                $retval .= '    var myOptions = {'."\n";
                        $retval .= '        center: latlng,'."\n";
                        $retval .= '        zoom: 14,'."\n";
                        $retval .= '    };'."\n";

                        $retval .= 'map = L.map("OMapsID", myOptions);' ."\n";

                                                $retval .= ' var openStreetType = L.tileLayer(\'https://tile.openstreetmap.org/{z}/{x}/{y}.png\', {' ."\n";
                                                $retval .= '        attribution: \'&copy; <a href="'.$urlProtocol.'://www.openstreetmap.org/copyright">OpenStreetMap</a> '.Text::_('COM_ZHOSMMAP_MAP_CONTRIBUTORS').'\'' ."\n";
                                                $retval .= '    });' ."\n";


                                                $retval .= ' openStreetType.addTo(map);'."\n";
                                              
                                                if ((int)$currentmarker->baloon == 5
                                                   && (int)$currentmarker->overridemarkericon == 0) 
                                                {
                                                    $retval .= 'var marker = L.marker(latlng, {' ."\n";
                                                }
                                                else
                                                {
													$retval .= 'var marker = L.marker(latlng, {icon:' ."\n";
                                                    $retval .= MapPlacemarksHelper::get_placemark_icon_definition(
                                                                                            $imgpathIcons,
                                                                                            $imgpath4size,
                                                                                            $currentmarker). ',';  																						
                                                }
                                                $retval .= '});'."\n";
                        
                                                $retval .= 'marker.addTo(map);' ."\n";
                    }            
            }                


            $retval .= '}'."\n";
            if ($loadtype == "1")
            {
                $retval .= ' window.addEvent(\'domready\', initialize);' ."\n";
            }
            else if ($loadtype == "2")
            {
                $retval .= ' var tmpJQ = jQuery.noConflict();'."\n";
                $retval .= ' tmpJQ(document).ready(function() {initialize();});' ."\n";
            }            
            else
            {
                $retval .= ' function addLoadEvent(func) {' ."\n";
                $retval .= '  var oldonload = window.onload;' ."\n";
                $retval .= '  if (typeof window.onload != \'function\') {' ."\n";
                $retval .= '    window.onload = func;' ."\n";
                $retval .= '  } else {' ."\n";
                $retval .= '    window.onload = function() {' ."\n";
                $retval .= '      if (oldonload) {' ."\n";
                $retval .= '        oldonload();' ."\n";
                $retval .= '      }' ."\n";
                $retval .= '      func();' ."\n";
                $retval .= '    }' ."\n";
                $retval .= '  }' ."\n";
                $retval .= '}    ' ."\n";    

                $retval .= 'addLoadEvent(initialize);' ."\n";
            }

        }
        
        return $retval;
    }    
   

}
