<?php

namespace Shm\ShmAdmin\AdminRPC;

use Shm\Shm;
use Shm\ShmAdmin\AdminPanel;
use Shm\ShmAdmin\SchemaCollections\SubAccountsSchema;
use Shm\ShmAdmin\Types\BaseStructureType;
use Shm\ShmAuth\Auth;
use Shm\ShmIntegrations\TBankNominal\TBankCollections\TNominalBankDetails;
use Shm\ShmIntegrations\TBankNominal\TBankCollections\TNominalCompanies;
use Shm\ShmRPC\ShmRPC;
use Shm\ShmTypes\CompositeTypes\BalanceTypes\BalanceUtils;

class AdminRPCProfile
{
    public static function rpc()
    {

        return ShmRPC::lazy(function () {

            return [
                "type" => Shm::structure([

                    'structure' => BaseStructureType::get(),
                    'data' => Shm::mixed(),
                    'changePassword' => Shm::boolean(),
                    'subAccount' => Shm::boolean(),


                    "alerts" => Shm::arrayOf(Shm::structure([
                        "type" => Shm::enum([
                            "error" => Shm::string(),
                            "warning" => Shm::string(),
                            "info" => Shm::string(),
                            "success" => Shm::string(),
                        ]),
                        "title" => Shm::string(),
                        "message" => Shm::string(),
                        "navigate" => Shm::enum([
                            "tCompany",
                            "tCompanyBank",
                            "profile",
                            "openLink",
                        ]),
                        "link" => Shm::string(),
                    ])->staticBaseTypeName("ProfileAlert")),

                    'canAddTCompanyData' => Shm::boolean(),


                    'tCompanyData' => TNominalCompanies::structure(),
                    'tCompanyBankData' => TNominalBankDetails::structure(),
                    'tCompanyStructure' => BaseStructureType::get(),
                    'tCompanyBankStructure' => BaseStructureType::get(),



                    'balances' => Shm::arrayOf(Shm::structure([
                        'field' => BaseStructureType::get(),
                        'path' => Shm::string(),
                    ])),
                ]),

                'resolve' => function ($root, $args) {


                    Auth::authenticateOrThrow(...AdminPanel::$authStructures);


                    if (Auth::subAccountAuth()) {

                        $findStructure = SubAccountsSchema::baseStructure();
                    } else {

                        $findStructure = null;


                        foreach (AdminPanel::$authStructures as $user) {

                            if ($user->collection == Auth::getAuthCollection()) {
                                $findStructure = $user;
                                break;
                            }
                        }
                    }
                    if (!$findStructure) {
                        ShmRPC::error(\Shm\ShmUtils\I18n::get('access_denied'));
                    }


                    $passwordField =  $findStructure->findItemByType(Shm::password());

                    if ($passwordField)
                        $findStructure->items[$passwordField->key]->inAdmin(false);


                    $emailField = $findStructure->findItemByType(Shm::email());
                    $loginField = $findStructure->findItemByType(Shm::login());
                    $phoneField = $findStructure->findItemByType(Shm::phone());


                    if ($emailField) {
                        $findStructure->items[$emailField->key]->editable(false)->setCol(24);
                    }
                    if ($loginField) {
                        $findStructure->items[$loginField->key]->editable(false)->setCol(24);
                    }
                    if ($phoneField) {
                        $findStructure->items[$phoneField->key]->editable(false)->setCol(24);
                    }

                    $balances = [];
                    foreach (BalanceUtils::ALLOWED_CURRENCIES as $currency) {

                        $field = $findStructure->findBalanceFieldByCurrency($currency);

                        if ($field) {

                            $balances[] = [
                                'field' => $field->json(),
                                'path' => $field->getPathString(),
                            ];
                        }
                    }


                    $tCompanyData = null;
                    $tCompanyStructure = null;
                    $tCompanyBankData = null;
                    $tCompanyBankStructure = null;

                    $alerts = [];

                    if ($findStructure->canAddTCompanyData) {
                        $tCompanyData = TNominalCompanies::structure()->findOne([
                            'owner' => Auth::getAuthID(),
                            'ownerCollection' =>  Auth::getAuthCollection(),
                        ]);

                        if (!$tCompanyData) {



                            $tCompanyInsert = TNominalCompanies::structure()->insertOne([
                                'owner' => Auth::getAuthID(),
                                'ownerCollection' =>  Auth::getAuthCollection(),
                            ]);
                            $tCompanyData =  TNominalCompanies::structure()->findOne([
                                '_id' => $tCompanyInsert->getInsertedId(),
                            ]);
                        }


                        if ($tCompanyData['status'] == 'draft') {

                            $alerts[] = [
                                "type" => "info",
                                "title" => "Заполните информацию о компании",
                                "message" => "Заполните информацию о компании и отправьте на проверку",
                                "navigate" => "tCompany",
                            ];
                        }


                        $tCompanyBankData = TNominalBankDetails::structure()->findOne([
                            'owner' => Auth::getAuthID(),
                            'ownerCollection' =>  Auth::getAuthCollection(),
                        ]);
                        if (!$tCompanyBankData) {
                            $tCompanyBankDataInsert = TNominalBankDetails::structure()->insertOne([
                                'owner' => Auth::getAuthID(),
                                'ownerCollection' =>  Auth::getAuthCollection(),
                            ]);
                            $tCompanyBankData =  TNominalBankDetails::structure()->findOne([
                                '_id' => $tCompanyBankDataInsert->getInsertedId(),
                            ]);
                        }

                        if ($tCompanyBankData['status'] == 'draft') {
                            $alerts[] = [
                                "type" => "info",
                                "title" => "Заполните реквизиты банка",
                                "message" => "Заполните реквизиты банка вашей компании и отправьте на проверку",
                                "navigate" => "tCompanyBank",
                            ];
                        }

                        $tCompanyStructure = TNominalCompanies::structure()->json();
                        $tCompanyBankStructure = TNominalBankDetails::structure()->json();
                    }

                    return [
                        'structure' => $findStructure->json(),
                        'data' => $findStructure->removeOtherItems($findStructure->normalize($findStructure->findOne([
                            '_id' => Auth::subAccountAuth() ? Auth::getSubAccountID() :  Auth::getAuthID()
                        ]))),

                        'alerts' => $alerts,
                        'subAccount' => Auth::subAccountAuth(),
                        'tCompanyData' => $tCompanyData,
                        'tCompanyBankData' => $tCompanyBankData,
                        'canAddTCompanyData' => $findStructure->canAddTCompanyData,
                        'tCompanyStructure' => $tCompanyStructure,
                        'tCompanyBankStructure' => $tCompanyBankStructure,
                        'balances' =>  Auth::subAccountAuth() ? [] : $balances,
                        'changePassword' => $passwordField ? true : false,
                    ];
                }
            ];
        });
    }
}