<?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');
}

/**
 *
 * @author dharris
 * Model for the main view
 *
 */
class XMovieModelMain extends JModelListLegacy
{
    protected $_items = null;
    protected $_item = null;
    protected $_articles = null;
    protected $_siblings = null;
    protected $_children = null;
    protected $_parent = null;
    protected $_active = null;
    protected $_mainItemId = null;
    protected $_total = null;
    protected $_pagination = null;
    protected $_category = null;
    protected $_categoryids = null;
    protected $_categories = null;

    /**
     * Constructor
     *
     * @since 1.5
     */
    function __construct() 
    {
        parent::__construct();
    }

    /**
     * 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($ordering = 'ordering', $direction = 'ASC') 
    {
        $app = JFactory::getApplication();
        $cfgParams = $this -> getConfigParams();
        $input = JFactory::getApplication() -> input;
        $menuitemid = $input -> getInt('Itemid');
        $menu = JFactory::getApplication() -> getMenu();
        $params = $menu -> getParams($menuitemid);

        // List state information
        $value = JRequest::getUInt('limit', $params -> get('mov_per_page', $cfgParams -> get('cview_movs_per_page')));
        $this -> setState('list.limit', $value);
        $value = JRequest::getUInt('limitstart', 0);
        $this -> setState('list.start', $value);

        switch (JRequest::getString('sort', $params->get('sort_order'))) {
            case 'popular' :
                $sort_method = "a.hits";
                $listOrder = "DESC";
                break;
            case 'oldest' :
                $sort_method = "a.creation_date";
                $listOrder = "ASC";
                break;
            case 'id' :
                $sort_method = "a.id";
                $listOrder = "DESC";
                break;
            case 'latest' :
                $sort_method = "a.creation_date";
                $listOrder = "DESC";
                break;
            default :
                $sort_method = "a.ordering";
                $listOrder = "ASC";
        }

        $orderCol = JRequest::getCmd('filter_order', $sort_method);
        $this -> setState('list.ordering', $orderCol);

        $listOrder = JRequest::getCmd('filter_order_Dir', $listOrder);
        $this -> setState('list.direction', $listOrder);

        $params = $app -> getParams();
        $this -> setState('params', $params);
        $user = JFactory::getUser();

        if ((!$user -> authorise('core.edit.state', 'com_xmovie')) && (!$user -> authorise('core.edit', 'com_xmovie'))) {
            // filter on published for those who do not have edit or edit.state rights.
            $this -> setState('filter.published', 1);
        }

        $this -> setState('filter.language', $app -> getLanguageFilter());

        // process show_noauth parameter
        if (!$params -> get('show_noauth')) {
            $this -> setState('filter.access', true);
        } else {
            $this -> setState('filter.access', false);
        }

        $this -> setState('layout', JRequest::getCmd('layout'));
    }

    public function getItems() 
    {
        $app = JFactory::getApplication();
        // Invoke the parent getItems method to get the main list
        $items = parent::getItems();
        $this -> _total = $this -> getTotal();
        $categories = MovieHelper::getItemIds();
        $mainid = JRequest::getVar('Itemid', '');
        $mainalias = $this -> getMainAlias();
        $cat = MovieHelper::getTopLevel('main');

        // Convert the params field into an object, saving original in _params
        for ($i = 0, $n = count($items); $i < $n; $i++) {
            $item = &$items[$i];
            $cid = $item -> catid;
            $user = JFactory::getUser($item -> user_id);
            $item -> submitter = $user -> username;

            if (isset($categories[$cid]['itemId']) && $categories[$cid]['itemId'] != '') {
                $item -> itemId = $categories[$cid]['itemId'];
            }

            if (isset($cat[$item -> catid])) {
                $item -> catido = $cat[$item -> catid] -> menuid;
                $item -> catidoa = $cat[$item -> catid] -> alias;
            }

            if ($item -> catid == 0) {
                $item -> catid = 0;
                //$mainid;
                $item -> catalias = $mainalias;
            }

            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);
        $query -> select('MIN(lft) AS lft');
        $query -> from('#__categories');
        $query -> where("`extension` = 'com_xmovie'");
        $db -> setQuery($query);
        $lft = $db -> loadResult();

        $query = $db -> getQuery(true);
        $query -> select('MAX(rgt) AS rgt');
        $query -> from('#__categories');
        $query -> where("`extension` = 'com_xmovie'");
        $db -> setQuery($query);
        $rgt = $db -> loadResult();

        $query = $db -> getQuery(true);
        // Select required fields from the categories.
        $query -> select('a.*');
        $query -> from($db -> quoteName('#__xmovie_movies') . ' AS a');

        // Join over the categories.
        $query -> select('c.alias AS catalias, c.title AS cattitle');
        $query -> join('LEFT', $db -> quoteName('#__categories') . ' AS c ON c.id = a.catid');

        $query -> where('a.access IN (' . $groups . ')');
        $query -> where('a.published = 1');

        $catQuery = 'a.catid = ANY (SELECT `id` FROM ' . $db -> quoteName('#__categories') . " WHERE extension = 'com_xmovie' AND published = '1' AND lft >= '{$lft}' AND rgt <= '{$rgt}' AND access IN ({$groups})) OR (a.catid = 0 and a.published = 1)";
        $query -> where($catQuery);

        // 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')));

        return $query;
    }

    public function getMainInfo() 
    {
        if (!$this -> _active) {
            $this -> getCategory();
        }

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

        $query -> select('lft, rgt');
        $query -> from('#__menu');
        $query -> query('id = ' . $this -> _active -> id);
    }

    public function getConfigParams() 
    {
        $cfgParams = JComponentHelper::getParams('com_xmovie');

        return $cfgParams;
    }

    public function getSubCategories($all = false) 
    {

        $tmpId = 0;
        $itemid = '';
        $alias = '';
        $c_id = '';
        $tmpRows = array();
        $this -> _categoryids = array();
        $db = $this -> getDbo();
        $query = $db -> getQuery(true);

        $app = JFactory::getApplication();
        $params = $app -> getParams();

        $user = JFactory::getUser();
        $groups = implode(',', $user -> getAuthorisedViewLevels());

        $query -> select('*');
        $query -> from('#__categories');
        $query -> where("(parent_id = '1' AND extension = 'com_xmovie' AND published = '1')");

        switch ($params->get('main_cat_sort_order')) {
            case 'title' :
                $sort_method = "title";
                break;
            case 'date' :
                $sort_method = "created_time";
                break;
            case 'random' :
                $sort_method = "RAND()";
                break;
            case 'popular' :
            default :
                $sort_method = "hits";
        }

        if ($params -> get('main_cat_sort_order_dir') == 'desc') {
            $listOrder = "DESC";
        } else {
            $listOrder = "ASC";
        }

        $query -> where('access IN (' . $groups . ') ORDER BY ' . $sort_method . ' ' . $listOrder);
        $db -> setQuery($query, 0, $params -> get('cat_limit'));
        $rows = $db -> loadAssocList('id');

        $itemids = MovieHelper::getItemIds($all);

        foreach ($rows as $key => $value) {
            $p_id = $rows[$key]['parent_id'];

            if (isset($itemids[$key])) {
                $itemid = $itemids[$key]['itemId'];
                $alias = $rows[$key]['alias'];

                $this -> _categoryids[$key] = MovieHelper::getTopId($key);
                $tmpRows[$key] = $rows[$key];
                $tmpRows[$key]['itemId'] = $itemids[$key]['itemId'];
                $tmpRows[$key]['link'] = "index.php?view=category&id={$key}:{$alias}&Itemid={$itemid}";
            }
        }

        unset($rows);
        $this -> _categories = $tmpRows;

        return $this -> _categories;
    }

    /**
     * Method to get category data for the current category
     *
     * @param    int        An optional ID
     *
     * @return    object
     * @since    1.5
     */
    public function getCategory() 
    {
        if (!is_object($this -> _item)) {
            $app = JFactory::getApplication();
            $menu = $app -> getMenu();
            $active = $menu -> getActive();
            $params = new JRegistry();

            if ($active) {
                $this -> _active = $active;
                $params -> loadString($active -> params);
            }

            $options = array();
            $options['countItems'] = $params -> get('show_cat_items', 1) || $params -> get('show_empty_categories', 0);
            $categories = JCategories::getInstance('XMovie', $options);

            $this -> _item = $categories -> get($this -> getState('category.id', 'root'));
            if (is_object($this -> _item)) {
                $this -> _children = $this -> _item -> getChildren();
                $this -> _parent = false;
                if ($this -> _item -> getParent()) {
                    $this -> _parent = $this -> _item -> getParent();
                }
                $this -> _rightsibling = $this -> _item -> getSibling();
                $this -> _leftsibling = $this -> _item -> getSibling(false);
            } else {
                $this -> _children = false;
                $this -> _parent = false;
            }
        }

        return $this -> _item;
    }

    public function getMainItemId() 
    {
        return $this -> _mainItemId;
    }

    private function getMainAlias() 
    {
        $id = JRequest::getInt('Itemid');
        $db = $this -> getDbo();
        $query = $db -> getQuery(true);

        $query -> select('alias');
        $query -> from('#__menu');
        $query -> where('id = ' . $id);

        $db -> setQuery($query, 0, 1);
        return $db -> loadResult();
    }

    public function getActive() 
    {
        if ($this -> _active) {
            return $this -> _active;
        } else {
            return null;
        }
    }

    /**
     * Get the parent category.
     *
     * @param    int        An optional category id. If not supplied, the model state 'category.id' will be used.
     *
     * @return    mixed    An array of categories or false if an error occurs.
     */
    public function getParent() 
    {
        if (!is_object($this -> _item)) {
            $this -> getCategory();
        }
        return $this -> _parent;
    }

    /**
     * Get the sibling (adjacent) categories.
     *
     * @return    mixed    An array of categories or false if an error occurs.
     */
    function & getLeftSibling() 
    {
        if (!is_object($this -> _item)) {
            $this -> getCategory();
        }
        return $this -> _leftsibling;
    }

    function & getRightSibling() 
    {
        if (!is_object($this -> _item)) {
            $this -> getCategory();
        }
        return $this -> _rightsibling;
    }

    /**
     * Get the child categories.
     *
     * @param    int        An optional category id. If not supplied, the model state 'category.id' will be used.
     *
     * @return    mixed    An array of categories or false if an error occurs.
     */
    function & getChildren() 
    {
        if (!is_object($this -> _item)) {
            $this -> getCategory();
        }
        return $this -> _children;
    }

    public function getStart() 
    {
        return $this -> getState('list.start');
    }

    /**
     * Method to get a pagination object of the collection items for the category
     *
     * @access public
     * @return integer
     */

    function getPagination() 
    {
        // Lets load the content if it doesn't already exist
        if (empty($this -> _pagination)) {
            jimport('joomla.html.pagination');
            $this -> _pagination = new JPagination($this -> _total, $this -> getState('list.start'), $this -> getState('list.limit'));
        }

        return $this -> _pagination;
    }
}
?>

