<?php
/** 
 * @package     VikRestaurants
 * @subpackage  core
 * @author      E4J s.r.l.
 * @copyright   Copyright (C) 2023 E4J s.r.l. All Rights Reserved.
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @link        https://vikwp.com
 */

// No direct access
defined('ABSPATH') or die('No script kiddies please!');

VRELoader::import('library.mvc.controllers.admin');

/**
 * VikRestaurants admin note controller.
 *
 * @since 1.8
 */
class VikRestaurantsControllerAdminnote extends VREControllerAdmin
{
	/**
	 * Task used to save the record data set in the request.
	 * After saving, the user is redirected to the management
	 * page of the record that has been saved.
	 *
	 * @return 	void
	 */
	public function save()
	{
		$app  = JFactory::getApplication();
		$user = JFactory::getUser();

		if (!JSession::checkToken())
		{
			// missing CSRF-proof token
			E4J\VikRestaurants\Http\Document::getInstance($app)->close(403, JText::translate('JINVALID_TOKEN'));
		}
		
		$args = [];
		$args['id'] = $app->input->getInt('id', 0);
		$args['content'] = JComponentHelper::filterText($app->input->getRaw('content', ''));
		$args['status'] = $app->input->getUint('status', null);

		if (empty($args['content']))
		{
			unset($args['content']);
		}

		// get admin note model
		$adminNote = $this->getModel();

		if (!empty($args['id']))
		{
			$note = $adminNote->getItem($args['id'], $blank = true);

			if ($note->created_by != $user->id && $note->status == 0)
			{
				// the user is not authorized to update this note
				E4J\VikRestaurants\Http\Document::getInstance($app)->close(403, JText::translate('JERROR_ALERTNOAUTHOR'));
			}
		}

		// try to save arguments
		$id = $adminNote->save($args);

		if (!$id)
		{
			// get string error
			$error = $adminNote->getError(null, true);

			// display error message
			E4J\VikRestaurants\Http\Document::getInstance($app)->close(500, JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $error));
		}

		// reload note information and send them to the caller
		$this->sendJSON($adminNote->getItem($id));
	}

	/**
	 * Deletes a list of records set in the request.
	 *
	 * @return 	boolean
	 */
	public function delete()
	{
		$app  = JFactory::getApplication();
		$user = JFactory::getUser();

		if (!JSession::checkToken() && !JSession::checkToken('get'))
		{
			// missing CSRF-proof token
			E4J\VikRestaurants\Http\Document::getInstance($app)->close(403, JText::translate('JINVALID_TOKEN'));
		}

		$id = $app->input->get('id', 0, 'uint');

		// get admin note model
		$adminNote = $this->getModel();

		$note = $adminNote->getItem($id, $blank = true);

		if ($note->created_by != $user->id)
		{
			// the user is not authorized to delete this note
			E4J\VikRestaurants\Http\Document::getInstance($app)->close(403, JText::translate('JERROR_ALERTNOAUTHOR'));
		}

		// delete selected records
		$adminNote->delete($id);

		$this->sendJSON($note);
	}
}
