<?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
 */

namespace E4J\VikRestaurants\API\Plugins;

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

use E4J\VikRestaurants\API\Event;
use E4J\VikRestaurants\API\Response;

/**
 * Event used to invoke the delete method of the specified model.
 *
 * @since 1.11.1
 */
class DeleteDataPluginAPI extends Event
{
	/**
	 * @inheritDoc
	 */
	protected function execute(array $args, Response $response)
	{
		try
		{
			// first look within the request for the model to load
			$modelName = \JFactory::getApplication()->input->get('model');

			if (!$modelName)
			{
				// model not found within the request, lets load it from the payload
				if (empty($args['modelname']))
				{
					// missing model
					throw new \Exception('Model not specified', 400);
				}

				// extract model name from payload
				$modelName = $args['modelname'];
			}

			// lets load the model
			$model = \JModelVRE::getInstance($modelName);

			if (!$model)
			{
				// the given model doesn't exist
				throw new \Exception(sprintf('Model [%s] does not exist', $modelName), 404);
			}

			if (empty($args['id']))
			{
				// missing ID attribute
				throw new \Exception('The payload doesn\'t specify the ID(s) to delete', 400);
			}

			// delete given records
			$status = $model->delete($args['id']);
		}
		catch (\Exception $error)
		{
			// register response and abort request
			$response->setStatus(0)->setContent($error->getMessage());

			// propagate error to safely launch the correct status code
			throw $error;
		}

		// removal was successful
		$response->setStatus(1);
		// register short description
		$response->setContent(sprintf('Deleted [%s] with ID [%s]', $modelName, implode(', ', (array) $args['id'])));

		// let the application framework safely output the response
		return $status;
	}

	/**
	 * @inheritDoc
	 */
	public function getTitle()
	{
		/**
		 * @todo translate
		 */
		return 'Delete Data';
	}

	/**
	 * @inheritDoc
	 */
	public function getShortDescription()
	{
		/**
		 * @todo translate
		 */
		return 'This plugin can be used to delete any element via API according to the specifications of the requested model.';
	}

	/**
	 * @inheritDoc
	 */
	public function getDescription()
	{
		// read the description HTML from a layout
		return \JLayoutHelper::render('apis.plugins.delete_data', ['plugin' => $this]);
	}
}
