<?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;

class Djcatalog2ModelCustomer extends JModelAdmin
{
	protected $text_prefix = 'COM_DJCATALOG2';

	public function __construct($config = array()) {
		parent::__construct($config);
	}

	public function getTable($type = 'Customers', $prefix = 'Djcatalog2Table', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm('com_djcatalog2.customer', 'customer', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}
		return $form;
	}

	protected function loadFormData()
	{
		$data = JFactory::getApplication()->getUserState('com_djcatalog2.edit.customer.data', array());

		if (empty($data)) {
			$data = $this->getItem();
		}
		
		$app = JFactory::getApplication();
		$user_id = $app->input->getInt('user_id');
		if ($user_id && empty($data->user_id) && is_object($data)) {
			$data->user_id = $user_id;
		}
		
		return $data;
	}
	
	public function getItem($pk = null) {
		if ($item = parent::getItem($pk)) {
			$db = JFactory::getDbo();
			$app	= JFactory::getApplication();
			
			$user_id = (isset($item->user_id)) ? $item->user_id :  $app->input->getInt('user_id');
			
			if ((!isset($item->vendors) || !is_array($item->vendors)) && $user_id){
				$db->setQuery('SELECT vendor_id FROM #__djc2_vendors_customers WHERE customer_id=\''.$user_id.'\'');
				$item->vendors = $db->loadColumn();
			}
			
			return $item;
		}
		
		return false;
	}
	
	protected function getReorderConditions($table = null)
	{
		$condition = array();
		return $condition;
	}

	public function delete(&$cid) {
		return parent::delete($cid);
	}
	
	public function save($data) {
		return parent::save($data);
	}
	
	
	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission for the component.
	 *
	 * @since   1.6
	 */
	protected function canDelete($record)
	{
		return JFactory::getUser()->authorise('core.delete', $this->option) || JFactory::getUser()->authorise('djcatalog2.admin.customers', $this->option);
	}
	
	/**
	 * Method to test whether a record can have its state changed.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to change the state of the record. Defaults to the permission for the component.
	 *
	 * @since   1.6
	 */
	protected function canEditState($record)
	{
		return JFactory::getUser()->authorise('core.edit.state', $this->option)  || JFactory::getUser()->authorise('djcatalog2.admin.customers', $this->option);
	}
}