<?php
declare(strict_types=1);

$pageTitle = 'Conta';
require_once __DIR__ . '/includes/header.php';

$db = gpc_db();
$self = basename($_SERVER['PHP_SELF']);
$adminId = (int) ($_SESSION['admin_id'] ?? 0);

$stmt = $db->prepare('SELECT id, username FROM admins WHERE id = :id LIMIT 1');
$stmt->execute([':id' => $adminId]);
$admin = $stmt->fetch();

if (!$admin) {
    gpc_logout();
    header('Location: index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && gpc_csrf_check($_POST['csrf'] ?? null)) {
    $username = trim((string) ($_POST['username'] ?? ''));
    $pass = (string) ($_POST['password'] ?? '');
    $pass2 = (string) ($_POST['password2'] ?? '');

    if ($username === '') {
        gpc_flash('bad', 'Informe o usuário.');
    } elseif (strlen($username) < 3) {
        gpc_flash('bad', 'O usuário precisa ter pelo menos 3 caracteres.');
    } elseif (preg_match('/\s/', $username)) {
        gpc_flash('bad', 'O usuário não pode conter espaços.');
    } else {
        $check = $db->prepare('SELECT id FROM admins WHERE username = :u AND id <> :id LIMIT 1');
        $check->execute([':u' => $username, ':id' => $adminId]);

        if ($check->fetch()) {
            gpc_flash('bad', 'Este usuário já está em uso.');
        } elseif ($pass !== '' || $pass2 !== '') {
            if (strlen($pass) < 6) {
                gpc_flash('bad', 'A senha precisa ter no mínimo 6 caracteres.');
            } elseif ($pass !== $pass2) {
                gpc_flash('bad', 'As senhas não conferem.');
            } else {
                $hash = password_hash($pass, PASSWORD_DEFAULT);
                $db->prepare('UPDATE admins SET username = :u, password = :p WHERE id = :id')
                    ->execute([':u' => $username, ':p' => $hash, ':id' => $adminId]);
                $_SESSION['admin_user'] = $username;
                gpc_flash('ok', 'Usuário e senha atualizados com sucesso.');
            }
        } else {
            $db->prepare('UPDATE admins SET username = :u WHERE id = :id')
                ->execute([':u' => $username, ':id' => $adminId]);
            $_SESSION['admin_user'] = $username;
            gpc_flash('ok', 'Usuário atualizado com sucesso.');
        }
    }

    header('Location: ' . $self);
    exit;
}

$csrf = gpc_csrf_token();
$currentUsername = (string) ($admin['username'] ?? gpc_admin_user());
?>

<div class="card">
    <div class="card-body">
        <form method="post" autocomplete="off">
            <input type="hidden" name="csrf" value="<?= gpc_h($csrf) ?>">
            <div class="form-grid" style="max-width:420px">
                <div class="field">
                    <label>Usuário do admin</label>
                    <input type="text" name="username" value="<?= gpc_h($currentUsername) ?>" required minlength="3" autocomplete="username">
                </div>
                <div class="field">
                    <label>Nova senha</label>
                    <input type="password" name="password" minlength="6" autocomplete="new-password" placeholder="Deixe em branco para manter a atual">
                </div>
                <div class="field">
                    <label>Confirmar nova senha</label>
                    <input type="password" name="password2" minlength="6" autocomplete="new-password" placeholder="Repita somente se for trocar a senha">
                </div>
            </div>
            <div class="form-actions">
                <button type="submit" class="btn"><i data-lucide="save"></i> Salvar alterações</button>
            </div>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
