<?php
/**
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @copyright   Copyright (C) 2016-2024 CMExension
 * @license     GNU General Public License version 2 or later
 */

defined('_JEXEC') or die;

use Joomla\Filter\InputFilter;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Response\JsonResponse;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\Session\Session;
use Joomla\CMS\Layout\FileLayout;

/**
 * Controller class for menu item.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       1.0.0
 */
class CMGiftCardControllerItem extends BaseController
{
	/**
	 * Proxy for getModel.
	 *
	 * @param   string  $name    The model name. Optional.
	 * @param   string  $prefix  The class prefix. Optional.
	 * @param   array   $config  The array of possible config values. Optional.
	 *
	 * @return  object  The model.
	 *
	 * @since   1.0.0
	 */
	public function getModel($name = 'Item', $prefix = 'CMGiftCardModel', $config = array('ignore_request' => true))
	{
		$model = parent::getModel($name, $prefix, $config);

		return $model;
	}

	/**
	 * Save item.
	 *
	 * @return  void
	 *
	 * @since   1.0.0
	 */
	public function save()
	{
		$app = Factory::getApplication();

		if (Session::checkToken('get'))
		{
			$app->enqueueMessage(Text::_('JINVALID_TOKEN'), 'error');
			echo new JsonResponse(null, null, true);

			$app->close();
		}

		$inputData = $app->input->post->get('data', '', 'raw');
		$data = array();
		parse_str($inputData, $data);

		$fields = array(
			'id', 'title', 'menu_id', 'parent_id', 'menu_item_id',
			'value', 'image', 'button_label', 'type', 'full_width', 'ordering'
		);

		$filter = new InputFilter;

		foreach ($fields as $field)
		{
			if (!isset($data[$field]))
				$data[$field] = '';

			switch ($field)
			{
				case 'id':
				case 'menu_id':
				case 'parent_id':
				case 'full_width':
				case 'ordering':
				case 'menu_item_id':
					$data[$field] = $filter->clean($data[$field], 'uint');
					break;

				default:
					$data[$field] = ComponentHelper::filterText($data[$field]);
			}
		}

		$menu = BaseDatabaseModel::getInstance('Menu', 'CMGiftCardModel')->getItem($data['menu_id']);

		if (empty($menu->id))
		{
			$app->enqueueMessage(Text::_('COM_CMGIFTCARD_ERROR_MENU_NOT_FOUND'), 'error');
			echo new JsonResponse(null, null, true);

			$app->close();
		}

		if ($data['title'] == '')
		{
			$app->enqueueMessage(Text::_('COM_CMGIFTCARD_ERROR_EMPTY_ITEM_TITLE'), 'error');
			echo new JsonResponse(null, null, true);

			$app->close();
		}

		$model = $this->getModel();

		$response = array(
			'html'	=> '',
		);

		if ($model->save($data))
		{
			$layout = new FileLayout('itemlist', $basePath = JPATH_ROOT . '/administrator/components/com_cmgiftcard/layouts');

			$data = array(
				'menu'	=> $menu,
			);

			$response['html'] = $layout->render($data);

			$app->enqueueMessage(Text::_('COM_CMGIFTCARD_ITEM_SAVE_SUCCESS'));
			echo new JsonResponse($response);
		}
		else
		{
			$app->enqueueMessage($model->getError(), 'error');
			echo new JsonResponse($response, null, true);
		}
	}

	/**
	 * Get edit form for an item.
	 *
	 * @return  void
	 *
	 * @since   1.0.0
	 */
	public function getForm()
	{
		$app = Factory::getApplication();

		if (!Session::checkToken('get'))
		{
			$app->enqueueMessage(Text::_('JINVALID_TOKEN'), 'error');
			echo new JsonResponse(null, null, true);

			$app->close();
		}

		$itemId		= $app->input->post->get('item_id', 0, 'integer');
		$parentId	= $app->input->post->get('parent_id', 0, 'integer');
		$menuId		= $app->input->post->get('menu_id', 0, 'integer');

		$menu = BaseDatabaseModel::getInstance('Menu', 'CMGiftCardModel')->getItem($menuId);

		if (empty($menu->id))
		{
			$app->enqueueMessage(Text::_('COM_CMGIFTCARD_ERROR_MENU_NOT_FOUND'), 'error');
			echo new JsonResponse(null, null, true);

			$app->close();
		}

		$model = $this->getModel();
		$item = null;
		$parent = null;

		if ($parentId > 0)
		{
			$parent = $model->getItem($parentId);

			if (empty($parent->id))
			{
				$app->enqueueMessage(Text::_('COM_CMGIFTCARD_ERROR_PARENT_ID_NOT_FOUND'), 'error');
				echo new JsonResponse(null, null, true);

				$app->close();
			}
		}

		if ($itemId > 0)
		{
			$item = $model->getItem($itemId);

			if (empty($item->id))
			{
				$app->enqueueMessage(Text::_('COM_CMGIFTCARD_ERROR_ITEM_NOT_FOUND'), 'error');
				echo new JsonResponse(null, null, true);

				$app->close();
			}
		}

		$layout = new FileLayout('itemform', $basePath = JPATH_ROOT . '/administrator/components/com_cmgiftcard/layouts');

		$data = array(
			'menu'		=> $menu,
			'item'		=> $item,
			'parent'	=> $parent,
		);

		$response['html'] = $layout->render($data);

		echo new JsonResponse($response);
	}

	/**
	 * Delete an item.
	 *
	 * @return  void
	 *
	 * @since   1.0.0
	 */
	public function delete()
	{
		$app = Factory::getApplication();

		if (!Session::checkToken('get'))
		{
			$app->enqueueMessage(Text::_('JINVALID_TOKEN'), 'error');
			echo new JsonResponse(null, null, true);

			$app->close();
		}

		$itemId = $app->input->post->get('item_id', 0, 'integer');
		$model = $this->getModel();

		if ($itemId > 0)
		{
			$item = $model->getItem($itemId);
		}
		else
		{
			$item = null;
		}

		if (empty($item->id))
		{
			$app->enqueueMessage(Text::_('COM_CMGIFTCARD_ERROR_ITEM_NOT_FOUND'), 'error');
			echo new JsonResponse(null, null, true);

			$app->close();
		}

		$response = array(
			'html'	=> '',
		);

		if ($model->delete($itemId))
		{
			$menu = BaseDatabaseModel::getInstance('Menu', 'CMGiftCardModel')->getItem($item->menu_id);

			if (!empty($menu->id))
			{
				$layout = new FileLayout('itemlist', $basePath = JPATH_ROOT . '/administrator/components/com_cmgiftcard/layouts');

				$data = array(
					'menu'	=> $menu,
				);

				$response['html'] = $layout->render($data);
			}
			else
			{
				$app->enqueueMessage(Text::_('COM_CMGIFTCARD_ERROR_MENU_NOT_FOUND'));
			}

			$app->enqueueMessage(Text::_('COM_CMGIFTCARD_ITEM_DELETE_SUCCESS'));
			echo new JsonResponse($response);
		}
		else
		{
			$app->enqueueMessage($model->getError(), 'error');
			echo new JsonResponse($response, null, true);
		}
	}
}
