<?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.application.component.modellist');

if (!class_exists('JModelListLegacy')) {
    class_alias('JModelList', 'JModelListLegacy');
}

class XMovieModelRss extends JModelListLegacy
{
    protected $_id = null;
    protected $_cat_ids = null;
    protected $_max_items = null;
    protected $_show_protected = null;
    protected $_total = null;
    protected $_items = null;
    protected $_cfgParams = null;
    protected $_category = null;
    
    function __construct() 
    {
        parent::__construct();
        
        $this->_cfgParams = $this->getConfigParams();                
        $this->_max_items = $this->_cfgParams->rss_max_items;
        $this->_show_protected = $this->_cfgParams->rss_show_protected;
        $this->_id = JRequest::getInt('id', '');                
    }
    
    public function getConfigParams() 
    {
        $app = JComponentHelper::getParams('com_xmovie');
        $cfgParams =  $app->get('params');
        
        return $cfgParams;
    }
    
    public function getItems() 
    {
        // Invoke the parent getItems method to get the main list
        $items = parent::getItems();
        $this->_total    = $this->getTotal();

        // Convert the params field into an object, saving original in _params
        for ($i = 0, $n = count($items); $i < $n; $i++) {
            $item = &$items[$i];
            if (!isset($this->_params)) {
                $params = new JRegistry();
                $item->params = $params;
                $params->loadString($item->params);
            }
        }
        
        $this->_items = $items;
        
        return $this->_items;        
    }
    
    /**
     * Method to build an SQL query to load the list data.
     *
     * @return    string    An SQL query
     * @since    1.6
     */
    protected function getListQuery() 
    {
        $user    = JFactory::getUser();
        $groups    = implode(',', $user->getAuthorisedViewLevels());

        // Create a new query object.
        $db        = $this->getDbo();
        $query    = $db->getQuery(true);
        
        // Select required fields from the categories.
        $query->select($this->getState('list.select', 'a.*'));
        $query->from($db->quoteName('#__xmovie_movies').' AS a');
        $query->where('a.access IN ('.$groups.')');
        
        if (!empty($this->_id)) {
            $category = $this->getCategoryInfo();
            $catQuery = 'a.catid = ANY (SELECT `id` FROM '.$db->quoteName('#__categories'). ' WHERE lft >= ' .$category->lft. ' AND rgt <= ' .$category->rgt. " AND extension = 'com_xmovie') ";
            
            $query->where($catQuery);
        }
        
        $query->where('a.published = 1');
        
        // Filter by start and end dates.
        $nullDate = $db->Quote($db->getNullDate());
        $date = JFactory::getDate();
        $nowDate = $db->Quote($date->format($db->getDateFormat()));

        if ($this->getState('filter.publish_date')){
            $query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')');
            $query->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
        }

        // Filter by language
        if ($this->getState('filter.language')) {
            $query->where('a.language in ('.$db->Quote(JFactory::getLanguage()->getTag()).','.$db->Quote('*').')');
        }

        // Add the list ordering clause.
        $query->order($db->escape($this->getState('list.ordering', 'a.ordering')).' '.$db->escape($this->getState('list.direction', 'ASC')));
        $query->limit($this->_max_items);
        
        return $query;
    }
    
    public function getCategoryInfo() 
    {
        if (!$this->_category) {
            $cat_id = $this->_id;
            
            $db = $this->getDbo();
            $query = $db->getQuery(true);
            
            $query->select('*');
            $query->from('#__categories');
            $query->where("id = '{$cat_id}' AND extension = 'com_xmovie' AND published = '1'");
            
            $db->setQuery($query);
            $this->_category = $db->loadObject();
        }
        return $this->_category;
    }

    /**
     * Method to auto-populate the model state.
     *
     * Note. Calling getState in this method will result in recursion.
     *
     * @since    1.6
     */
    protected function populateState($ordering = null, $direction = null) 
    {
        // Initialise variables.
        $app    = JFactory::getApplication();
        $params    = &$app->getParams();
        $cfgParams = $this->getConfigParams();
        $db        = $this->getDbo();
        
        // List state information
        $value = JRequest::getUInt('limit', $this->_max_items);
        $this->setState('list.limit', $value);        

        // Get list ordering default from the parameters
        $menuParams = new JRegistry();
        if ($menu = $app->getMenu()->getActive()) {
            $menuParams->loadString($menu->params);
        }
        $mergedParams = clone $params;
        $mergedParams->merge($menuParams);

        $orderCol    = JRequest::getCmd('filter_order', $mergedParams->get('initial_sort', 'ordering'));
        if (!in_array($orderCol, $this->filter_fields)) {
            $orderCol = 'ordering';
        }
        $this->setState('list.ordering', $orderCol);

        $listOrder    =  JRequest::getCmd('filter_order_Dir', 'ASC');
        if (!in_array(strtoupper($listOrder), array('ASC', 'DESC', ''))) {
            $listOrder = 'ASC';
        }
        $this->setState('list.direction', $listOrder);

        $id = JRequest::getVar('id', 0, '', 'int');
        $this->setState('category.id', $id);

        $user = JFactory::getUser();
        if ((!$user->authorise('core.edit.state', 'com_xmovie')) &&  (!$user->authorise('core.edit', 'com_xmovie'))){
            // limit to published for people who can't edit or edit.state.
            $this->setState('filter.published', 1);

            // Filter by start and end dates.
            $this->setState('filter.publish_date', true);
        }
        $this->setState('filter.language', $app->getLanguageFilter());

        // Load the parameters.
        $this->setState('params', $params);
    }
}
