<?php
/** 
 * @package     VikAppointments
 * @subpackage  core
 * @author      E4J s.r.l.
 * @copyright   Copyright (C) 2021 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!');

/**
 * Event used to invoke the delete method of the specified model.
 *
 * @since 1.7
 */
class VAPApiEventDeleteData extends VAPApiEvent
{
	/**
	 * The custom action that the event have to perform.
	 * This method should not contain any exit or die function, 
	 * otherwise the event won't be properly terminated.
	 *
	 * @param 	array           $args      The provided arguments for the event.
	 * @param 	VAPApiResponse  $response  The response object for admin.
	 *
	 * @return 	mixed           The response to output or the error message (ErrorAPIs).
	 */
	protected function doAction(array $args, VAPApiResponse $response)
	{
		// 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
				$error = new Exception('Model not specified', 400);

				// register response and abort request
				$response->setStatus(0)->setContent($error->getMessage());

				throw $error;
			}

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

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

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

			// register response and abort request
			$response->setStatus(0)->setContent($error->getMessage());

			throw $error;
		}

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

			// register response and abort request
			$response->setStatus(0)->setContent($error->getMessage());

			throw $error;
		}

		// delete given records
		$status = $model->delete($args['id']);

		// 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;
	}

	/**
	 * @override
	 * Returns the description of the plugin.
	 *
	 * @return 	string
	 */
	public function getDescription()
	{
		// read the description HTML from a layout
		return JLayoutHelper::render('api.plugins.delete_data', array('plugin' => $this));
	}
}
