<?php
require_once __DIR__ . '/includes/bootstrap.php';
require_admin();
$adminId = (int)$_SESSION['admin_id'];
$stmt = db()->prepare('SELECT * FROM admins WHERE id=?');
$stmt->execute([$adminId]);
$admin = $stmt->fetch();
if (!$admin) {
    session_destroy();
    redirect('index.php');
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    verify_csrf();
    $username = trim((string)($_POST['username'] ?? ''));
    $current = (string)($_POST['current_password'] ?? '');
    $newPassword = (string)($_POST['new_password'] ?? '');
    try {
        if ($username === '') {
            throw new RuntimeException('O usuário não pode ficar vazio.');
        }
        if (!password_verify($current, (string)$admin['password_hash'])) {
            throw new RuntimeException('A senha atual está incorreta.');
        }
        if ($newPassword !== '' && strlen($newPassword) < 8) {
            throw new RuntimeException('A nova senha deve ter pelo menos 8 caracteres.');
        }
        if ($newPassword !== '') {
            $update = db()->prepare('UPDATE admins SET username=?,password_hash=? WHERE id=?');
            $update->execute([$username, password_hash($newPassword, PASSWORD_DEFAULT), $adminId]);
        } else {
            $update = db()->prepare('UPDATE admins SET username=? WHERE id=?');
            $update->execute([$username, $adminId]);
        }
        flash('success', 'Credenciais administrativas atualizadas.');
        redirect('user.php');
    } catch (Throwable $e) {
        flash('error', strpos($e->getMessage(), 'UNIQUE') !== false ? 'Este nome de usuário já está em uso.' : $e->getMessage());
        redirect('user.php');
    }
}

$pageTitle = 'Meu Perfil';
$pageSubtitle = 'Atualize o usuário e a senha usados para acessar o painel administrativo.';
$pageIcon = 'fa-user-shield';
require __DIR__ . '/includes/header.php';
?>
<section class="panel-card" style="max-width:760px;margin-left:auto;margin-right:auto">
    <div class="panel-card-head"><div class="panel-card-icon"><i class="fa-solid fa-user-shield"></i></div><div><h2>Credenciais administrativas</h2><p>Por segurança, confirme a senha atual antes de salvar.</p></div></div>
    <form method="post">
        <input type="hidden" name="csrf" value="<?=e(csrf_token())?>">
        <div class="form-grid" style="grid-template-columns:1fr">
            <div class="form-field"><label for="username">Usuário</label><input id="username" name="username" value="<?=e($admin['username'])?>" required></div>
            <div class="form-field"><label for="current_password">Senha atual</label><input id="current_password" name="current_password" type="password" required></div>
            <div class="form-field"><label for="new_password">Nova senha</label><input id="new_password" name="new_password" type="password" minlength="8" placeholder="Deixe vazio para manter a atual"><small>Mínimo de 8 caracteres.</small></div>
        </div>
        <div class="form-actions" style="position:static;margin:0 20px 20px"><button class="button primary" type="submit"><i class="fa-solid fa-floppy-disk"></i> Atualizar perfil</button></div>
    </form>
</section>
<?php require __DIR__ . '/includes/footer.php'; ?>
