<?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 Djcatalog2ModelCartField extends DJCJModelAdmin
{
	protected $text_prefix = 'COM_DJCATALOG2';

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

	public function getTable($type = 'CartFields', $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.cartfield', 'cartfield', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}

		return $form;
	}

	protected function loadFormData()
	{
		$data = JFactory::getApplication()->getUserState('com_djcatalog2.edit.cartfield.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);
		
		if (empty($table->alias)) {
			$table->alias = JFilterOutput::stringURLSafe($table->name);
			$table->alias = trim(str_replace('-','_',$table->alias));
			if(trim(str_replace('_','',$table->alias)) == '') {
				$table->alias = JFactory::getDate()->format('Y_m_d_H_i_s');
			}
		}

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

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

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

	public function delete(&$cid) {
		if (count( $cid ))
		{
			$cids = implode(',', $cid);
			try {
				$db = JFactory::getDbo();
				$db->setQuery('DELETE FROM #__djc2_cart_extra_fields_options WHERE field_id IN ('.$cids.') ');
				$db->execute();
			} 
			catch (Exception $e) {
				$this->setError($e->getMessage());
				return false;
			}
		}
		return parent::delete($cid);
	}
	
	public function saveOptions($values, &$table, $newField) {
		$db = JFactory::getDbo();
		if (!empty($values) && array_key_exists('id', $values) && array_key_exists('option', $values) && array_key_exists('position', $values)) {
			if ($table->type == 'select' || $table->type == 'checkbox' || $table->type == 'radio') {
				
				//$db->setQuery('SELECT MAX(ordering) FROM #__djc2_cart_extra_fields_options WHERE field_id='.(int)$table->id);
				//$max = $db->loadResult();
				
				$pks = array();
                
                $max = 1;
				
				foreach ($values['id'] as $key=>$id) {
					if ($values['option'][$key] != '') {
						$fo_table = JTable::getInstance('CartFieldOptions', 'Djcatalog2Table', array());
						$isNew = true;
						// Load the row if saving an existing record.
						if ($id > 0 && $newField === false) {
							$fo_table->load($id);
							$isNew = false;
						}
						
						$data = array();
						$data['id'] = $isNew ? null:$id;
						//$data['value'] = htmlspecialchars($values['option'][$key]);
						$data['value'] = ($values['option'][$key]);
						$data['ordering'] = ($values['position'][$key] > 0) ? $values['position'][$key] : 0;
						$data['field_id'] = $table->id;
						// Bind the data.
						if (!$fo_table->bind($data)) {
							$this->setError($fo_table->getError());
							return false;
						}
						if (empty($fo_table->ordering) || !$fo_table->ordering) {
							$fo_table->ordering = $max;
						}
                        $max = $fo_table->ordering + 1;
						// Check the data.
						if (!$fo_table->check()) {
							$this->setError($fo_table->getError());
							return false;
						}
			
						// Store the data.
						if (!$fo_table->store()) {
							$this->setError($fo_table->getError());
							return false;
						}
						
						$pks[] = $fo_table->id;
					}
				}
				if (!empty($pks)) {
					$db->setQuery('DELETE FROM #__djc2_cart_extra_fields_options WHERE field_id='.(int)$table->id.' AND id NOT IN ('.implode(',',$pks).')');
					$db->execute();
				}
			}
		}
		return true;
	}
	public function deleteOptions(&$table) {
		$db = JFactory::getDbo();
		$db->setQuery('DELETE FROM #__djc2_cart_extra_fields_options WHERE field_id='.(int)$table->id);
		if (!$db->execute()){
			$this->setError($db->getError());
		}
		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.misc_settings', $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.misc_settings', $this->option);
	}
}