<?php

use Core\{Config, Database, Db};
use User\UserIp;

if (!defined('GAME_VERSION')) {
    require_once '_incl_data/autoload.php';
}

$step = 1;
$error = '';
Config::init();
Database::init();

if (isset($_GET['login'])) {
    $_POST['relogin'] = $_GET['login'];
}

if (isset($_POST['relogin'])) {
    $_POST['relogin'] = htmlspecialchars($_POST['relogin'], null);

    $u = User::start();

    $usr = Db::getRow('select * from users where login =?', [$_POST['relogin']]);
    if (!isset($usr['id'])) {
        $error = 'Логин "' . htmlspecialchars($_POST['relogin'], null) . '" не найден в базе.';
    } else {
        if ($usr['admin'] != 0 || $usr['banned'] != 0) {
            $error = 'Персонаж "' . $_POST['relogin'] . '" заблокирован!';
        } else {
            $step = 2;
            if (isset($_POST['redate'])) {
                //Третий шаг
                $lst_psw = Db::getValue(
                    'select count(*) from repass where uid = ? and time > unix_timestamp() - 24 * 60 * 60 and type = 1',
                    [$usr['id']]
                );
                if ($lst_psw) {
                    $error = 'Высылать пароль можно не более одного раза в сутки.';
                } elseif (
                    str_replace('0', '', date('d.m.Y', strtotime($_POST['redate']))) == str_replace('0', '', $usr['bithday'])
                ) {
                    $re = Db::getValue(
                        'select count(*) from logs_auth where uid = ? and type = 0 and depass != ?',
                        [$usr['id'], '']
                    );

                    if ($usr['securetime'] < Config::get('securetime')) {
                        unset($re);
                    }
                    if (!empty($re)) {
                        $newPassword = PassGen::new();
                        $title = 'Восстановление пароля от "' . $usr['login'] . '".';
                        $txt = 'Добрый день.<br>';
                        $txt .= 'С IP-адреса - <b>' . UserIp::get() . '</b>, был запрошен пароль для вашего персонажа.<br>Если это не Вы, просто удалите это письмо.<br><br>';
                        $txt .= 'Ваш логин: <b>' . $usr['login'] . '</b><br>';
                        $txt .= 'Ваш пароль: ' . $newPassword . '<br><br>';
                        $txt .= 'Отвечать на данное письмо не нужно.<br><br>';
                        $txt .= 'С уважением,<br>';
                        $txt .= 'Администрация Бойцовского Клуба';
                        $mail = Helper\Mail::send($usr['mail'], $txt, $title);

                        if ($mail === 1) {
                            Db::sql(
                                'update users set securetime = unix_timestamp(), pass = ? where id = ?',
                                [password_hash($newPassword, PASSWORD_DEFAULT), $usr['id']]
                            );
                            Db::sql(
                                'insert into repass (uid, time, ip, type) values (?,unix_timestamp(),?,1)',
                                [$usr['id'], UserIp::get()]
                            );
                            $step = 3;
                        } else {
                            $error = $mail;
                        }
                        unset($mail);
                        $error = '<br><br><br>Пароль от персонажа &quot;' . $usr['login'] . '&quot; был успешно выслан на E-mail указанный при регистрации! <br><br><br>';
                    }
                } else {
                    $error = 'Неверно указан день рождения.';
                }
            }
        }
    }
}

?>
<!DOCTYPE html>
<html lang="ru-RU">
<head>
    <title><?= Config::get('name') ?>: Восстановление пароля от персонажа</title>
    <meta name="keywords" content="<?= Config::get('keys') ?>">
    <meta name="description" content="<?= Config::get('desc') ?>"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <link type="text/css" rel="stylesheet" href="stylen.css"/>
    <style>
        input[type=text], input[type=date] {
            padding: 3px;
        }

        div.content, div.after {
            display: flex;
            justify-content: center;
        }

        div.content {
            align-items: center;
            flex-direction: column;
            height: 50%;
        }
    </style>
</head>
<body>
<form method="post" id="repass"></form>
<div class="content">
    <h1>Восстановление пароля</h1>
    <?= $error ? '<b style="color: red">' . $error . '</b>' : '' ?>
    <?php if ($step === 1): ?>
        <label for="relogin">Укажите логин персонажа:</label>
        <input form="repass" placeholder="Логин" maxlength="30" name="relogin" type="text" class="inup" id="relogin">
        <br>
        <input form="repass" type="submit" class="btn" value="Перейти к следующему шагу">
    <?php elseif ($step === 2): ?>
        <label for="relogin">Логин персонажа:</label>
        <input form="repass" maxlength="30" name="relogin" type="text" class="inup" value="<?= $_POST['relogin'] ?>" id="relogin">
        <br>
        <label for="redate">День рождения:</label>
        <input form="repass" name="redate" type="date" class="inup" id="redate"><br>
        <small class="testro">(день рождения вы указывали при регистрации персонажа в формате
            dd.mm.yyyy)</small><br>
        <input form="repass" type="submit" class="btn" value="Выслать пароль на E-mail">
    <?php endif; ?>
</div>
<div class="after">
    <a href="<?= Config::get('https') ?>">Вернутся на главную страницу</a>
</div>
<div class="after">
    <span class="testro"><?= Config::get('footer') ?></span>
</div>
</body>
</html>