<?php

/*------------------------------------------------------------------------
# JBusinessDirectory
# author CMSJunkie
# copyright Copyright (C) 2012 cmsjunkie.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.cmsjunkie.com
# Technical Support: Forum - http://www.cmsjunkie.com/forum/j-businessdirectory/?p=1
-------------------------------------------------------------------------*/

defined('_JEXEC') or die('Restricted access');

use Joomla\Utilities\ArrayHelper;
use Joomla\CMS\Session\Session;

class JBusinessDirectoryControllerProjects extends JControllerAdmin {
	/**
	 * Class constructor.
	 *
	 * @param   array $config A named array of configuration variables.
	 *
	 * @since   1.6
	 */
	public function __construct($config = array()) {
		parent::__construct($config);

		$this->registerTask('unpublish', 'changeState');
		$this->registerTask('publish', 'changeState');
	}

	/**
	 * Display the view
	 *
	 * @param   boolean			If true, the view output will be cached
	 * @param   array  An array of safe url parameters and their variable types, for valid values see {@link JFilterInput::clean()}.
	 *
	 * @return  JController		This object to support chaining.
	 * @since   1.6
	 */
	public function display($cachable = false, $urlparams = false) {
	}

	/**
	 * 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.6
	 */
	public function getModel($name = 'Project', $prefix = 'JBusinessDirectoryModel', $config = array('ignore_request' => true)) {
		$model = parent::getModel($name, $prefix, $config);
		return $model;
	}

	public function back() {
		$this->setRedirect('index.php?option=com_jbusinessdirectory');
	}

	/**
	 * Removes an item
	 */
	public function delete() {
		// Check for request forgeries
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		// Get items to remove from the request.
		$cid = $this->input->get('cid', array(), 'array');

		if (!is_array($cid) || count($cid) < 1) {
			JError::raiseWarning(500, JText::_('COM_JBUSINESSDIRECTORY_NO_PROJECT_SELECTED'));
		} else {
			// Get the model.
			$model = $this->getModel("Project");

			// Make sure the item ids are integers
			jimport('joomla.utilities.arrayhelper');
			ArrayHelper::toInteger($cid);

			// Remove the items.
			if (!$model->delete($cid)) {
				$this->setMessage($model->getError());
			} elseif (!empty($model->getErrors())) {
				$implodeErrors = implode('<br />', $model->getErrors());
				$this->setMessage(JText::sprintf('COM_JBUSINESSDIRECTORY_DELETED_WARNING', $implodeErrors), 'Warning');
			} else {
				$this->setMessage(JText::plural('COM_JBUSINESSDIRECTORY_N_PROJECTS_DELETED', count($cid)));
			}
		}

		$this->setRedirect('index.php?option=com_jbusinessdirectory&view=projects');
	}

	/**
	 * Change state of selected item
	 */
	public function changeState() {
		// Check for request forgeries
		//Session::checkToken() or die(JText::_('JINVALID_TOKEN'));

		// Get items to publish from the request.
		$cid   = $this->input->get('cid', array(), 'array');
		$data  = array('publish' => 1, 'unpublish' => 0, 'archive' => 2, 'trash' => -2, 'report' => -3);
		$task  = $this->getTask();
		$value = ArrayHelper::getValue($data, $task, 0, 'int');
		$error = false;

		$model = $this->getModel('Project');
		foreach ($cid as $item) {
			if (!$model->changeState($item, $value)) {
				$this->setMessage(JText::_('LNG_ERROR_CHANGE_STATE'), 'warning');
			} else {
				if ($value == 1) {
					$ntext = $this->text_prefix . '_N_ITEMS_PUBLISHED';
				} elseif ($value == 0) {
					$ntext = $this->text_prefix . '_N_ITEMS_UNPUBLISHED';
				} elseif ($value == 2) {
					$ntext = $this->text_prefix . '_N_ITEMS_ARCHIVED';
				} else {
					$ntext = $this->text_prefix . '_N_ITEMS_TRASHED';
				}

				$this->setMessage(JText::plural($ntext, count($cid)));
			}
		}

		$ajax = $this->input->get('ajax');
		if (!empty($ajax)) {
			$response          = array();
			$response["cid"]   = $cid[0];
			$response["error"] = $error;

			echo json_encode($response);

			exit;
		}

		$this->setRedirect('index.php?option=com_jbusinessdirectory&view=projects');
	}

	/**
	 * Override the publish parent method to allow type parameter in link
	 *
	 * @return  void
	 *
	 */
	public function publish() {
		// Check for request forgeries
		JSession::checkToken() or die(JText::_('JINVALID_TOKEN'));
		// Get items to publish from the request.
		$cid = JFactory::getApplication()->input->get('cid', array(), 'array');
		$data = array('publish' => 1, 'unpublish' => 0, 'archive' => 2, 'trash' => -2, 'report' => -3);
		$task = $this->getTask();
		$value = ArrayHelper::getValue($data, $task, 0, 'int');

		$model = $this->getModel('Project');

		if (empty($cid)) {
			JLog::add(JText::_($this->text_prefix . '_NO_ITEM_SELECTED'), JLog::WARNING, 'jerror');
		} else {
			// Make sure the item ids are integers
			ArrayHelper::toInteger($cid);

			// Publish the items.
			try {
				$model->publish($cid, $value);
				$errors = $model->getErrors();

				if ($value == 1) {
					if ($errors) {
						$app = JFactory::getApplication();
						$app->enqueueMessage(JText::plural($this->text_prefix . '_N_ITEMS_FAILED_PUBLISHING', count($cid)), 'error');
					} else {
						$ntext = $this->text_prefix . '_N_ITEMS_PUBLISHED';
					}
				} elseif ($value == 0) {
					$ntext = $this->text_prefix . '_N_ITEMS_UNPUBLISHED';
				} elseif ($value == 2) {
					$ntext = $this->text_prefix . '_N_ITEMS_ARCHIVED';
				} else {
					$ntext = $this->text_prefix . '_N_ITEMS_TRASHED';
				}

				$this->setMessage(JText::plural($ntext, count($cid)));
			} catch (Exception $e) {
				$this->setMessage($e->getMessage(), 'error');
			}
		}

		$type = $this->input->get('filter_type');
		$typeURL = ($type) ? '&filter_type=' . $type : '';
		$this->setRedirect(JRoute::_('index.php?option=' . $this->option . '&view=' . $this->view_list . $typeURL, false));
	}
}
