<?php

declare(strict_types=1);

namespace mirzaev\arming_bot\controllers;

// Files of the project
use mirzaev\arming_bot\views\templater,
	mirzaev\arming_bot\models\core as models,
	mirzaev\arming_bot\models\account,
	mirzaev\arming_bot\models\session,
	mirzaev\arming_bot\models\settings,
	mirzaev\arming_bot\models\suspension,
	mirzaev\arming_bot\models\enumerations\language;

// Framework for PHP
use mirzaev\minimal\controller;

/**
 * Core of controllers
 *
 * @package mirzaev\arming_bot\controllers
 * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
 */
class core extends controller
{
	/**
	 * Postfix for name of controllers files
	 */
	final public const string POSTFIX = '';

	/**
	 * Instance of the settings
	 */
	protected readonly settings $settings;

	/**
	 * Instance of a session
	 */
	protected readonly session $session;

	/**
	 * Instance of an account
	 */
	protected readonly ?account $account;

	/**
	 * Language
	 */
	protected language $language = language::en;

	/**
	 * Registry of errors
	 */
	protected array $errors = [
		'session' => [],
		'account' => []
	];

	/**
	 * Constructor of an instance
	 *
	 * @param bool $initialize Initialize a controller?
	 *
	 * @return void
	 *
	 * @todo settings account и session не имеют проверок на возврат null
	 */
	public function __construct(bool $initialize = true)
	{
		// Blocking requests from CloudFlare (better to write this blocking into nginx config file)
		if (isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] === 'nginx-ssl early hints') return;

		// For the extends system
		parent::__construct($initialize);

		if ($initialize) {
			// Initializing is requested

			// Initializing of models core (connect to ArangoDB...)
			new models(true);

			// Initializing of the date until which the session will be active
			$expires = strtotime('+1 week');

			// Initializing of default value of hash of the session
			$_COOKIE["session"] ??= null;

			// Initializing of a session
			$this->session = new session($_COOKIE["session"], $expires, $this->errors['session']);

			// Handle a problems with initializing a session
			if (!empty($this->errors['session'])) exit(1);

			// телеграм не сохраняет куки
			/* else if ($_COOKIE["session"] !== $this->session->hash) {
				// Hash of the session is changed (implies that the session has expired and recreated)

				// Write a new hash of the session to cookies
				setcookie(
					'session',
					$this->session->hash,
					[
						'expires' => $expires,
						'path' => '/',
						'secure' => true,
						'httponly' => true,
						'samesite' => 'strict'
					]
				);
			} */

			// Initializing of the account 
			$this->account = $this->session->account($this->errors['account']);

			// Initializing of the settings
			$this->settings = settings::active();

			// Initializing of language
			if ($this->account?->language) $this->language = $this->account->language ?? language::en->name;
			else if ($this->settings?->language) $this->language = $this->settings->language ?? language::en->name;

			// Initializing of preprocessor of views
			$this->view = new templater(
				session: $this->session,
				account: $this->account,
				settings: $this->settings
			);

			// @todo перенести в middleware

			// Search for suspensions                                                      
			$suspension = suspension::search();

			if ($suspension && $suspension->targets['web app']) {
				// Found a suspension                                              

				if ($this->account) {
					// Initialized account

					foreach ($suspension->access as $type => $status) {
						// Перебор статусов доступа                                                   

						if ($status && $this->account->{$type}) {
							// Authorized account                                                       

							// Exit (success)                                                           
							return $this;
						}
					}

					// Exit (success)
					goto suspension;
				} else {
					// Not initialized account     

					// Send the suspension page and exit (success)
					suspension:

					// Write title of the page to templater global variables
					$this->view->title = match ($this->language) {
						language::en => 'Suspended',
						language::ru => 'Приостановлено',
						default => 'Suspended'
					};

					// Write description of the suspension to templater global variables
					$this->view->description = $suspension->description[$this->language] ?? array_values($suspension->description)[0];

					// Write message of remaining time of the suspension to templater global variables
					$this->view->remain = [
						'title' => match ($this->language) {
							language::en => 'Time remaining: ',
							language::ru => 'Осталось времени: ',
							default => 'Time remaining: '
						},
						'value' => $suspension?->message()
					];

					// Send the suspension page                                                                                    
					echo $this->view->render('suspension/page.html');

					// Exit (success)                                                                                              
					exit(0);
				}
			}
		}
	}

	/**
	 * Check of initialization
	 *
	 * Checks whether a property is initialized in a document instance from ArangoDB
	 *
	 * @param string $name Name of the property from ArangoDB
	 *
	 * @return bool The property is initialized?
	 */
	public function __isset(string $name): bool
	{
		// Check of initialization of the property and exit (success)
		return match ($name) {
			default => isset($this->{$name})
		};
	}
}
