<?php

declare(strict_types=1);

namespace garden\campanula;

// Files of the project
use garden\campanula\models\account,
	garden\campanula\models\message,
	garden\campanula\models\telegram\middlewares,
	garden\campanula\models\telegram\commands,
	garden\campanula\models\telegram\settings;

// Library for languages support
use mirzaev\languages\language;

// Framework for PHP
use mirzaev\minimal\core,
	mirzaev\minimal\route;

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

// Baza database
use mirzaev\baza\database,
	mirzaev\baza\column,
	mirzaev\baza\record,
	mirzaev\baza\enumerations\encoding,
	mirzaev\baza\enumerations\type;

// The library for escaping all markdown symbols
use function mirzaev\unmarkdown;

// Framework for asynchronous PHP
use function React\Async\await;

// Built-in libraries
use pdo,
	pdoexception;

// Enabling debugging
/* ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1); */

// Initializing path to the public directory 
define('INDEX', __DIR__);

// Initializing path to the project root directory
define('ROOT',  INDEX . DIRECTORY_SEPARATOR	. '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR	. '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR);

// Initializing path to the directory of views 
define('VIEWS', INDEX . DIRECTORY_SEPARATOR	. '..' . DIRECTORY_SEPARATOR . 'views');

// Initializing path to the directory of settings 
define('SETTINGS', INDEX . DIRECTORY_SEPARATOR	. '..' . DIRECTORY_SEPARATOR . 'settings');

// Initializing system settings 
require SETTINGS . DIRECTORY_SEPARATOR . 'system.php';

// Initializing path to the directory of the storage 
define('STORAGE', INDEX . DIRECTORY_SEPARATOR	. '..' . DIRECTORY_SEPARATOR . 'storage');

// Initializing path to the databases directory
define('DATABASES', INDEX . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'databases');

// Initializing path to the localizations directory
define('LOCALIZATIONS', INDEX . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'localizations');

// Initiailizing Telegram chat-robot settings
require(SETTINGS . DIRECTORY_SEPARATOR . 'telegram.php');

// Initiailizing Gammu database connection data
require(SETTINGS . DIRECTORY_SEPARATOR . 'gammu.php');

// Initializing dependencies
require ROOT . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';

// Initializing the gammu database connection
$gammu = new pdo(GAMMU['type'] . ':dbname=' . GAMMU['database'] . ';host=' . GAMMU['server'], GAMMU['name'], GAMMU['password']);

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

// Initializing the robot
$robot = new Zanzara(ROBOT['key'], $config);

// Initializing the request
$request = $gammu->prepare('SELECT * FROM `' . GAMMU['table_inbox'] . '` WHERE `' . GAMMU['table_inbox'] . '`.`ReceivingDateTime` <= NOW() + interval 1 week ORDER BY `inbox`.`ReceivingDateTime` ASC');

// Initializing the request parameters
$parameters = [];

// Sending the request
$request->execute($parameters);

// Fetching the response
$response = (array) $request->fetchAll(pdo::FETCH_ASSOC);

foreach ($response as $message) {
	// Iterating over messages from last week

	// Searching for the message
	$model = new message()->read(filter: fn(record $record) => $record->sended === 1 && $record->identifier_gammu === (int) $message['ID']);

	if ($model instanceof message) {
		// The message was sent
	} else {
		// The message was not send

		// Initializing the message parameters
		$sender = unmarkdown($message['SenderNumber']);
		$date = unmarkdown($message['ReceivingDateTime']);
		$text = unmarkdown($message['TextDecoded']);

		// Sending the message
		await($robot->getTelegram()->sendMessage(
			<<<TXT
			$text

			**$sender**
			`$date`
			TXT,
			[
				'chat_id' => ROBOT['receiver'],
				'link_preview_options' => [
					'is_disabled' => true
				],
				'disable_notification' => false
			]
		)->then(function () use ($message, $sender, $date, $text) {
			// Sended the message

			// Initializing the model
			$model = new message();

			// Creating the message
			$model->write(
				identifier_gammu: $message['ID'],
				sender: $sender,
				date: $date,
				text: $text,
				sended: true
			);
		}));

		sleep(1);
	}
}
