<?php

declare(strict_types=1);

namespace mirzaev\huesos;

// Files of the project
use mirzaev\huesos\controllers\core as controller,
	mirzaev\huesos\models\core as model,
	mirzaev\huesos\models\cart,
	mirzaev\huesos\models\telegram;

// Framework for Telegram
use Zanzara\Zanzara,
	Zanzara\Context,
	Zanzara\Config;

// Framework for ArangoDB
use mirzaev\arangodb\document;

ini_set('error_reporting', E_ALL ^ E_DEPRECATED);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

// Версия робота
define('ROBOT_VERSION', '1.0.0');

// Путь до настроек
define('SETTINGS', __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'settings');

// Путь до хранилища
define('STORAGE', __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'storage');

// Файл в формате xlsx с примером excel-документа для импорта каталога
define('CATALOG_EXAMPLE', STORAGE . DIRECTORY_SEPARATOR . 'example.xlsx');

// Файл в формате xlsx для импорта каталога
define('CATALOG_IMPORT', STORAGE . DIRECTORY_SEPARATOR . 'import.xlsx');

/**
 * Ключ чат-робота Telegram 
 * @deprecated
 */
define('KEY', require(SETTINGS . DIRECTORY_SEPARATOR . 'telegram.php'));
define('TELEGRAM_KEY', require(SETTINGS . DIRECTORY_SEPARATOR . 'telegram.php'));

// Initialize dependencies
require __DIR__ . DIRECTORY_SEPARATOR
	. '..' . DIRECTORY_SEPARATOR
	. '..' . DIRECTORY_SEPARATOR
	. '..' . DIRECTORY_SEPARATOR
	. '..' . DIRECTORY_SEPARATOR
	. 'vendor' . DIRECTORY_SEPARATOR
	. 'autoload.php';

// Инициализация ядра контроллеров MINIMAL
/* new controller(new core, false); */

// Инициализация ядра моделей MINIMAL
new model(true);

$config = new Config();
$config->setParseMode(Config::PARSE_MODE_MARKDOWN);
$config->useReactFileSystem(true);

$bot = new Zanzara(TELEGRAM_KEY, $config);

$bot->onUpdate(function (Context $ctx): void {
	// Initializing the message
	$message = $ctx->getMessage();

	// Initializing the "web app" data
	$app = $message?->getWebAppData();

	if (!empty($app)) {
		// Initialized the "web app" data

		// Initializing request from "web app" data
		$request = json_decode($app->getData(), false, 10);

		if ($request->type === 'cart_share') {
			// Cart attaching

			// Attaching cart to the Telegram account
			telegram::cart_attach($ctx, $request->hash);
		}
	} else {
		// Not initialized the "web app" data

		// Initializing account
		$account = $ctx->get('account');

		if ($account) {
			// Initialized the account

			if (!empty($message)) {
				// Initialized the message

				// Initializing the contact data
				$contact = $message?->getContact();

				if (!empty($contact)) {
					// Initialized the contact data

					// Sanitizing received SIM-number (only numbers)
					$sanitized = preg_replace('/[^\d]/', '', $contact->getPhoneNumber());

					if (!empty($sanitized)) {
						// Sanitized receiver SIM-number

						// Writing receiver SIM-number into the account
						$account->receiver = ['sim' => (int) $sanitized] + ($account->receiver ?? []);

						// Deabstracting the language parameter
						$account->language = $account->language->name;

						if (document::update($account->__document())) {
							// Writed the account instance into the ArangoDB document

							$ctx->sendMessage(
								<<<TXT
								✅ *SIM\-номер зарегистрирован:* $sanitized
								TXT,
								[
									'reply_markup' => [
										'remove_keyboard' => true
									]
								]
							)->then(function ($message) use ($ctx) {
								// Sended message

								// Sending the account parameters menu
								telegram::account_parameters($ctx);
							});
						} else {
							// Not writed the account instance into the ArangoDB document

							// Sending the message
							$ctx->sendMessage('⚠️ *Не удалось записать SIM\-номер*');
						}
					}
				}
			}
		}
	}

	unset($app);
});

$bot->onCommand('start', fn($ctx) => telegram::start($ctx));
$bot->onCommand('contacts', fn($ctx) => telegram::contacts($ctx));
$bot->onCommand('company', fn($ctx) => telegram::company($ctx));
$bot->onCommand('community', fn($ctx) => telegram::community($ctx));
$bot->onCommand('settings', fn($ctx) => telegram::settings($ctx));

$bot->onText('💬 Контакты', fn($ctx) => telegram::contacts($ctx));
$bot->onText('🏛️ О компании', fn($ctx) => telegram::company($ctx));
$bot->onText('🎯 Сообщество', fn($ctx) => telegram::community($ctx));
$bot->onText('⚙️  Настройки', fn($ctx) => telegram::settings($ctx));

$bot->onCbQueryData(['mail'], fn($ctx) => telegram::_mail($ctx));
$bot->onCbQueryData(['import_request'], fn($ctx) => telegram::import_request($ctx));
$bot->onCbQueryData(['order'], fn($ctx) => telegram::order($ctx));
$bot->onCbQueryData(['tuning'], fn($ctx) => telegram::tuning($ctx));
$bot->onCbQueryData(['brands'], fn($ctx) => telegram::brands($ctx));

$bot->onCbQueryData(['receiver_sim_choose'], fn($ctx) => telegram::receiver_sim_choose($ctx));
$bot->onCbQueryData(['receiver_sim_request'], fn($ctx) => telegram::receiver_sim_request($ctx));
$bot->onCbQueryData(['receiver_sim_input'], fn($ctx) => telegram::receiver_sim_input($ctx));
$bot->onCbQueryData(['receiver_sim_write'], fn($ctx) => telegram::receiver_sim_write($ctx));

$bot->onCbQueryData(['receiver_name_choose'], fn($ctx) => telegram::receiver_name_choose($ctx));
$bot->onCbQueryData(['receiver_name_request'], fn($ctx) => telegram::receiver_name_request($ctx));
$bot->onCbQueryData(['receiver_name_input'], fn($ctx) => telegram::receiver_name_input($ctx));
$bot->onCbQueryData(['receiver_name_write'], fn($ctx) => telegram::receiver_name_write($ctx));

$bot->onException(function (Context $ctx, $exception) {
	var_dump($exception);
});

// Инициализация middleware с обработкой аккаунта
$bot->middleware([telegram::class, "account"]);

// Инициализация middleware с обработкой технических работ разных уровней
$bot->middleware([telegram::class, "suspension"]);

// Запуск чат-робота
$bot->run();
