<?php
/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) 2012 DJ-Extensions.com LTD, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

defined('_JEXEC') or die;

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

class Djcatalog2ControllerCoupon extends JControllerForm {
	
	protected function allowAdd($data = array())
	{
		$user = JFactory::getUser();
		return $user->authorise('djcatalog2.admin.misc_settings', $this->option);
	}
	
	protected function allowEdit($data = array(), $key = 'id')
	{
		$canDo = JFactory::getUser()->authorise('djcatalog2.admin.misc_settings', $this->option);
		
		return $canDo;
	}
	
	public function save($key = null, $urlVar = null) {
		return parent::save($key, $urlVar);
	}

	public function generate() {

		// Check for request forgeries.
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		$app   = JFactory::getApplication();
		$model = $this->getModel();
		$table = $model->getTable();
		$data  = $this->input->post->get('jform', array(), 'array');
		$checkin = property_exists($table, $table->getColumnAlias('checked_out'));
		$context = "$this->option.edit.$this->context";
		$task = $this->getTask();

		$key = $table->getKeyName();

		// Populate the row id from the session.
		$data[$key] = 0;

		// Access check.
		if (!$this->allowSave($data, $key))
		{
			$this->setError(JText::_('JLIB_APPLICATION_ERROR_SAVE_NOT_PERMITTED'));
			$this->setMessage($this->getError(), 'error');

			$this->setRedirect(
					JRoute::_(
							'index.php?option=' . $this->option . '&view=' . $this->view_list
							. $this->getRedirectToListAppend(), false
					)
			);

			return false;
		}

		// generate the coupons' codes
		$generator  = $this->input->post->get('generator', array(), 'array');
		$number = (int)$generator['number'];
		$codes = array();
		
		if($number <= 0) {
			$this->setMessage(JText::_('COM_DJCATALOG2_COUPONS_GENERATOR_NUMBER_INVALID'), 'warning');
			$this->setRedirect(
					JRoute::_(
							'index.php?option=' . $this->option . '&view=' . $this->view_list
							. $this->getRedirectToListAppend(), false
					)
			);
			
			return false;
		}
		
		for($i = 0; $i < $number; $i++) {
			$model->setState($model->getName() . '.id', null);
			
			$data[$key] = 0;
			$data['code'] = strtoupper(JUserHelper::genRandomPassword(10));
			$codes[] = $data['code'];

			// Validate the posted data.
			// Sometimes the form needs some posted data, such as for plugins and modules.
			$form = $model->getForm($data, false);

			if (!$form)
			{
				$app->enqueueMessage($model->getError(), 'error');

				return false;
			}

			// Test whether the data is valid.
			$validData = $model->validate($form, $data);

			// Check for validation errors.
			if ($validData === false)
			{
				// Get the validation messages.
				$errors = $model->getErrors();

				// Push up to three validation messages out to the user.
				for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++)
				{
					if ($errors[$i] instanceof Exception)
					{
						$app->enqueueMessage($errors[$i]->getMessage(), 'warning');
					}
					else
					{
						$app->enqueueMessage($errors[$i], 'warning');
					}
				}

				// Save the data in the session.
				//$app->setUserState($context . '.data', $data);

				// Redirect back to the edit screen.
				$this->setRedirect(
						JRoute::_(
								'index.php?option=' . $this->option . '&view=' . $this->view_list
								. $this->getRedirectToListAppend(), false
						)
				);

				return false;
			}

			if (!isset($validData['tags']))
			{
				$validData['tags'] = null;
			}

			// Attempt to save the data.
			if (!$model->save($validData))
			{
				// Save the data in the session.
				$app->setUserState($context . '.data', $validData);

				// Redirect back to the edit screen.
				$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError()));
				$this->setMessage($this->getError(), 'error');

				$this->setRedirect(
						JRoute::_(
								'index.php?option=' . $this->option . '&view=' . $this->view_list
								. $this->getRedirectToListAppend(), false
						)
				);

				return false;
			}

			// Invoke the postSave method to allow for the child class to access the model.
			$this->postSaveHook($model, $validData);
		}
		
		$this->setMessage(JText::sprintf('COM_DJCATALOG2_COUPONS_GENERATOR_SUCCESS_MSG', count($codes), implode(', ', $codes)));
		
		// Redirect the user
		$url = 'index.php?option=' . $this->option . '&view=' . $this->view_list
		. $this->getRedirectToListAppend();
		
		// Check if there is a return value
		$return = $this->input->get('return', null, 'base64');
		
		if (!is_null($return) && JUri::isInternal(base64_decode($return)))
		{
			$url = base64_decode($return);
		}
		
		// Redirect to the list screen.
		$this->setRedirect(JRoute::_($url, false));

		return true;

	}
}
?>
