<?php

declare(strict_types=1);

namespace kodorvan\neurobot\models\acquirings;

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

// Library for currencies support
use mirzaev\currencies\currency;

// The library for YooKassa support
use	YooKassa\Request\Payments\CreatePaymentRequest as yookassa_request,
	YooKassa\Model\CurrencyCode as yookassa_currency,
	YooKassa\Model\ConfirmationType as yookassa_confirmation,
	YooKassa\Model\NotificationEventType as yookassa_event;

// Built-in libraries
use Exception as exception,
	RuntimeException as exception_runtime;

/**
 * YooKassa
 *
 * @package kodorvan\neurobot\models\acquirings
 *
 * @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
{
	/**
	 * Invoice
	 *
	 * @throws exception_runtime If failed to create the invoice
	 *
	 * @param int $account The account identifier
	 * @param tariff_type $tariff The tariff type
	 * @param int|float $cost
	 * @param currency $currency
	 * @param string $description
	 *
	 * @return string|null The URL to pay the generated invoice
	 */
	public static function invoice(int $account, tariff_type $tariff, int|float $cost, currency $currency = currency::usd, string $description = ''): string|null
	{
		try {
			// Initializing the yookassa request
			$request = yookassa_request::builder();

			// Packing the yookassa request
			$request = $request
				->setAmount($cost)
				->setCapture(true)
				->setCurrency(yookassa_currency::{$currency->value} ?? yookassa_currency::USD)
				->setDescription($description)
				->setConfirmation([
					'type'      => yookassa_confirmation::REDIRECT,
					'returnUrl' => 'https://' . PROJECT_DOMAIN . '/invoice/yookassa/payment',
				])
				->build();

			// Sending the request
			$response = YOOKASSA->createPayment($request);

			// Creating the invoice
			$invoice = new invoice()->write(account: $account, acquiring: acquiring::yookassa, acquiring_identifier: $response->getId());

			if (is_int($invoice)) {
				// Created the invoice

				// Creating the tariff
				$tariff = new tariff()->write(account: $account, invoice: $invoice, active: 0, type: $tariff);

				if (is_int($tariff)) {
					// Created the tariff

					// Exit (success)
					return $response->getConfirmation()->getConfirmationUrl();
				} else {
					// Not created the tariff

					// Exit (fail)
					throw new exception_runtime('Failed to create the tariff');
				}
			} else {
				// Not created the invoice

				// Exit (fail)
				throw new exception_runtime('Failed to create the invoice');
			}
		} catch (exception $exception) {
			error_log(print_r($exception, true));
		}

		// Exit (fail)
		return null;
	}


	/**
	 * Payment
	 *
	 * Initializing the payment webhooks (only for OAuth authentication)
	 *
	 * @return void
	 *
	 * @deprecated
	 */
	public static function payment(): void
	{
		// Initializing the webhook URL
		$url = 'https://' . PROJECT_DOMAIN . '/acquirings/yookassa/webhooks/payment';

		// Initializing the webhooks list
		$webhooks = YOOKASSA->getWebhooks()->getItems();

		foreach ([yookassa_event::PAYMENT_SUCCEEDED => '/success', yookassa_event::PAYMENT_CANCELED => '/fail'] as $event => $urn) {
			// Iterating over target events

			foreach ($webhooks as $webhook) {
				// Iterating over webhooks

				if ($webhook->getEvent() === $event) {
					// Matched the webhook event

					if ($webhook->getUrl() === $url) {
						// Mathed the webhook URL

						// Deleting the webhook
						/* YOOKASSA->removeWebhook($webhook->getId()); */
					} else {
						// Not matched the webhook URL

						// Creating the webhook
						YOOKASSA->addWebhook(['event' => yookassa_event::PAYMENT_SUCCEEDED, 'url' => $url . $urn]);
					}
				}
			}
		}
	}
}
