<?php

namespace KupShop\ApiBundle\View;

use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Util\System\TokenGenerator;
use KupShop\KupShopBundle\Views\View;
use Query\Operator;

class UserSettingsView extends View
{
    protected $template = 'api/userSettings.tpl';

    public $requirements = [
        'modules' => [
            'eshop_users' => true,
            'api' => true,
        ],
        'logged_user' => true,
    ];

    public function __construct(
        private UserContext $userContext,
        private TokenGenerator $tokenGenerator,
    ) {
    }

    private function getUser(): ?\User
    {
        $user = $this->userContext->getActive();
        if (!$user) {
            return null;
        }

        return $user;
    }

    public function getTitle()
    {
        return translate('title', 'user.api');
    }

    public function getBodyVariables()
    {
        $vars = parent::getBodyVariables();

        $vars['user'] = $this->getUser();

        return $vars;
    }

    public function handleChangeApiPassword(): void
    {
        if (!($user = $this->getUser())) {
            return;
        }

        sqlQueryBuilder()
            ->update('users')
            ->directValues(
                [
                    'api_password' => $this->tokenGenerator->generate(20),
                ]
            )
            ->where(Operator::equals(['id' => $user->id]))
            ->execute();
    }
}
