<?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.modeladmin');
require_once(JPATH_ROOT.'/administrator/components/com_djcatalog2/lib/modeladmin.php');

class Djcatalog2ModelProducer extends DJCJModelAdmin
{
	protected $text_prefix = 'COM_DJCATALOG2';
	
	protected $associationsContext = 'com_djcatalog2.producer';

	public function __construct($config = array()) {
		//$config['event_after_save'] = 'onProducerAfterSave';
		//$config['event_after_delete'] = 'onProducerAfterDelete';
		parent::__construct($config);
	}

	public function getTable($type = 'Producers', $prefix = 'Djcatalog2Table', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	public function getForm($data = array(), $loadData = true)
	{
		// Initialise variables.
		$app	= JFactory::getApplication();

		// Get the form.
		$form = $this->loadForm('com_djcatalog2.producer', 'producer', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}

		return $form;
	}
	
	public function getItem($pk = null)
	{
		if ($item = parent::getItem($pk)) {
			/*
			 * Multilang
			 */
			if (JLanguageAssociations::isEnabled())
			{
				$item->associations = array();
				
				if ($item->id != null)
				{
					$associations = JLanguageAssociations::getAssociations('com_djcatalog2', '#__djc2_producers', 'com_djcatalog2.producer', (int) $item->id, 'id', 'alias', '');
					
					foreach ($associations as $tag => $association)
					{
						$item->associations[$tag] = $association->id;
					}
				}
			}
			return $item;
		} else {
			return false;
		}
	}
	
	/**
	 * Method to preprocess the form to add the association fields dynamically
	 *
	 * @return     none
	 */
	protected function preprocessForm(Joomla\CMS\Form\Form $form, $data, $group = 'content')
	{
		// Association content items
		if (JLanguageAssociations::isEnabled())
		{
			$languages = JLanguageHelper::getContentLanguages(false, true, null, 'ordering', 'asc');
			
			if (count($languages) > 1)
			{
				$addform = new SimpleXMLElement('<form />');
				$fields = $addform->addChild('fields');
				$fields->addAttribute('name', 'associations');
				$fieldset = $fields->addChild('fieldset');
				$fieldset->addAttribute('name', 'item_associations');
				
				foreach ($languages as $language)
				{
					$field = $fieldset->addChild('field');
					$field->addAttribute('name', $language->lang_code);
					$field->addAttribute('type', 'djproducermodal');
					$field->addAttribute('language', $language->lang_code);
					$field->addAttribute('label', $language->title);
					$field->addAttribute('translate_label', 'false');
				}
				
				$form->load($addform, false);
			}
		}
		parent::preprocessForm($form, $data, $group);
	}

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

		if (empty($data)) {
			$data = $this->getItem();
		}

		return $data;
	}

	protected function _prepareTable(&$table)
	{
		jimport('joomla.filter.output');
		$date = JFactory::getDate();
		$user = JFactory::getUser();

		$table->name		= htmlspecialchars_decode($table->name, ENT_QUOTES);
		$table->alias		= JApplicationHelper::stringURLSafe($table->alias);

		if (empty($table->alias)) {
			$table->alias = JApplicationHelper::stringURLSafe($table->name);
		}

		if (empty($table->id)) {
			if (empty($table->ordering)) {
				$db = JFactory::getDbo();
				$db->setQuery('SELECT MAX(ordering) FROM #__djc2_producers');
				$max = $db->loadResult();

				$table->ordering = $max+1;
			}
		}
	}

	protected function getReorderConditions($table = null)
	{
		$condition = array();
		return $condition;
	}

	public function delete(&$cid) {
		if (count( $cid ))
		{
			$cids = implode(',', $cid);
				
			$this->_db->setQuery("SELECT COUNT(*) FROM #__djc2_items WHERE producer_id IN ( ".$cids." )");
			if ($this->_db->loadResult() > 0) {
				$this->setError(JText::_('COM_DJCATALOG2_DELETE_PRODUCERS_HAVE_ITEMS'));
				return false;
			}
		}
		return parent::delete($cid);
	}
	
	public function saveAttributes($data, &$table) {
		$db = JFactory::getDbo();
		
		//if (!empty($data) ) {
		$non_empty_fields = array(0);
		
		if (!empty($data)) {
			foreach ($data as $k=>$v) {
				if (!empty($v) || trim($v) != '') {
					$non_empty_fields[] = (int)$k;
				}
			}
		}
		$app = JFactory::getApplication();
		$task = $app->input->getCmd('task');
		
		$non_empty_fields = array_unique($non_empty_fields);
		$non_empty_fields_ids = implode(',', $non_empty_fields);
		
		if ($task != 'import') {
			$query = $db->getQuery(true);
			$query->delete();
			$query->from('#__djc2_producers_extra_fields_values_text');
			//$query->where('item_id ='.$table->id.' and field_id not in (select id from #__djc2_producers_extra_fields where group_id = '.$table->group_id.' or group_id = 0)');
			
			$query->where('item_id ='.$table->id.' and field_id not in ('.$non_empty_fields_ids.')');
			
			$db->setQuery($query);
			$db->execute();
			
			$query = $db->getQuery(true);
			$query->delete();
			$query->from('#__djc2_producers_extra_fields_values_int');
			//$query->where('item_id ='.$table->id.' and field_id not in (select id from #__djc2_producers_extra_fields where group_id = '.$table->group_id.' or group_id = 0)');
			
			$query->where('item_id ='.$table->id.' and field_id not in ('.$non_empty_fields_ids.')');
			
			$db->setQuery($query);
			$db->execute();
			
			
			$query = $db->getQuery(true);
			$query->delete();
			$query->from('#__djc2_producers_extra_fields_values_date');
			//$query->where('item_id ='.$table->id.' and field_id not in (select id from #__djc2_producers_extra_fields where group_id = '.$table->group_id.' or group_id = 0)');
			
			$query->where('item_id ='.$table->id.' and field_id not in ('.$non_empty_fields_ids.')');
			
			$db->setQuery($query);
			$db->execute();
		}
		
		if (empty($data)) {
			return true;
		}
		
		$query = $db->getQuery(true);
		$query->select('ef.*');
		$query->from('#__djc2_producers_extra_fields as ef');
		//$query->where('ef.group_id='.$table->group_id.' OR ef.group_id=0');
		$query->where('ef.id in ('.$non_empty_fields_ids.')');
		$db->setQuery($query);
		
		$attribs = $db->loadObjectList();
		$itemId = $table->id;
		$rows = array();
		
		$text_types = array('text','textarea','html');
		$int_types = array('select', 'multiselect', 'checkbox','radio', 'color', 'multicolor', 'bool');
		$date_types = array('calendar');
		/*
		 foreach ($attribs as $k=>$v) {
		 $fieldId = $v->id;
		 $className =  DJCatalog2CustomField.ucfirst($v->type);
		 if (class_exists($className) == false ){
		 continue;
		 }
		 
		 $field = new $className($fieldId, $itemId, $v->name, $v->required);
		 
		 if (array_key_exists($fieldId, $data) && !empty($data[$fieldId])) {
		 $field->setValue($data[$fieldId]);
		 $field->save();
		 } else {
		 $field->delete();
		 }
		 }
		 
		 return true;*/

		foreach ($attribs as $k=>$v) {
			$fv_table = null;
			$type_table_name = null;
			$table_type = null;
			if (in_array($v->type, $text_types)) {
				$fv_table = JTable::getInstance('ProducersFieldValuesText', 'Djcatalog2Table', array());
				$type_table_name = '#__djc2_producers_extra_fields_values_text';
				$table_type = 'text';
			} else if (in_array($v->type, $int_types)) {
				$fv_table = JTable::getInstance('ProducersFieldValuesInt', 'Djcatalog2Table', array());
				$type_table_name = '#__djc2_producers_extra_fields_values_int';
				$table_type = 'int';
			} else if (in_array($v->type, $date_types)) {
				$fv_table = JTable::getInstance('ProducersFieldValuesDate', 'Djcatalog2Table', array());
				$type_table_name = '#__djc2_producers_extra_fields_values_date';
				$table_type = 'date';
			} else {
				continue;
			}
			$fieldId = $v->id;
			if (array_key_exists($fieldId, $data) && isset($data[$fieldId])) {
				// add/alter data
				$value = null;
				$id = null;
				
				if (is_array($data[$fieldId])) {
					$db->setQuery('
									SELECT id
									FROM '.$type_table_name.'
									WHERE
										item_id='.(int)$itemId.'
										AND field_id='.$fieldId. ' order by id '
						);
					$values = $db->loadColumn();
					$count = (count($values) > count($data[$fieldId])) ? count($values) : count($data[$fieldId]);
					for ($i = 0; $i < $count; $i++) {
						if (isset($data[$fieldId][$i])) {
							$id = null;
							if (isset($values[$i])) {
								$id = $values[$i];
							}
							
							$rows[] = array(
								'id'=>$id,
								'item_id'=>$itemId,
								'field_id'=>$fieldId,
								'value' => $data[$fieldId][$i],
								'type' => $table_type
							);
						} else {
							$db->setQuery('
								DELETE
								FROM '.$type_table_name.'
								WHERE id='.(int)$values[$i]
								);
							$db->execute();
						}
					}
					
				} else {
					if ($v->type == 'html') {
						$data[$fieldId] = JComponentHelper::filterText($data[$fieldId]);
						$data[$fieldId] = preg_replace('/&(?![A-Za-z0-9#]{1,7};)/','&amp;',$data[$fieldId]);
					}
					if ($fv_table->load(array('item_id'=>$itemId,'field_id'=>$fieldId))) {
						$id = $fv_table->id;
					}
					$rows[] = array(
						'id'=>$id,
						'item_id'=>$itemId,
						'field_id'=>$fieldId,
						'value' => $data[$fieldId],
						'type' => $table_type
					);
				}
				
			} else {
				// remove data
				$db->setQuery('
								DELETE
								FROM '.$type_table_name.'
								WHERE
									field_id='.(int)$fieldId.'
									AND item_id='.(int)$itemId
					);
				$db->execute();
			}
		}
		
		foreach ($rows as $key=>$row) {
			$fv_table = null;
			if (isset($row['type'])) {
				if ($row['type'] == 'text' || $row['type'] == 'int' || $row['type'] == 'date') {
					$fv_table = JTable::getInstance('ProducersFieldValues'.ucfirst($row['type']), 'Djcatalog2Table', array());
					unset($row['type']);
				} else{
					continue;
				}
			} else {
				continue;
			}
			
			$isNew = true;
			// Load the row if saving an existing record.
			if ($row['id'] > 0) {
				$fv_table->load($row['id'], true);
				$isNew = false;
			}
			
			// Bind the data.
			if (!$fv_table->bind($row)) {
				$this->setError($fv_table->getError());
				return false;
			}
			// Check the data.
			if (!$fv_table->check()) {
				$this->setError($fv_table->getError());
				return false;
			}
			
			// Store the data.
			if (!$fv_table->store()) {
				$this->setError($fv_table->getError());
				return false;
			}
			
		}
		//}
		return true;
	}
	
	/**
	 * 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.catalogue', $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.catalogue', $this->option);
	}
}