<?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\Administrator\Controller;

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

use Joomla\CMS\MVC\Controller\BaseController;

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Uri\Uri;


class DisplayController extends BaseController {
	
	var $inserted = 0;
    var $errors = 0;
    var $warnings = 0;
	
    /**
     * The default view for the display method.
     *
     * @var string
     */
    protected $default_view = 'dashboard';
    
    public function display($cachable = false, $urlparams = array()) {
        
        $view   = $this->input->get('view', 'dashboard');
		$layout = $this->input->get('layout', 'default');
		$id     = $this->input->getInt('id');
        
        return parent::display();
    }
    

        function insertLog($extension, $kind, $title, $id_target, $id_src, $id_find, $description, $remark) {
            
            $rec2ins = new \stdClass();
            
            $rec2ins->extension = $extension;
            $rec2ins->title = $title;           
            $rec2ins->kind = $kind;
            $rec2ins->description = $description;
            $rec2ins->remarks = $remark;
            $rec2ins->id = null;

            $rec2ins->id_target = $id_target;
            $rec2ins->id_source = $id_src;
            $rec2ins->id_find = $id_find;

            
            $result = Factory::getDbo()->insertObject('#__zhosmmaps_log', $rec2ins, 'id');

        }

        function deleteLog($extension) {
            
            $db = Factory::getDBO();

            $query = $db->getQuery(true);

            $query->delete($db->quoteName('#__zhosmmaps_log'));
            $query->where('extension='.$db->quote($extension));

            $db->setQuery($query);

            $result = $db->execute();
            
        }
        
        function getCategoryID($extension, $catid, $pfx) {
            
            $ret_val = 0;
            
            
            if ($catid != 0)
            {
                $db = Factory::getDBO();

                $query = $db->getQuery(true);

                $query->select('h.id')
                    ->from('#__categories as t')
                    ->leftJoin('#__categories as h ON h.path=t.path')
                    ->where('h.extension=\'com_zhosmmap\' and t.extension='.$db->quote('com_zh'.$extension.'map').' and t.id='.(int)$catid)
                ;          

                $db->setQuery($query);        

                $cat = $db->loadObject();

                if (isset($cat) && !empty($cat)) 
                {
                    $ret_val = $cat->id;
                }
                else 
                {
                   $ret_val = 0;
                }
            }

            return $ret_val;

        }

        function getGroupID($extension, $groupid, $pfx) {
            
            $ret_val = 0;
            
            
            if ($groupid != 0)
            {
                $db = Factory::getDBO();

                $query = $db->getQuery(true);

                $query->select('h.id')
                    ->from($db->quoteName('#__zh'.$extension.'maps_markergroups', 't'))
                    ->leftJoin('#__zhosmmaps_markergroups as h ON h.title=t.title')
                    ->where('t.id='.(int)$groupid)
                ;          
 
                $db->setQuery($query);        

                $grp = $db->loadObject();

                if (isset($grp) && !empty($grp)) 
                {
                    $ret_val = $grp->id;
                }
                else 
                {
                   $ret_val = '';
                }
            }

            return $ret_val;

        }
              
        function insertGroup($extension, $group_src, $pfx) {
            $currentUser = Factory::getUser();
            //$currentUser->id;
            $grp2ins = new \stdClass();
            
            $grp2ins->title = $group_src->title;
            
            $grp2ins->icontype = $group_src->icontype;
            $grp2ins->iconofsetx = $group_src->iconofsetx;
            $grp2ins->iconofsety = $group_src->iconofsety;
            $grp2ins->overridemarkericon = $group_src->overridemarkericon;
            $grp2ins->markermanagerminzoom = $group_src->markermanagerminzoom;
            $grp2ins->markermanagermaxzoom = $group_src->markermanagermaxzoom;
            $grp2ins->activeincluster = $group_src->activeincluster;
            $grp2ins->description = $group_src->description;
            $grp2ins->published = $group_src->published;
            $grp2ins->publish_up = $group_src->publish_up;
            $grp2ins->publish_down = $group_src->publish_down;
            $grp2ins->ordering = $group_src->ordering;
            $grp2ins->userorder = $group_src->userorder;
            if ($extension == 'google')
            {
                $grp2ins->overridegroupicon = $group_src->overridegroupicon;
            }
            else if ($extension == 'yandex')
            {
                // this properties will be ignored
                //$grp2ins->showiconcontent = $group_src->showiconcontent;
                //$grp2ins->preseticontype = $group_src->preseticontype;
                //$grp2ins->presettitle = $group_src->presettitle;
            }
            $grp2ins->catid = $this->getCategoryID($extension, $group_src->catid, $pfx);
            
            $grp2ins->id = null;
            
            $result = Factory::getDbo()->insertObject('#__zhosmmaps_markergroups', $grp2ins, 'id');
            
            $new_id = $grp2ins->id;

            $this->inserted += 1;
            if ($group_src->catid != 0 && $grp2ins->catid == 0)
            {
                $this->insertLog($extension, Text::_('COM_ZHOSMMAP_UTILS_GROUP'), Text::_('COM_ZHOSMMAP_UTILS_CATEGORY_NOT_FOUND'), $new_id, $group_src->id, $group_src->catid, "", "");
                $this->warnings += 1;
            }
            
            return $new_id;
        }
        
        function insertPlacemark($extension, $marker_src, $mapid_to, $pfx) {
            $currentUser = Factory::getUser();
            //$currentUser->id;
            $marker2ins = new \stdClass();
            
            $marker2ins->mapid = (int)$mapid_to;

            $marker2ins->title = $marker_src->title;           
            $marker2ins->latitude = $marker_src->latitude;
            $marker2ins->longitude = $marker_src->longitude;

            $marker2ins->icontype = $marker_src->icontype;
            $marker2ins->iconofsetx = $marker_src->iconofsetx;
            $marker2ins->iconofsety = $marker_src->iconofsety;

            
            if ($extension == 'google')
            {
                // todo - animation
                if ($marker_src->baloon == 0
                 || $marker_src->baloon == 3
                )
                {
                    $marker2ins->baloon = $marker_src->baloon;
                }
                else
                {
                    $marker2ins->baloon = 3;
                }
                
                if ($marker_src->actionbyclick == 0
                 || $marker_src->actionbyclick == 1
                 || $marker_src->actionbyclick == 2
                 || $marker_src->actionbyclick == 3
                 || $marker_src->actionbyclick == 4
                )
                {
                    $marker2ins->actionbyclick = $marker_src->actionbyclick;
                }
                else
                {
                    $marker2ins->actionbyclick = 1;
                }                
                
                
                // it is not in yandex
                $marker2ins->descriptionfullhtml = $marker_src->descriptionfullhtml;
                $marker2ins->hoverhtml = $marker_src->hoverhtml;
                
                // do not load infobubble style reference
                //$marker2ins->tabid = $marker_src->tabid;
                
                $marker2ins->tab1 = $marker_src->tab1;
                $marker2ins->tab2 = $marker_src->tab2;
                $marker2ins->tab3 = $marker_src->tab3;
                $marker2ins->tab4 = $marker_src->tab4;
                $marker2ins->tab5 = $marker_src->tab5;
                $marker2ins->tab6 = $marker_src->tab6;
                $marker2ins->tab7 = $marker_src->tab7;
                $marker2ins->tab8 = $marker_src->tab8;
                $marker2ins->tab9 = $marker_src->tab9;
                $marker2ins->tab10 = $marker_src->tab10;
                $marker2ins->tab11 = $marker_src->tab11;
                $marker2ins->tab12 = $marker_src->tab12;
                $marker2ins->tab13 = $marker_src->tab13;
                $marker2ins->tab14 = $marker_src->tab14;
                $marker2ins->tab15 = $marker_src->tab15;
                $marker2ins->tab16 = $marker_src->tab16;
                $marker2ins->tab17 = $marker_src->tab17;
                $marker2ins->tab18 = $marker_src->tab18;
                $marker2ins->tab19 = $marker_src->tab19;
                $marker2ins->tab1title = $marker_src->tab1title;
                $marker2ins->tab2title = $marker_src->tab2title;
                $marker2ins->tab3title = $marker_src->tab3title;
                $marker2ins->tab4title = $marker_src->tab4title;
                $marker2ins->tab5title = $marker_src->tab5title;
                $marker2ins->tab6title = $marker_src->tab6title;
                $marker2ins->tab7title = $marker_src->tab7title;
                $marker2ins->tab8title = $marker_src->tab8title;
                $marker2ins->tab9title = $marker_src->tab9title;
                $marker2ins->tab10title = $marker_src->tab10title;
                $marker2ins->tab11title = $marker_src->tab11title;
                $marker2ins->tab12title = $marker_src->tab12title;
                $marker2ins->tab13title = $marker_src->tab13title;
                $marker2ins->tab14title = $marker_src->tab14title;
                $marker2ins->tab15title = $marker_src->tab15title;
                $marker2ins->tab16title = $marker_src->tab16title;
                $marker2ins->tab17title = $marker_src->tab17title;
                $marker2ins->tab18title = $marker_src->tab18title;
                $marker2ins->tab19title = $marker_src->tab19title;
                $marker2ins->tab1image = $marker_src->tab1image;
                $marker2ins->tab2image = $marker_src->tab2image;
                $marker2ins->tab3image = $marker_src->tab3image;
                $marker2ins->tab4image = $marker_src->tab4image;
                $marker2ins->tab5image = $marker_src->tab5image;
                $marker2ins->tab6image = $marker_src->tab6image;
                $marker2ins->tab7image = $marker_src->tab7image;
                $marker2ins->tab8image = $marker_src->tab8image;
                $marker2ins->tab9image = $marker_src->tab9image;
                $marker2ins->tab10image = $marker_src->tab10image;
                $marker2ins->tab11image = $marker_src->tab11image;
                $marker2ins->tab12image = $marker_src->tab12image;
                $marker2ins->tab13image = $marker_src->tab13image;
                $marker2ins->tab14image = $marker_src->tab14image;
                $marker2ins->tab15image = $marker_src->tab15image;
                $marker2ins->tab16image = $marker_src->tab16image;
                $marker2ins->tab17image = $marker_src->tab17image;
                $marker2ins->tab18image = $marker_src->tab18image;
                $marker2ins->tab19image = $marker_src->tab19image;
                $marker2ins->tab_info = $marker_src->tab_info;       
                
                $marker2ins->gogoogle = $marker_src->gogoogle;
                
                $marker2ins->labelanchorx = $marker_src->labelanchorx;
                $marker2ins->labelanchory = $marker_src->labelanchory;
                $marker2ins->labelclass = $marker_src->labelclass;
                $marker2ins->labelcontent = $marker_src->labelcontent;    
                
                $marker2ins->attributesdetail = $marker_src->attributesdetail;
                
                $marker2ins->toolbarcontact = $marker_src->toolbarcontact;
                $marker2ins->toolbararticle = $marker_src->toolbararticle;
                $marker2ins->toolbardetail = $marker_src->toolbardetail;   
                
                $marker2ins->hrefcontact = $marker_src->hrefcontact;
                $marker2ins->hrefarticle = $marker_src->hrefarticle;
                $marker2ins->hrefdetail = $marker_src->hrefdetail;
                $marker2ins->articleid = $marker_src->articleid;
                $marker2ins->showgps = $marker_src->showgps;
                $marker2ins->iframearticleclass = $marker_src->iframearticleclass;
                        
            }
            else if ($extension == 'yandex')
            {
                if ($marker_src->showiconcontent == 0
                )
                {
                    $marker2ins->baloon = 3;
                }
                else
                {
                    $marker2ins->baloon = 3;
                }
                

                $marker2ins->actionbyclick = $marker_src->actionbyclick;
            
            }
            
			if (isset($marker_src->addresstext)) {
				$marker2ins->addresstext = $marker_src->addresstext;
			}
            $marker2ins->openbaloon = $marker_src->openbaloon;
            $marker2ins->zoombyclick = $marker_src->zoombyclick;
            $marker2ins->description = $marker_src->description;
            $marker2ins->descriptionhtml = $marker_src->descriptionhtml;
            $marker2ins->published = $marker_src->published;
            $marker2ins->hrefsite = $marker_src->hrefsite;
            $marker2ins->hrefimage = $marker_src->hrefimage;
            $marker2ins->hrefimagethumbnail = $marker_src->hrefimagethumbnail;
            $marker2ins->hrefsitename = $marker_src->hrefsitename;
            $marker2ins->markercontent = $marker_src->markercontent;
            $marker2ins->contactid = $marker_src->contactid;
            $marker2ins->createdbyuser = $marker_src->createdbyuser;
            $marker2ins->showcontact = $marker_src->showcontact;
            $marker2ins->showuser = $marker_src->showuser;
            $marker2ins->publish_up = $marker_src->publish_up;
            $marker2ins->publish_down = $marker_src->publish_down;
            $marker2ins->createddate = $marker_src->createddate;
            $marker2ins->userprotection = $marker_src->userprotection;
            $marker2ins->params = $marker_src->params;
            $marker2ins->attribute1 = $marker_src->attribute1;
            $marker2ins->attribute2 = $marker_src->attribute2;
            $marker2ins->attribute3 = $marker_src->attribute3;
            $marker2ins->attribute4 = $marker_src->attribute4;
            $marker2ins->attribute5 = $marker_src->attribute5;
            $marker2ins->attribute6 = $marker_src->attribute6;
            $marker2ins->attribute7 = $marker_src->attribute7;
            $marker2ins->attribute8 = $marker_src->attribute8;
            $marker2ins->attribute9 = $marker_src->attribute9;
            
            $marker2ins->ordering = $marker_src->ordering;
            $marker2ins->rating_value = $marker_src->rating_value;
            $marker2ins->rating_count = $marker_src->rating_count;

            $marker2ins->includeinlist = $marker_src->includeinlist;
            $marker2ins->access = $marker_src->access;
            $marker2ins->alias = $marker_src->alias;


            $marker2ins->userorder = $marker_src->userorder;
            $marker2ins->preparecontent = $marker_src->preparecontent;

            // $marker2ins->tag_show = $marker_src->tag_show;
            // $marker2ins->tag_style = $marker_src->tag_style;
              
            $marker2ins->markergroup = $this->getGroupID($extension, $marker_src->markergroup, $pfx);
            
            $marker2ins->catid = $this->getCategoryID($extension, $marker_src->catid, $pfx);
            
            $marker2ins->id = null;
            
            $result = Factory::getDbo()->insertObject('#__zhosmmaps_markers', $marker2ins, 'id');
            
            $new_id = $marker2ins->id;

            $this->inserted += 1;
            if ($marker_src->catid != 0 && $marker2ins->catid == 0)
            {
                $this->insertLog($extension, Text::_('COM_ZHOSMMAP_UTILS_PLACEMARK'), Text::_('COM_ZHOSMMAP_UTILS_CATEGORY_NOT_FOUND'), $new_id, $marker_src->id, $marker_src->catid, "", "");
                $this->warnings += 1;
            }
            if ($marker_src->markergroup != 0 && $marker2ins->markergroup == '')
            {
                $this->insertLog($extension, Text::_('COM_ZHOSMMAP_UTILS_PLACEMARK'), Text::_('COM_ZHOSMMAP_UTILS_GROUP_NOT_FOUND'), $new_id, $marker_src->id, $marker_src->markergroup, "", "");
                $this->warnings += 1;
            }
            
            return $new_id;
        }
        
        function loadGroup($extension, $group_src, $pfx) {
            
            
            $db = Factory::getDBO();

            $query = $db->getQuery(true);

            $query->select('h.* ')
                ->from('#__zhosmmaps_markergroups as h')
                ->where('h.title='.$db->quote($group_src->title))
            ;          
            
            $db->setQuery($query);        

            $grp = $db->loadObject();
            
            if (isset($grp) && !empty($grp)) 
            {
                // skipping
                
            }
            else 
            {
                $new_id = $this->insertGroup($extension, $group_src, $pfx);
            }

        }
        
        function loadPlacemark($extension, $marker_src, $mapid_to, $pfx) {
            
            
            $db = Factory::getDBO();

            $query = $db->getQuery(true);

            $query->select('h.* ')
                ->from('#__zhosmmaps_markers as h')
                ->where('h.title='.$db->quote($marker_src->title).' and h.mapid='.(int)$mapid_to)
            ;          
            
            $db->setQuery($query);        

            $grp = $db->loadObject();
            
            if (isset($grp) && !empty($grp)) 
            {
                // skipping
                
            }
            else 
            {
                $new_id = $this->insertPlacemark($extension, $marker_src, $mapid_to, $pfx);
            }

        }
        
        function forEachGroup($extension, $pfx) {
            
            
            $db = Factory::getDBO();

            $query = $db->getQuery(true);

            $query->select('h.* ')
                ->from($db->quoteName('#__zh'.$extension.'maps_markergroups', 'h'))
                ->where('h.published IN (0, 1)');
            ;

            $db->setQuery($query);        

            $groups = $db->loadObjectList();
         
            if (isset($groups) && !empty($groups)) 
            {
                foreach ($groups as $key => $current_group) 
                {
                    $this->loadGroup($extension, $current_group, $pfx);
                }
            }

            
        }

        function forEachPlacemark($extension, $mapid_from, $mapid_to, $pfx) {
            
            
            $db = Factory::getDBO();

            $query = $db->getQuery(true);

            $query->select('h.* ')
                ->from($db->quoteName('#__zh'.$extension.'maps_markers', 'h'))
                ->where('h.published IN (0, 1) and h.mapid='.(int)$mapid_from);
            ;

            $db->setQuery($query);        

            $markers = $db->loadObjectList();
         
            if (isset($markers) && !empty($markers)) 
            {
                foreach ($markers as $key => $current_marker) 
                {
                    $this->loadPlacemark($extension, $current_marker, $mapid_to, $pfx);
                }
            }

            
        }
        
        function cloneGroups($extension) {
            Session::checkToken() or jexit(Text::_('JINVALID_TOKEN'));
            // Get the model
            $model = $this->getModel();
            
            $app = Factory::getApplication(); 
            $input = $app->input; 
            // get the data from the HTTP POST request
            $data  = $input->get('jform', array(), 'array');

            // Get the current URI to set in redirects. As we're handling a POST, 
            // this URI comes from the <form action="..."> attribute in the layout file above
            $currentUri = (string)Uri::getInstance();
          
            $flg_validate_text = "";
            $flg_validate_error = false;
             
            if ($flg_validate_error)
            {
                $app->enqueueMessage(Text::_('COM_ZHOSMMAP_MAPBUFMRKS_IMPORT_ERROR_REQUIRED'), 'error');
                $app->enqueueMessage("<br />".$flg_validate_text, 'error');
                return false;
            }
            else
            {      
                $responseVar = "";
                $ret_val = "";
                $ret_status = 0;

                $this->inserted = 0;
                $this->errors = 0;
                $this->warnings = 0;

                $this->deleteLog($extension);

                $this->forEachGroup($extension, "");

                if ($this->inserted != 0) 
                {
                    $ret_status = 1;

                    $ret_val = '<span>'.Text::_('COM_ZHOSMMAP_UTILS_LOG_INSERTED').' '.$this->inserted.'.</span>';
                    if ($this->warnings != 0)
                    {
                        $ret_val .= '<br /><span>'.Text::_('COM_ZHOSMMAP_UTILS_LOG_WARNINGS').' '.$this->warnings.'.</span><br /><span>'.Text::_('COM_ZHOSMMAP_UTILS_CHECK_LOG').'</span>';
                        $ret_status = 2;
                    }
                    /*
                    $responseVar = array(
                         'dataexists'=>$ret_status
                        ,'logtext'=> $ret_val
                        ); 
                    */
                }
                else
                {
                    $ret_val = Text::_('COM_ZHOSMMAP_UTILS_LOG_NO_NEW_DATA_FOUND');
                    /*
                    $responseVar = array(
                         'dataexists'=>$ret_status
                        ,'errortext'=> $ret_val
                        ); 
                    */
                }
            
                //echo (json_encode($responseVar));
                if ($ret_status == 1)
                {
                    $app->enqueueMessage($ret_val, 'message');
                }
                else if ($ret_status == 2)
                {
                    $app->enqueueMessage($ret_val, 'warning');
                }
                else
                {
                    $app->enqueueMessage($ret_val, 'notice');
                }
                
            }

            return true;
            
            
        }

        function clonePlacemarks($extension) {
            Session::checkToken() or jexit(Text::_('JINVALID_TOKEN'));
            // Get the model
            $model = $this->getModel();
            
            $app = Factory::getApplication(); 
            $input = $app->input; 
            // get the data from the HTTP POST request
            $data  = $input->get('jform', array(), 'array');

            // Get the current URI to set in redirects. As we're handling a POST, 
            // this URI comes from the <form action="..."> attribute in the layout file above
            $currentUri = (string)Uri::getInstance();
          
            $flg_validate_text = "";
            $flg_validate_error = false;
            
            $mapid_from = $data["mapid_from"];
            $mapid_to = $data["mapid_to"];
             
            if (!isset($mapid_from) || $mapid_from == "" || (int)$mapid_from == 0)
            {
                $flg_validate_error = true;
                $flg_validate_text .= Text::_('COM_ZHOSMMAP_MAPBUFMRKS_IMPORT_ERROR_INVALID')." ".Text::_('COM_ZHOSMMAP_UTILS_PLACEMARK_MAP_SRC_LABEL')."<br />";
            }
            if (!isset($mapid_to) || $mapid_to == "" || (int)$mapid_to == 0)
            {
                $flg_validate_error = true;
                $flg_validate_text .= Text::_('COM_ZHOSMMAP_MAPBUFMRKS_IMPORT_ERROR_INVALID')." ".Text::_('COM_ZHOSMMAP_UTILS_PLACEMARK_MAP_TRG_LABEL')."<br />";
            }
            
            if ($flg_validate_error)
            {
                $app->enqueueMessage(Text::_('COM_ZHOSMMAP_MAPBUFMRKS_IMPORT_ERROR_REQUIRED'), 'error');
                $app->enqueueMessage("<br />".$flg_validate_text, 'error');
                return false;
            }
            else
            {
                $responseVar = "";
                $ret_val = "";
                $ret_status = 0;

                $this->inserted = 0;
                $this->errors = 0;
                $this->warnings = 0;

                $this->deleteLog($extension);

                $this->forEachPlacemark($extension, $mapid_from, $mapid_to, "");

                if ($this->inserted != 0) 
                {
                    $ret_status = 1;

                    $ret_val = '<span>'.Text::_('COM_ZHOSMMAP_UTILS_LOG_INSERTED').' '.$this->inserted.'.</span>';
                    if ($this->warnings != 0)
                    {
                        $ret_val .= '<br /><span>'.Text::_('COM_ZHOSMMAP_UTILS_LOG_WARNINGS').' '.$this->warnings.'.</span><br /><span>'.Text::_('COM_ZHOSMMAP_UTILS_CHECK_LOG').'</span>';
                        $ret_status = 2;
                    }
                    /*
                    $responseVar = array(
                         'dataexists'=>$ret_status
                        ,'logtext'=> $ret_val
                        ); 
                    
                    */
                }
                else
                {
                    $ret_val = Text::_('COM_ZHOSMMAP_UTILS_LOG_NO_NEW_DATA_FOUND');
                    /*
                    $responseVar = array(
                         'dataexists'=>$ret_status
                        ,'errortext'=> $ret_val
                        ); 
                    */
                }

                //echo (json_encode($responseVar));
                if ($ret_status == 1)
                {
                    $app->enqueueMessage($ret_val, 'message');
                }
                else if ($ret_status == 2)
                {
                    $app->enqueueMessage($ret_val, 'warning');
                }
                else
                {
                    $app->enqueueMessage($ret_val, 'notice');
                }
            }
            
            return true;
        }
     
        public function cloneGroupsGoogle() {
            $extension = 'google';
             
            return $this->cloneGroups($extension);
        }
       
        public function cloneGroupsYandex() {
            $extension = 'yandex';
    
            return $this->cloneGroups($extension);
        }

        public function clonePlacemarksGoogle() {
            $extension = 'google';
            
            $this->clonePlacemarks($extension);
        }
        
        public function clonePlacemarksYandex() {
            $extension = 'yandex';
              
            $this->clonePlacemarks($extension);
        }
			
}
