<?php

declare(strict_types=1);

namespace kodorvan\neurobot\controllers\acquirings;

// Files of the project
use kodorvan\neurobot\controllers\core,
	kodorvan\neurobot\models\account,
	kodorvan\neurobot\models\tariff,
	kodorvan\neurobot\models\invoice,
	kodorvan\neurobot\models\enumerations\tariff as tariff_type,
	kodorvan\neurobot\models\enumerations\acquiring;

// Framework for PHP
use mirzaev\minimal\http\enumerations\content,
	mirzaev\minimal\http\enumerations\status;

// Framework for Telegram
use Zanzara\Zanzara as zanzara,
	Zanzara\Context as context,
	Zanzara\Config as config,
	Zanzara\Telegram\Type\Message as message;

/**
 * YooKassa
 *
 * @package kodorvan\neurobot\controllers\acquirings
 *
 * @param array $errors Registry of errors
 *
 * @method null payment() The page for success payment receive
 *
 * @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
 * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
 */
final class yookassa extends core
{
	/**
	 * Errors
	 *
	 * @var array $errors Registry of errors
	 */
	protected array $errors = [
		'system' => []
	];

	/**
	 * Payment page
	 *
	 * @return null
	 */
	public function payment(): null
	{
		if (str_contains($this->request->headers['accept'] ?? '', content::html->value)) {
			// Request for any response

			// Render page
			$page = $this->view->render('/acquirings/yookassa/success.html');

			// Sending response
			$this->response
				->start()
				->clean()
				->sse()
				->write($page)
				->validate($this->request)
				?->body()
				->end();

			// Deinitializing rendered page
			unset($page);

			// Exit (success)
			return null;
		}

		// Exit (fail)
		return null;
	}

	/**
	 * Callback
	 *
	 * @see https://yookassa.ru/developers/using-api/webhooks Callback API (not webhooks)
	 * @see https://yookassa.ru/developers/using-api/webhooks#events Events
	 *
	 * @param string|null $type Type of the event (always 'notification')
	 * @param string|null $event Name of the event (example: 'payment.succeeded')
	 * @param array|null $object JSON-object with the event content
	 *
	 * @return null
	 */
	public function callback(?string $type = null, ?string $event = null, ?array $object = null): null
	{
		// Sending response
		$this->response
			->start()
			->clean()
			->sse()
			->validate($this->request)
			?->body()
			->end();

		if ($type === 'notification') {
			// Notifiaction

			if ($event === 'payment.succeeded') {
				// Success

				// Searching for the invoice
				$invoice = new invoice()->read(filter: fn($record) => $record->acquiring_identifier === $object['id']);

				if ($invoice instanceof invoice) {
					// Found the invoice 

					// Searching for the tariff
					$tariff = new tariff()->read(filter: fn($record) => $record->invoice === $invoice->identifier);

					if ($tariff instanceof tariff) {
						// Found the tariff

						// Activating the tariff
						$tariff->active = 1;

						// Writing the updated tariff into the database
						$tariff->update();

						// Initializing the account
						$account = new account()->read(filter: fn($record) => $record->identifier === $tariff->account);

						// Writing the account tariff
						$account->tariff = $tariff->identifier;

						// Writing the updated account into the database
						$account->update();

						// Deserializing the account
						$account->deserialize();

						if ($account instanceof account) {
							// Found the account

							// Initializing configuration for the chat-robot Telegram
							$config = new config();
							$config->setParseMode(config::PARSE_MODE_MARKDOWN);
							$config->useReactFileSystem(true);

							// Initializing the chat-robot Telegram
							$robot = new zanzara(TELEGRAM_KEY, $config);

							// Initializing path to the localization file
							$file = LOCALIZATIONS . DIRECTORY_SEPARATOR . strtolower($account->language->label()) . '.php';

							if (file_exists($file) && is_readable($file)) {
								// Found the localization file

								// Initializing localization
								$localization = require($file);

								if (is_array($localization)) {
									// Initialized the localization

									// Sending the message
									$robot->getTelegram()->sendMessage('✅ *' . $localization['tariff_invoice_success'] . '*', ['chat_id' => $account->identifier_telegram])
										->then(function ($message) {
											// Sended the message

										});
								}
							}
						}
					}
				}
			} else if ($event === 'payment.canceled') {
				// Cancel

			}
		}

		// Exit (success)
		return null;
	}
}
