<?php
/**
 * @package DJ-Events
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 * @developer Szymon Woronowski - szymon.woronowski@design-joomla.eu
 *
 */

defined('_JEXEC') or die('Restricted access');

class DJEventsControllerCpanel extends JControllerForm
{
    public function migrateTags()
    {
		$app = JFactory::getApplication();
		$db = JFactory::getDBO();
		$params = JComponentHelper::getParams('com_djevents');

		if($params->get('tags_type', 'djevents') == 'joomla'){

            $tag_helper = new JHelperTags;
            $migrate_counter = 0;
            
            $query = "SELECT id, name FROM #__djev_tags";
			$db->setQuery($query);
            $core_tags = $db->loadObjectList();

            foreach($core_tags as $c_tag){

                $query = "SELECT id FROM #__tags WHERE title=".$db->quote($c_tag->name);
                $db->setQuery($query);
                $tag_exists = $db->loadResult();
                if(!$tag_exists){
                    $j_tag = $tag_helper->createTagsFromField(array('#new#'.$c_tag->name));
                    $j_tag_id = $j_tag[0];

                    $query = "SELECT event_id FROM #__djev_tags_xref WHERE tag_id=".$c_tag->id;
                    $db->setQuery($query);
                    $tag_event_ids = $db->loadColumn();

                    foreach($tag_event_ids as $ev_id){
                        $query = "INSERT INTO #__djev_jtags_xref(tag_id, event_id) VALUES(".$j_tag_id.",".$ev_id.")";
                        $db->setQuery($query);
                        $db->execute();
                    }

                    $migrate_counter++;
                }
            }

            $app->redirect('index.php?option=com_djevents', JTEXT::sprintf('COM_DJEVENTS_N_TAGS_MIGRATED', $migrate_counter));
		}
	}
}
