<?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 save method of the specified model.
 *
 * @since 1.11.1
 */
class SaveDataPluginAPI 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);
			}

			// save given payload
			$id = $model->save($args);

			if (!$id)
			{
				// an error occurred, retrieve error from model
				$error = $model->getError();

				if (!$error instanceof Exception)
				{
					$error = new Exception($error ? $error : 'Error', 500);
				}

				throw $error;
			}
		}
		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;
		}

		// save was successful
		$response->setStatus(1);
		// register short description
		$response->setContent(sprintf('Saved [%s] with ID [%s]', $modelName, $id));

		// let the application framework safely output the response
		return $model->getData();
	}

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

	/**
	 * @inheritDoc
	 */
	public function getShortDescription()
	{
		/**
		 * @todo translate
		 */
		return 'This plugin can be used to insert/update 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.save_data', ['plugin' => $this]);
	}
}
