<?php
/*
 * @package Joomla 3.0
 * @copyright Copyright (C) 2005 Open Source Matters. All rights reserved.
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 *
 * @component XMovie Component
 * @copyright Copyright (C) Dana Harris optikool.com
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 */
defined('_JEXEC') or die('Restricted access');

jimport('joomla.database.databasequery');

function XMovieBuildRoute(&$query) 
{
    $segments = array();
    
    // Get a menu item based on Itemid or currently active
    $app = JFactory::getApplication();
    $menu = $app -> getMenu();
    $params = JComponentHelper::getParams('com_xmovie');
    $advanced = $params -> get('sef_advanced_link', 0);

    // We need a menu item.  Either the one specified in the query, or the current active one if none specified
    if (empty($query['Itemid'])) {
        $menuItem = $menu -> getActive();
        $menuItemGiven = false;
    } else {
        $menuItem = $menu -> getItem($query['Itemid']);
        $menuItemGiven = true;
    }

    // Check again
    if ($menuItemGiven && isset($menuItem) && $menuItem -> component != 'com_xmovie') {
        $menuItemGiven = false;
        unset($query['Itemid']);
    }

    if (isset($query['view'])) {
        $view = $query['view'];
    } else {
        // We need to have a view in the query or it is an invalid URL
        return $segments;
    }

    // Are we dealing with an article or category that is attached to a menu item?
    if (($menuItem instanceof stdClass) && $menuItem -> query['view'] == $query['view'] && isset($query['id']) && $menuItem -> query['id'] == (int)$query['id']) {
        unset($query['view']);

        if (isset($query['catid'])) {
            unset($query['catid']);
        }

        unset($query['id']);

        return $segments;
    }

    if ($view == 'category' || $view == 'single') {
        if (!$menuItemGiven) {
            $segments[] = $view;
        }

        unset($query['view']);

        if ($view == 'single') {
            if (isset($query['id']) && isset($query['catid']) && $query['catid']) {
                $catid = $query['catid'];

                // Make sure we have the id and the alias
                if (strpos($query['id'], ':') === false) {
                    $db = JFactory::getDbo();
                    $dbQuery = $db -> getQuery(true) -> select('alias') -> from('#__xmovie_movies') -> where('id=' . (int)$query['id']);
                    $db -> setQuery($dbQuery);
                    $alias = $db -> loadResult();
                    $query['id'] = $query['id'] . ':' . $alias;
                }
            } else {
                // We should have these two set for this view.  If we don't, it is an error
                return $segments;
            }
        } else {
            if (isset($query['id'])) {
                $catid = $query['id'];
            } else {
                // We should have id set for this view.  If we don't, it is an error
                return $segments;
            }
        }

        if ($menuItemGiven && isset($menuItem -> query['id'])) {
            $mCatid = $menuItem -> query['id'];
        } else {
            $mCatid = 0;
        }

        $categories = JCategories::getInstance('XMovie');
        $category = $categories -> get($catid);

        if (!$category) {
            // We couldn't find the category we were given.  Bail.
            return $segments;
        }

        $path = array_reverse($category -> getPath());

        $array = array();

        foreach ($path as $id) {
            if ((int)$id == (int)$mCatid) {
                break;
            }

            list($tmp, $id) = explode(':', $id, 2);

            $array[] = $id;
        }

        $array = array_reverse($array);

        if (!$advanced && count($array)) {
            $array[0] = (int)$catid . ':' . $array[0];
        }

        $segments = array_merge($segments, $array);

        if ($view == 'single') {
            if ($advanced) {
                list($tmp, $id) = explode(':', $query['id'], 2);
            } else {
                $id = $query['id'];
            }

            $segments[] = $id;
        }

        unset($query['id']);
        unset($query['catid']);
    }

    $total = count($segments);

    for ($i = 0; $i < $total; $i++) {
        $segments[$i] = str_replace(':', '-', $segments[$i]);
    }

    return $segments;
}

function XMovieParseRoute(&$segments) 
{
    $total = count($segments);
    $vars = array();
    
    // Get the active menu item.
    $app = JFactory::getApplication();
    $menu = $app->getMenu();
    $item = $menu->getActive();
    $params = JComponentHelper::getParams('com_xmovie');
    $advanced = $params->get('sef_advanced_link', 0);
    $db = JFactory::getDbo();

    // Count route segments
    $count = count($segments);
    
    /*
	* Standard routing for articles.  If we don't pick up an Itemid then we get the view from the segments
	* the first segment is the view and the last segment is the id of the article or category.
	*/
    if (!isset($item)) {
        $vars['view'] = $segments[0];
        $vars['id'] = $segments[$count - 1];

        return $vars;
    }

    /*
	* If there is only one segment, then it points to either an article or a category.
	* We test it first to see if it is a category.  If the id and alias match a category,
	* then we assume it is a category.  If they don't we assume it is an article
	*/
    if ($count == 1) {
        // We check to see if an alias is given.  If not, we assume it is an article
        if (strpos($segments[0], ':') === false) {
            $vars['view'] = 'single';
            $vars['id'] = (int) $segments[0];
            
            return $vars;
        }

        list($id, $alias) = explode(':', $segments[0], 2);

        // First we check if it is a category
        $category = JCategories::getInstance('XMovie')->get($id);

        if ($category && $category->alias == $alias) {
            $vars['view'] = 'category';
            $vars['id'] = $id;
            
            return $vars;
        } else {
            $query = $db->getQuery(true)
            ->select($db->quoteName(array('alias', 'catid')))
            ->from($db->quoteName('#__xmovie_movies'))
            ->where($db->quoteName('id') . ' = ' . (int) $id);
            $db->setQuery($query);
            $collection = $db->loadObject();

            if ($collection) {
                if ($collection->alias == $alias) {
                    $vars['view'] = 'single';
                    $vars['catid'] = (int) $collection->catid;
                    $vars['id'] = (int) $id;
                    
                    return $vars;
                }
            }
        }
    }

    /*
	* If there was more than one segment, then we can determine where the URL points to
	* because the first segment will have the target category id prepended to it.  If the
	* last segment has a number prepended, it is an article, otherwise, it is a category.
	*/
    if (!$advanced) {
        $cat_id = (int) $segments[0];
    
        $movie_id = (int) $segments[$count - 1];
    
        if ($movie_id > 0) {
            $vars['view'] = 'single';
            $vars['catid'] = $cat_id;
            $vars['id'] = $movie_id;
        } else {
            $vars['view'] = 'category';
            $vars['id'] = $cat_id;
        }
    
        return $vars;
    }

    // We get the category id from the menu item and search from there
    $id = $item->query['id'];
    $category = JCategories::getInstance('XMovie')->get($id);

    if (!$category) {
        //JError::raiseError(404, JText::_('COM_CONTENT_ERROR_PARENT_CATEGORY_NOT_FOUND'));
        return $vars;
    }

    $categories = $category->getChildren();
    $vars['catid'] = $id;
    $vars['id'] = $id;
    $found = 0;

    foreach ($segments as $segment) {
        $segment = str_replace(':', '-', $segment);

        foreach ($categories as $category) {
            if ($category->alias == $segment)    {
                $vars['id'] = $category->id;
                $vars['catid'] = $category->id;
                $vars['view'] = 'category';
                $categories = $category->getChildren();
                $found = 1;
                break;
            }
        }

        if ($found == 0) {
            if ($advanced) {
                $db = JFactory::getDbo();
                $query = $db->getQuery(true)
                ->select($db->quoteName('id'))
                ->from('#__xmovie_movies')
                ->where($db->quoteName('catid') . ' = ' . (int) $vars['catid'])
                ->where($db->quoteName('alias') . ' = ' . $db->quote($segment));
                $db->setQuery($query);
                $cid = $db->loadResult();
            } else {
                $cid = $segment;
            }

            $vars['id'] = $cid;
            $vars['view'] = 'single';
        }

        $found = 0;
    }

    return $vars;
}

function XMovieGetAlias($id, $view) 
{
    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    
    if ($view == 'category') {
        $query->select('alias');
        $query->from('#__categories');
        $query->where('id = ' . $id);
    } elseif ($view == 'single') {
        $query->select('alias');
        $query->from('#__xmovie_movies');
        $query->where('id = ' . $id);
    } else {
        return '';
    }
    
    return $db->setQuery($query)->loadResult();
}

function XMovieGetItemid($view) 
{
    $db = JFactory::getDbo();
    $db_query = $db->getQuery(true);
    $db_query->select('id')
        ->from('#__menu')
        ->where("link = 'index.php?option=com_xmovie&view={$view}' AND client_id = 0");
        
    $db->setQuery($db_query);
    
    return $db->loadResult();
}

function XMovieGetIDFromAlias($alias, $view) 
{
    $db = JFacgtory::getDbo();
    $query = $db->getQuery(true);
    $alias = str_replace(':', '-', $alias);
    $alias = $db->getEscaped($alias);
    
    if ($view == 'category' || $view == 'main') {
        $query->select('id');
        $query->from('#__categories');
        $query->where('alias = ' . $alias);
    } elseif ($view == 'single') {
        $query->select('id');
        $query->from('#__xmovie_movies');
        $query->where('alias = ' . $alias);
    } else {
        return 0;
    }
    
    $db->setQuery($query);
    $rows = $db->loadResult();
    return $rows;
}
