<?php
/**
 * @package DJ-Catalog2
 * @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
 */

// no direct access
defined('_JEXEC') or die;

jimport('joomla.application.component.modellist');

class Djcatalog2ModelCustomers extends JModelList
{
    public function __construct($config = array())
    {
        if (empty($config['filter_fields'])) {
            $config['filter_fields'] = array(
                'a.id', 'u.id', 'customer_type', 'u.email', 'u.username'
            );
        }

        parent::__construct($config);
    }
    protected function populateState($ordering = null, $direction = null)
    {
        // List state information.
        parent::populateState('u.username', 'asc');

        // Initialise variables.
        $app = JFactory::getApplication();
        $session = JFactory::getSession();

        $search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
        $this->setState('filter.search', $search);

        // Get customer type filter value
        $customer_type = $this->getUserStateFromRequest($this->context.'.filter.customer_type', 'filter_customer_type', 'registered');
        $this->setState('filter.customer_type', $customer_type);


        // Load the parameters.
        $params = JComponentHelper::getParams('com_djcatalog2');
        $this->setState('params', $params);
    }

    protected function getStoreId($id = '')
    {
        // Compile the store id.
        $id	.= ':'.$this->getState('filter.search');
        $id	.= ':'.$this->getState('filter.customer_type');

        return parent::getStoreId($id);
    }

    protected function getListQuery()
    {
        // Create a new query object.
        $db = $this->getDbo();
        $query = $db->getQuery(true);

        // Customer type filter
        $customer_type = $this->getState('filter.customer_type', 'registered');
        // If customer type filter is set to guest
        if($customer_type == 'guest') {
            $query->select(
                array('CONCAT_WS(" ",u.firstname , u.lastname) as guestname, u.firstname , u.lastname, u.city', 'u.email', 'u.company', 'u.postcode', 'u.address', 'u.country as country_name ')
            );

            $query->from('#__djc2_orders AS u');
            $query->where('u.user_id = 0');

            $search = $this->getState('filter.search');
            if (!empty($search)) {
                $search = $db->quote('%'.$db->escape($search, true).'%');
                $query->where('
                    CONCAT_WS(" ",u.firstname , u.lastname) LIKE ' . $search . ' OR
                    u.city LIKE ' . $search . ' OR
                    u.email LIKE ' . $search . ' OR
                    u.company LIKE ' . $search
                );
            }

            // Add the list ordering clause.
            $orderCol	= $this->state->get('list.ordering');
            $orderDirn	= $this->state->get('list.direction');

            if ($orderCol == 'u.username') {
            	$orderCol = 'u.lastname';
            }
            $query->order($db->escape($orderCol.' '.$orderDirn));

        } else {
            // Select the required fields from the table.
            $query->select(
                $this->getState(
                    'list.select',
                    'a.*, u.email, u.name, u.username, u.id as _user_id, c.country_name'
                )
            );
            $query->from('#__users AS u');
            $query->join('left', '#__djc2_users as a on u.id=a.user_id');
            $query->join('left', '#__djc2_countries as c on c.id=a.country_id');

            $search = $this->getState('filter.search');
            if (!empty($search)) {
                if (stripos($search, 'id:') === 0) {
                    $query->where('a.id = '.(int) substr($search, 3));
                }
                else if (stripos($search, 'cid:') === 0) {
                    $query->where('u.id = '.(int) substr($search, 4));
                }
                else {
                    $search = $db->quote('%'.$db->escape($search, true).'%');
                    $query->where('(a.firstname LIKE '.$search.' OR a.lastname LIKE '.$search.' OR a.company LIKE '.$search.' OR u.name LIKE '.$search.' OR u.username LIKE '.$search.' OR u.email LIKE '.$search.')');
                }
            }
            // Add the list ordering clause.
            $orderCol	= $this->state->get('list.ordering');
            $orderDirn	= $this->state->get('list.direction');

            $query->order($db->escape($orderCol.' '.$orderDirn));
        }


        return $query;
    }
    
    /**
     * Method to get an array of data items.
     *
     * @return  mixed  An array of data items on success, false on failure.
     *
     * @since   1.6
     */
    public function getItems()
    {
    	// Get a storage key.
    	$store = $this->getStoreId();
    	
    	// Try to load the data from internal storage.
    	if (isset($this->cache[$store]))
    	{
    		return $this->cache[$store];
    	}
    	
    	try
    	{
    		// Load the list items and add the items to the internal cache.
    		$this->cache[$store] = $this->_getList($this->_getListQuery(), $this->getStart(), $this->getState('list.limit'));
    	}
    	catch (\RuntimeException $e)
    	{
    		$this->setError($e->getMessage());
    		
    		return false;
    	}
    	
    	$customer_type = $this->getState('filter.customer_type', 'registered');
    	
    	if($customer_type == 'registered') {
    		foreach ($this->cache[$store] as $key => $item) {
    			$this->cache[$store][$key]->_vendors = $this->getVendors($item->user_id);
    		}
    	}
    	
    	return $this->cache[$store];
    }
    
    protected function getVendors($user_id) {
    	$db = JFactory::getDbo();
    	$query = $db->getQuery(true);
    	$query->select('DISTINCT u.*, c.customer_id');
    	$query->from('#__users AS u');
    	$query->join('inner', '#__djc2_vendors AS v ON v.user_id=u.id');
    	$query->join('left', '#__djc2_vendors_customers AS c ON c.vendor_id = v.id');
    	$query->where('(c.customer_id = '.(int)$user_id.')');
    	
    	$db->setQuery($query);
    	$vendors = $db->loadObjectList();
    	
    	return $vendors;
    }

}