<?php

namespace kernel\app_modules\tgbot\controllers;

use app\modules\tgbot\models\Tgbot;
use JetBrains\PhpStorm\NoReturn;
use kernel\app_modules\card\models\forms\CreateCardForm;
use kernel\app_modules\card\services\CardService;
use kernel\helpers\Debug;
use kernel\modules\user\models\forms\CreateUserForm;
use kernel\modules\user\service\UserService;
use kernel\Request;
use kernel\RestController;
use kernel\services\TokenService;

class TgBotRestController extends RestController
{

    public function __construct()
    {
        $this->model = new Tgbot();
    }

    #[NoReturn] public function actionStore(): void
    {
        $request = new Request();
        $data = $request->post();

        $tgBot = $this->model->where("bot_id", $data['bot_id'])->where("dialog_id", $data['dialog_id'])->first();

        if (!$tgBot){
            foreach ($this->model->getFillable() as $item){
                $this->model->{$item} = $data[$item] ?? null;
            }

            $userService = new UserService();
            $userForm = new CreateUserForm();
            $username = $data['username'];
            $userForm->load([
                'username' => $username,
                'password' => TokenService::random_bytes(20),
                'email' => $username . "@hookahdnr.ru"
            ]);

            $user = $userService->create($userForm);
            if ($user) {
                $this->model->user_id = $user->id;
            }

            $this->model->save();

            $resArr = $tgBot->toArray();
            $resArr['has_card'] = CardService::userHasCard($resArr['user_id']);
            $this->renderApi($resArr);
        }
        $resArr = $tgBot->toArray();
        $resArr['has_card'] = CardService::userHasCard($resArr['user_id']);

        $this->renderApi($resArr);
    }

    #[NoReturn] public function actionCreateCard(): void
    {
        $cardService = new CardService();
        $request = new Request();
        $data = $request->post();
        $form = new CreateCardForm();
        $form->load($data);
        $form->setItem('payment_type', 2);
        $form->setItem('bank_id', 323);
        $form->setItem('info', 42);
        $form->setItem('program', 74);
        $form->setItem('cvc', 101);
        $form->setItem('pin', 1111);
        $form->setItem('status', 1);

        if ($form->validate()){
            $model = $cardService->create($form);

            $this->renderApi($model->load(['cardFile'])->toArray());
        }

        $this->renderApi([]);
    }

    #[NoReturn] public function actionGetByDialog(int $dialog_id, int $bot_id): void
    {
        $model = \kernel\app_modules\tgbot\models\Tgbot::where(['dialog_id' => $dialog_id, 'bot_id' => $bot_id])->first();
        if ($model) {
            $this->renderApi($model->toArray());
        }
        $this->renderApi([]);
    }

}