<?php

declare(strict_types=1);

namespace mirzaev\deeproots\models\telegram;

// Files of the project
use mirzaev\deeproots\models\core,
    mirzaev\deeproots\models\account,
    mirzaev\deeproots\models\question,
    mirzaev\deeproots\models\question\localization as question_localization,
    mirzaev\deeproots\models\answer,
    mirzaev\deeproots\models\telegram\processes\language\select as process_language_select,
    mirzaev\deeproots\models\enumerations\language;

// Framework for Telegram
use Zanzara\Context as context,
    Zanzara\Telegram\Type\Message as message,
    Zanzara\Telegram\Type\Input\InputFile as file_input;

// Baza database
use mirzaev\baza\record;

/**
 * Telegram commands
 *
 * @package mirzaev\deeproots\models\telegram
 *
 * @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
 * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
 */
final class commands extends core
{
    /**
     * Menu
     *
     * Responce for the commands: "/start", '/menu'
     *
     * @param context $context Request data from Telegram
     *
     * @return void
     */
    public static function menu(context $context): void
    {
        // Initializing the account
        $account = $context->get('account');

        if ($account instanceof record) {
            // Initialized the account

            // Initializing localization
            $localization = $context->get('localization');

            if ($localization) {
                // Initialized localization

                // Initializing the title
                $title = '📋 *' . $localization['menu_title'] . '*';

                // Sending the message
                $context->sendMessage(
                    <<<TXT
                    $title
                    TXT,
                    [
                        'reply_markup' => [
                            'inline_keyboard' => [
                                [
                                    [
                                        'text' => '🧠 ' . $localization['menu_button_start'],
                                        'callback_data' => 'projects'
                                    ]
                                ],
                                [
                                    [
                                        'text' => '📈 ' . $localization['menu_button_rating'],
                                        'callback_data' => 'rating'
                                    ],
                                    [
                                        'text' => '💰 ' . $localization['menu_button_balance'],
                                        'callback_data' => 'balance'
                                    ]
                                ]
                            ],
                            'disable_notification' => true,
                            'remove_keyboard' => true
                        ],
                    ]
                )->then(function (message $message) use ($context, $localization, $account) {
                    // Sended the message

                    if (
                        $account->authorized_system_accounts ||
                            $account->authorized_system_questions ||
                            $account->authorized_system_settings
                    ) {
                        // Found at least one system authorization

                        // Initializing the keyboard buffer
                        $keyboard = [];

                        if ($account->authorized_system_accounts) {
                            // Authorized to accounts

                            // Generating the button and writing into the keyboard buffer
                            $keyboard[] = [
                                [
                                    'text' => '🐣 ' . $localization['menu_button_system_accounts'],
                                    'callback_data' => 'system_accounts'
                                ]
                            ];
                        }

                        if ($account->authorized_system_questions) {
                            // Authorized to questions

                            // Generating the button and writing into the keyboard buffer
                            $keyboard[] = [
                                [
                                    'text' => '🗂 ' . $localization['menu_button_system_questions'],
                                    'callback_data' => 'system_questions'
                                ]
                            ];
                        }

                        if ($account->authorized_system_settings) {
                            // Authorized to system settings

                            // Generating the button and writing into the keyboard buffer
                            $keyboard[] = [
                                [
                                    'text' => '⚙️ ' . $localization['menu_button_system_settings'],
                                    'callback_data' => 'system_settings'
                                ]
                            ];
                        }

                        // Sending the message
                        $context->sendMessage(
                            '🛠 ' . $localization['menu_system_authorized'],
                            [
                                'reply_markup' => [
                                    'inline_keyboard' => $keyboard,
                                    'disable_notification' => true,
                                    'remove_keyboard' => true
                                ],
                            ]
                        );
                    }
                });
            } else {
                // Not initialized localization

                // Sending the message
                $context->sendMessage('⚠️ *Failed to initialize localization*')
                    ->then(function (message $message) use ($context) {
                        // Sended the message

                        // Ending the conversation process
                        $context->endConversation();
                    });
            }
        } else {
            // Not initialized the account

            // Sending the message
            $context->sendMessage('⚠️ *Failed to initialize the account*')
                ->then(function (message $message) use ($context) {
                    // Sended the message

                    // Ending the conversation process
                    $context->endConversation();
                });
        }
    }

    /**
     * Account
     *
     * Responce for the command: "/account"
     *
     * Sends information about account with menu
     *
     * @param context $context Request data from Telegram
     *
     * @return void
     */
    public static function account(context $context): void
    {
        // Initializing the telegram account
        $telegram = $context->get('telegram');

        if ($telegram instanceof record) {
            // Initialized the telegram account

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

            if ($account instanceof record) {
                // Initialized the account

                // Initializing localization
                $localization = $context->get('localization');

                if ($localization) {
                    // Initialized localization

                    // Initializing title for the message
                    $title = '🫵 ' . $localization['account_title'];

                    // Initializing the account identifier row for the message
                    $identifier = '*' . $localization['account_identifier'] . ":* $account->identifier \($telegram->identifier\)";

                    // Declaring buufer of rows about authorizations
                    $authorizations = '';

                    // Initializing rows about authorization
                    foreach ($account->values() as $key => $value) {
                        // Iterating over account parameters

                        if (str_starts_with($key, 'authorized_')) {
                            // Iterating over account authorizations

                            if (str_starts_with($key, 'authorized_system_') && $value) {
                                // A system authorization

                                // Writing into buffer of rows about authorizations
                                $authorizations .= '✅ ⚠️ *' . ($localization["account_$key"] ?? $key) . ':* ' . $localization['yes'] . "\n";
                            } else {
                                // Not a system authorization

                                // Writing into buffer of rows about authorizations
                                $authorizations .= ($value ? '✅' : '❎') . ' *' . ($localization["account_$key"] ?? $key) . ':* ' . ($value ? $localization['yes'] : $localization['no']) . "\n";
                            }
                        }
                    }

                    // Trimming the last line break character
                    $authorizations = trim($authorizations, "\n");

                    // Sending the message
                    $context->sendMessage(
                        <<<TXT
                        $title

                        $identifier

                        $authorizations
                        TXT
                    );
                } else {
                    // Not initialized localization

                    // Sending the message
                    $context->sendMessage('⚠️ *Failed to initialize localization*')
                        ->then(function (message $message) use ($context) {
                            // Sended the message

                            // Ending the conversation process
                            $context->endConversation();
                        });
                }
            } else {
                // Not initialized the account

                // Sending the message
                $context->sendMessage('⚠️ *Failed to initialize the account*')
                    ->then(function (message $message) use ($context) {
                        // Sended the message

                        // Ending the conversation process
                        $context->endConversation();
                    });
            }
        } else {
            // Not initialized the telegram account

            // Sending the message
            $context->sendMessage('⚠️ *Failed to initialize the telegram account*')
                ->then(function (message $message) use ($context) {
                    // Sended the message

                    // Ending the conversation process
                    $context->endConversation();
                });
        }
    }

    /**
     * Language
     *
     * Responce for the command: "/language"
     *
     * Send the language selection menu
     *
     * @param context $context Request data from Telegram
     *
     * @return void
     */
    public static function language(context $context): void
    {
        // Initializing the account
        $account = $context->get('account');

        if ($account instanceof record) {
            // Initialized the account

            // Initializing language
            $language = $context->get('language');

            if ($language instanceof language) {
                // Initialized language

                // Initializing localization
                $localization = $context->get('localization');

                if ($localization) {
                    // Initialized localization

                    // Sending the language selection
                    process_language_select::menu(
                        context: $context,
                        prefix: 'settings_language_',
                        title: '🌏 *' . $localization['settings_select_language_title'] . '*',
                        description: '🌏 *' . $localization['settings_select_language_description'] . '*'
                    );
                } else {
                    // Not initialized localization

                    // Sending the message
                    $context->sendMessage('⚠️ *Failed to initialize localization*')
                        ->then(function (message $message) use ($context) {
                            // Sended the message

                            // Ending the conversation process
                            $context->endConversation();
                        });
                }
            } else {
                // Not initialized language

                // Sending the message
                $context->sendMessage('⚠️ *Failed to initialize language*')
                    ->then(function (message $message) use ($context) {
                        // Sended the message

                        // Ending the conversation process
                        $context->endConversation();
                    });
            }
        } else {
            // Not initialized the account

            // Sending the message
            $context->sendMessage('⚠️ *Failed to initialize the account*')
                ->then(function (message $message) use ($context) {
                    // Sended the message

                    // Ending the conversation process
                    $context->endConversation();
                });
        }
    }

    /**
     * Repository
     *
     * Responce for the command: "/repository"
     *
     * Sends information about project and menu
     *
     * @param context $context Request data from Telegram
     *
     * @return void
     */
    public static function repository(context $context): void
    {
        // Initializing the account
        $account = $context->get('account');

        if ($account instanceof record) {
            // Initialized the account

            // Initializing localization
            $localization = $context->get('localization');

            if ($localization) {
                // Initialized localization

                // Initializing title of the message
                $title = '🏛️ ' . $localization['repository_title'];

                // Sending the message
                $context->sendMessage($title . "\n\n" . $localization['repository_text'], [
                    'reply_markup' => [
                        'inline_keyboard' => [
                            [
                                [
                                    'text' => '🏛️ ' . $localization['repository_button_code'],
                                    'url' => 'https://git.mirzaev.sexy/mirzaev/deeproots'
                                ]
                            ],
                            [
                                [
                                    'text' => '⚠️  ' . $localization['repository_button_issues'],
                                    'url' => 'https://git.mirzaev.sexy/mirzaev/deeproots/issues'
                                ],
                                [
                                    'text' => '🌱  ' . $localization['repository_button_suggestions'],
                                    'url' => 'https://git.mirzaev.sexy/mirzaev/deeproots/issues'
                                ]
                            ]
                        ],
                        'remove_keyboard' => true,
                        'disable_notification' => true
                    ],
                    'link_preview_options' => [
                        'is_disabled' => true
                    ]
                ]);
            } else {
                // Not initialized localization

                // Sending the message
                $context->sendMessage('⚠️ *Failed to initialize localization*')
                    ->then(function (message $message) use ($context) {
                        // Ending the conversation process
                        $context->endConversation();
                    });
            }
        } else {
            // Not initialized the account

            // Sending the message
            $context->sendMessage('⚠️ *Failed to initialize the account*')
                ->then(function (message $message) use ($context) {
                    // Ending the conversation process
                    $context->endConversation();
                });
        }
    }

    /**
     * Author
     *
     * Responce for the command: "/author"
     *
     * Sends
     *
     * @param context $context Request data from Telegram
     *
     * @return void
     */
    public static function author(context $context): void
    {
        // Initializing the account
        $account = $context->get('account');

        if ($account instanceof record) {
            // Initialized the account

            // Initializing localization
            $localization = $context->get('localization');

            if ($localization) {
                // Initialized localization

                // Initializing title of the message
                $title = '👽 ' . $localization['author_title'];

                // Sending the message
                $context->sendMessage($title . "\n\n" . $localization['author_text'], [
                    'reply_markup' => [
                        'inline_keyboard' => [
                            [
                                [
                                    'text' => '📚 ' . $localization['author_button_neurojournal'],
                                    'url' => 'https://mirzaev.sexy'
                                ],
                                [
                                    'text' => '🤟 ' . $localization['author_button_projects'],
                                    'url' => 'https://git.svoboda.works/mirzaev?tab=activity'
                                ]
                            ],
                            [
                                [
                                    'text' => '✖️  ' . $localization['author_button_twitter'],
                                    'url' => 'https://x.com/mirzaev_sexy'
                                ],
                                [
                                    'text' => '🦋 ' . $localization['author_button_bluesky'],
                                    'url' => 'https://bsky.app/profile/mirzaev.bsky.social'
                                ],
                                [
                                    'text' => '⛓️ ' . $localization['author_button_bastyon'],
                                    'url' => 'https://bsky.app/profile/mirzaev.bsky.social'
                                ]
                            ],
                            [
                                [
                                    'text' => '🇺🇸 ' . $localization['author_button_youtube_english'],
                                    'url' => 'https://www.youtube.com/@MIRZAEV'
                                ],
                                [
                                    'text' => '🇷🇺 ' . $localization['author_button_youtube_russian'],
                                    'url' => 'https://www.youtube.com/@MIRZAEV'
                                ]
                            ],
                            [
                                [
                                    'text' => '✉️ ' . $localization['author_button_message'],
                                    'url' => 'https://t.me/mirzaev_sexy'
                                ]
                            ]
                        ],
                        'remove_keyboard' => true,
                        'disable_notification' => true
                    ],
                    'link_preview_options' => [
                        'is_disabled' => true
                    ]
                ]);
            } else {
                // Not initialized localization

                // Sending the message
                $context->sendMessage('⚠️ *Failed to initialize localization*')
                    ->then(function (message $message) use ($context) {
                        // Ending the conversation process
                        $context->endConversation();
                    });
            }
        } else {
            // Not initialized the account

            // Sending the message
            $context->sendMessage('⚠️ *Failed to initialize the account*')
                ->then(function (message $message) use ($context) {
                    // Ending the conversation process
                    $context->endConversation();
                });
        }
    }

    /**
     * Society
     *
     * Responce for the command: "/society"
     *
     * Sends the "mushroom" image and the localized text "why so shroomious"
     *
     * @param context $context Request data from Telegram
     *
     * @return void
     */
    public static function society(context $context): void
    {
        // Initializing the account
        $account = $context->get('account');

        if ($account instanceof record) {
            // Initialized the account

            // Initializing localization
            $localization = $context->get('localization');

            if ($localization) {
                // Initialized localization

                // Sending the message
                $context->sendPhoto(
                    new file_input(STORAGE . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'mushroom.jpg'),
                    [
                        'caption' => $localization['why_so_shroomious'],
                        'disable_notification' => true
                    ]
                );
            } else {
                // Not initialized localization

                // Sending the message
                $context->sendMessage('⚠️ *Failed to initialize localization*')
                    ->then(function (message $message) use ($context) {
                        // Sended the message

                        // Ending the conversation process
                        $context->endConversation();
                    });
            }
        } else {
            // Not initialized the account

            // Sending the message
            $context->sendMessage('⚠️ *Failed to initialize the account*')
                ->then(function (message $message) use ($context) {
                    // Sended the message

                    // Ending the conversation process
                    $context->endConversation();
                });
        }
    }

    /**
     * Questions (system)
     *
     * Sends questions. answers and localizations management menu
     *
     * @param context $context Request data from Telegram
     *
     * @return void
     */
    public static function system_questions(context $context): void
    {
        // Initializing the account
        $account = $context->get('account');

        if ($account instanceof record) {
            // Initialized the account

            // Initializing localization
            $localization = $context->get('localization');

            if ($localization) {
                // Initialized localization

                // Initializing the question model
                $model_question = new question();

                // Counting questions
                $questions = $model_question->database->count();

                // Initializing the answer model
                $model_answer = new answer();

                // Counting answers
                $answers = $model_answer->database->count();

                // Declaring the localizations amounts buffer
                $localizations = [];

                // Declaring the questions list
                $list = '';

                foreach (language::cases() as $case) {
                    // Iterating over language

                    // Initializing the localization model by the language
                    $model_question_localization = new question_localization(language: $case);

                    // Counting localizations for the language
                    $amount = $model_question_localization->database->count();

                    // Writing into the localizations amounts buffer
                    $localizations[] = $amount;

                    // Writing into the questions list
                    $list .= PHP_EOL . $case->flag() . ' *' . $case->label(language::{$account->language ?? LANGUAGE_DEFAULT} ?? language::{LANGUAGE_DEFAULT}) . ':* ' . $amount;
                }

                // Deinitializing unnecessary variables
                unset($case, $model_question, $model_question_localization, $model_answer, $amount);

                // Searching for unique values in uhe buffer of questions localizations amounts
                $uniques = array_unique($localizations, SORT_REGULAR);

                // Is questions amounts matches?
                $matches = count($uniques) === 1;

                // Sending the message
                $context->sendMessage(
                    sprintf(
                        <<<TXT
                        🗂 *%s*

                        📄 *%s:* %u
                        🔏 *%s:* %u
                        %s

                        %s
                        %s
                        %s
                        TXT,
                        $localization['system_questions_title'],
                        $localization['system_questions_questions'],
                        $questions,
                        $localization['system_questions_answers'],
                        $answers,
                        $list,
                        $answers === $questions ? '💯 ' . $localization['system_questions_answers_amount_matches'] : '⚠️ ' . $localization['system_questions_answers_amount_different'],
                        $matches && $questions === $uniques[0] ? '💯 ' . $localization['system_questions_amount_matches'] : '⚠️ ' . $localization['system_questions_amount_different'],
                        $matches ? '💯 ' . $localization['system_questions_localizations_amount_matches'] : '⚠️ ' . $localization['system_questions_localizations_amount_different']
                    ),
                    [
                        'reply_markup' => [
                            'inline_keyboard' => [
                                [
                                    [
                                        'text' => '🔍 ' . $localization['system_questions_button_search'],
                                        'callback_data' => 'system_questions_search'
                                    ],
                                    [
                                        'text' => '✏️ ' . $localization['system_questions_button_create'],
                                        'callback_data' => 'system_questions_create'
                                    ]
                                ]
                            ],
                            'remove_keyboard' => true,
                            'disable_notification' => true
                        ],
                        'link_preview_options' => [
                            'is_disabled' => true
                        ]
                    ]
                );
            } else {
                // Not initialized localization

                // Sending the message
                $context->sendMessage('⚠️ *Failed to initialize localization*')
                    ->then(function (message $message) use ($context) {
                        // Sended the message

                        // Ending the conversation process
                        $context->endConversation();
                    });
            }
        } else {
            // Not initialized the account

            // Sending the message
            $context->sendMessage('⚠️ *Failed to initialize the account*')
                ->then(function (message $message) use ($context) {
                    // Sended the message

                    // Ending the conversation process
                    $context->endConversation();
                });
        }
    }
}
