<?php
/**
 * @package    JBusinessDirectory
 *
 * @author CMSJunkie http://www.cmsjunkie.com
 * @copyright  Copyright (C) 2007 - 2021 CMSJunkie. All rights reserved.
 * @license   https://www.gnu.org/licenses/agpl-3.0.en.html
 */
defined('_JEXEC') or die('Restricted access');
use Joomla\Utilities\ArrayHelper;
use Joomla\CMS\Session\Session;

class JBusinessDirectoryControllerEvents extends JControllerLegacy {

	/**
	 * 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 = 'Events', $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');
	}
	
	/**
	 * Delete an event or the associated reccuring events.
	 */
	public function delete() {
		// Check for request forgeries
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));

		// Get the model.
		$model = $this->getModel("Event");
		$this->deleteEvents($model);

		$this->setRedirect('index.php?option=com_jbusinessdirectory&view=events');
	}
	
	public function deleteEvents($model) {
		// Get items to remove from the request.
		$cid = $this->input->get('cid', array(), 'array');
		$delete_mode = JFactory::getApplication()->input->get("delete_mode", 1);
		$delete_ids = array();
		//if there are multiple events selected delete only the events selected. If only one give multiple options.
		
		if (!empty($cid) && count($cid)>1) {
			$delete_ids = $cid;
		} else {
			$id = $cid[0];
			switch ($delete_mode) {
				case 1:
					$delete_ids[]= $id;
					break;
				case 2:
					$delete_ids= $model->getNextEventsIds($id);
					break;
				case 3:
					$delete_ids = $model->getAllSeriesEventsIds($id);
					break;
				default:
					$delete_ids[]= $id;
					break;
			}
		}
		
		if (!is_array($delete_ids) || count($delete_ids) < 1) {
			JFactory::getApplication()->enqueueMessage(JText::_('COM_JBUSINESSDIRECTORY_NO_EVENT_SELECTED'), 'error');
		} else {
			// Make sure the item ids are integers
			jimport('joomla.utilities.arrayhelper');
			ArrayHelper::toInteger($delete_ids);
		
			// Remove the items.
			if (!$model->delete($delete_ids)) {
				$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_EVENTS_DELETED', count($delete_ids)));
			}
		}
		
		$this->setRedirect('index.php?option=com_jbusinessdirectory&view=events');
	}

	public function unpublish() {
		$model = $this->getModel('Event');

		if ($model->changeState()) {
			$this->setMessage(JText::_('LNG_ERROR_CHANGE_STATE'), 'warning');
		}

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

	/**
	 * 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('Event');
		if (!$model->changeState($cid[0])) {
			$this->setMessage(JText::_('LNG_ERROR_CHANGE_STATE'), 'warning');
			$error = true;
		} else {
			$this->text_prefix = "COM_JBUSINESSDIRECTORY";
			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';
			}

			if ($ntext !== null) {
				$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=events');
	}
	
	public function changeStateEventOfTheDay() {
		$model = $this->getModel('Event');
	
		if (!$model->changeStateEventOfTheDay()) {
			$this->setMessage(JText::_('LNG_ERROR_CHANGE_STATE'), 'warning');
		}
	
		$this->setRedirect('index.php?option=com_jbusinessdirectory&view=events');
	}

	public function importFromCsv() {
		JFactory::getApplication()->input->set("layout", "import");
		parent::display();
	}

	public function showExportCsv() {
		JFactory::getApplication()->input->set("layout", "export");
		parent::display();
	}

	public function exportEventsCsv() {
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
		$model = $this->getModel('events');
		$model->exportEventsCSV();
		exit;
	}

	public function importEventsFromCsv() {
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
		$config = JBusinessUtil::getSiteConfig();
		$filePath = $config->tmp_path;
		$data = JFactory::getApplication()->input->post->getArray();
		
		//upload file
		$filePath = JBusinessUtil::uploadFile("csvFile", $data, $filePath);
		
		$model = $this->getModel("Event");
		$model->importEventsFromCSV($filePath, $data["delimiter"]);

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

	public function importEventsFromTxtArea() {
		JSession::checkToken() or jexit(JText::_('JINVALID_TOKEN'));
		$data = JFactory::getApplication()->input->post->getArray();

		$csvContent = null;
		if (!empty($data["eventData_ForImport"])) {
			$csvContent = explode("\n", $data["eventData_ForImport"]);
		}

		$model = $this->getModel("Event");
		$model->importEventsFromTextArea($csvContent, $data["delimiter"]);

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

	/**
	 * Get all events by string
	 *
	 * @throws Exception
	 * @since   5.3.1
	 */
	public function getEventsByStringAjax() {
		$str = JFactory::getApplication()->input->get('term', null);
		header("Content-Type: application/json", true);
		echo json_encode(JBusinessUtil::getEventsByString($str));
		exit;
	}
}
