<?php
/**
 * @version     1.4.7
 * @package     sellacious
 *
 * @copyright   Copyright (C) 2012-2017 Bhartiy Web Technologies. All rights reserved.
 * @license     SPL Sellacious Private License; see http://www.sellacious.com/spl.html
 * @author      Izhar Aazmi <info@bhartiy.com> - http://www.bhartiy.com
 */
// no direct access.
defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;
use Sellacious\Utilities\Import;

/**
 * Categories list controller class
 *
 * @since   1.0.0
 */
class SellaciousControllerCategories extends SellaciousControllerAdmin
{
	/**
	 * @var    string  The prefix to use with controller messages.
	 *
	 * @since   1.0.0
	 */
	protected $text_prefix = 'COM_SELLACIOUS_CATEGORIES';

	/**
	 * Method to get a model object, loading it if required.
	 *
	 * @param  string  $name    The model name. Optional.
	 * @param  string  $prefix  The class prefix. Optional.
	 * @param  array   $config  Configuration array for model. Optional.
	 *
	 * @return  object  The model.
	 *
	 * @since   1.0.0
	 */
	public function getModel($name = 'Category', $prefix = 'SellaciousModel', $config = null)
	{
		return parent::getModel($name, $prefix, array('ignore_request' => true));
	}

	/**
	 * Rebuild the nested set tree.
	 *
	 * @return  bool  False on failure or error, true on success.
	 *
	 * @since   1.0.0
	 */
	public function rebuild()
	{
		// Check for request forgeries
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		$allowed = $this->helper->access->check('category.rebuild');

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

		if (!$allowed)
		{
			$this->setMessage(JText::_('COM_SELLACIOUS_ACCESS_NOT_ALLOWED'), 'error');

			return false;
		}

		/** @var  SellaciousModelCategory  $model */
		$model = $this->getModel();

		if ($model->rebuild())
		{
			$this->setMessage(JText::_($this->text_prefix . '_REBUILD_SUCCESS'));

			return true;
		}
		else
		{
			$this->setMessage(JText::sprintf($this->text_prefix . '_REBUILD_FAILURE', $model->getError()), 'error');

			return false;
		}
	}

	/**
	 * Method to set the default category for a category type.
	 *
	 * @since  1.0.0
	 */
	public function setDefault()
	{
		// Check for request forgeries
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
		$app = JFactory::getApplication();

		// Initialise variables.
		$pks = $app->input->post->get('cid', array(), 'array');

		$this->setRedirect('index.php?option=com_sellacious&view=categories');

		try
		{
			$pks = ArrayHelper::toInteger($pks);

			if (empty($pks))
			{
				throw new Exception(500, JText::_('COM_SELLACIOUS_CATEGORIES_NO_ITEM_SELECTED'));
			}

			// Pop off the first element.
			$id    = array_shift($pks);
			$model = $this->getModel();

			$model->setDefault($id);

			$this->setMessage(JText::_('COM_SELLACIOUS_CATEGORIES_DEFAULT_SET'));
		}
		catch (Exception $e)
		{
			JLog::add($e->getMessage(), JLog::WARNING, 'jerror');

			return false;
		}

		return true;
	}

	/**
	 * Method to set the default category for a category type.
	 *
	 * @return   bool
	 *
	 * @since  1.4.7
	 */
	public function csvTemplate()
	{
		JSession::checkToken('request') or jexit(JText::_('JINVALID_TOKEN'));
		$app = JFactory::getApplication();

		$pks = $app->input->get('cid', array(), 'array');
		$pks = ArrayHelper::toInteger($pks);
		$dl  = $app->input->getInt('dl');

		$this->setRedirect('index.php?option=com_sellacious&view=categories');

		try
		{
			if ($dl)
			{
				/** @var  Sellacious\Utilities\Import\Products  $importer */
				$importer = Import::getInstance('Products');
				$columns  = $importer->getColumns($pks);

				if (headers_sent($file, $line))
				{
					throw new Exception(JText::sprintf('COM_SELLACIOUS_HEADERS_ALREADY_SENT_AT', $file, $line));
				}

				header('content-type: text/csv');
				header('content-disposition: attachment; filename="sellacious-products-importable.csv"');
				header("Pragma: no-cache");
				header("Expires: 0");

				$stdout = fopen('php://output', 'w');
				fputcsv($stdout, $columns);
				fclose($stdout);
				jexit();
			}
			else
			{
				$token = JSession::getFormToken();
				$uri   = new JUri('index.php?option=com_sellacious&task=categories.csvTemplate');

				$uri->setVar('cid', $pks);
				$uri->setVar('dl', 1);
				$uri->setVar($token, 1);

				$this->helper->core->metaRedirect($uri->toString());

				$this->setMessage(JText::_('COM_SELLACIOUS_IMPORT_CSV_TEMPLATE_DOWNLOAD_INITIATED'));
			}
		}
		catch (SellaciousExceptionPremium $e)
		{
			$this->setMessage($e->getMessage(), 'premium');

			return false;
		}
		catch (Exception $e)
		{
			JLog::add($e->getMessage(), JLog::WARNING, 'jerror');

			return false;
		}

		return true;
	}
}
