<?php
/**
 * @version        4.3.0
 * @package        Joomla
 * @subpackage     Helpdesk Pro
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2013 - 2021 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */

namespace OSSolution\HelpdeskPro\Site\Controller;

use Exception;
use Joomla\CMS\Language\Text;
use OSSolution\HelpdeskPro\Site\Helper\Helper as HelpdeskproHelper;

defined('_JEXEC') or die;

class Api extends \OSL\Controller\Controller
{
	/**
	 * Add ticket
	 *
	 * @throws Exception
	 */
	public function add()
	{
		$this->validateAPIRequest();

		$errors = $this->validateTicketData($this->input);

		if (count($errors))
		{
			$success      = false;
			$responseData = $errors;
		}
		else
		{
			// Make sure id is not provided on a add request
			$this->input->remove('id');

			/* @var \OSSolution\HelpdeskPro\Admin\Model\Ticket $model */
			$model = $this->getModel('Ticket', ['ignore_request' => true]);
			$model->store($this->input);

			$success            = true;
			$responseData['id'] = $this->input->getInt('id');
		}


		$this->sendResponse($success, $responseData);
	}


	/**
	 * Validate data which is passed to add new ticket
	 *
	 * @param   \OSL\Input\Input  $input
	 *
	 * @return array
	 */
	protected function validateTicketData($input)
	{
		$data = $input->getData();

		$errors = [];

		if (empty($data['user_id']) && empty($data['username']))
		{
			// If user id is not provided, name and email must be passed

			if (empty($data['name']))
			{
				$errors[] = Text::_('You need to provide Name of user for this ticket');
			}

			if (empty($data['email']))
			{
				$errors[] = Text::_('You need to provide email of user for this ticket');
			}
		}
		else
		{
			$db = $this->container->db;

			// Validate and make user exists
			if (!empty($data['user_id']))
			{
				$userId = (int) $data['user_id'];

				$query = $db->getQuery(true)
					->select('COUNT(*)')
					->from('#__users')
					->where('id = ' . $userId);
				$db->setQuery($query);

				if (!$db->loadResult())
				{
					$errors[] = Text::sprintf('There is no user with ID %s in the system', $userId);
				}
			}
			else
			{
				$username = $data['username'];

				$query = $db->getQuery(true)
					->select('id')
					->from('#__users')
					->where('username = ' . $db->quote($username));
				$db->setQuery($query);

				$userId          = (int) $db->loadResult();
				$data['user_id'] = $userId;

				if (!$userId)
				{
					$errors[] = Text::sprintf('There is no user with username %s in the system', $username);
				}
			}
		}

		if (empty(trim($data['subject'])))
		{
			$errors[] = Text::_('Please provide subject for the ticket');
		}

		if (empty(trim($data['message'])))
		{
			$errors[] = Text::_('Please provide message for the ticket');
		}

		// Validate Category ID
		if (empty($data['category_id']))
		{
			$errors[] = Text::_('Please provide Category ID for the ticket');
		}

		return $errors;
	}

	/**
	 * Basic API validation, should be called before each request
	 *
	 * @throws \Exception
	 */
	protected function validateAPIRequest()
	{
		$config = HelpdeskproHelper::getConfig();

		// Check and make sure API is enabled
		if (!$config->enable_api)
		{
			throw new \Exception(Text::_('API is not enabled on this site'));
		}

		// Check API Key
		$apiKey = $this->input->getString('api_key');

		if ($apiKey !== $config->api_key)
		{
			throw new Exception(sprintf('The provided API Key %s is invalid', $apiKey));
		}
	}

	/**
	 * Send json response to the API call
	 *
	 * @param   bool   $success
	 * @param   array  $data
	 */
	protected function sendResponse($success, $data)
	{
		$response['success'] = $success;

		if ($success)
		{
			$response['data'] = $data;
		}
		else
		{
			$response['errors'] = $data;
		}

		echo json_encode($response);
		$this->app->close();
	}
}