<?php
require_once 'db.php';
if (empty($_SESSION['user_id']) || !is_admin($_SESSION['user_id'])) {
echo 'Доступ только для администратора.';
exit;
}
$errors = [];
$success = [];
/* ====== ДЕЙСТВИЯ С ПОЛЬЗОВАТЕЛЯМИ ====== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? '';
// бан / разбан / удаление
if (in_array($action, ['ban_user','unban_user','delete_user'], true)) {
$user_id = (int)($_POST['user_id'] ?? 0);
if ($user_id <= 0) {
$errors[] = 'Некорректный ID пользователя.';
} else {
if ($action === 'ban_user') {
$stmt = $mysqli->prepare("UPDATE users SET is_banned = 1 WHERE id = ?");
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->close();
$success[] = "Пользователь #$user_id заблокирован.";
} elseif ($action === 'unban_user') {
$stmt = $mysqli->prepare("UPDATE users SET is_banned = 0 WHERE id = ?");
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->close();
$success[] = "Пользователь #$user_id разблокирован.";
} elseif ($action === 'delete_user') {
$stmt = $mysqli->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->close();
$success[] = "Пользователь #$user_id удалён.";
}
}
}
/* ====== ДОБАВЛЕНИЕ КАТЕГОРИИ ПОДАРКОВ ====== */
if ($action === 'add_category') {
$name = trim($_POST['category_name'] ?? '');
if ($name === '') {
$errors[] = 'Название категории не может быть пустым.';
} else {
$stmt = $mysqli->prepare("INSERT INTO gift_categories (name) VALUES (?)");
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->close();
$success[] = 'Категория подарков добавлена.';
}
}
/* ====== ДОБАВЛЕНИЕ ПОДАРКА ====== */
if ($action === 'add_gift') {
$title = trim($_POST['gift_title'] ?? '');
$category_id = (int)($_POST['gift_category_id'] ?? 0);
if ($title === '') {
$errors[] = 'Название подарка не может быть пустым.';
}
if ($category_id <= 0) {
$errors[] = 'Выберите категорию подарка.';
}
$image_file = null;
if (!empty($_FILES['gift_image']['name']) && $_FILES['gift_image']['error'] === UPLOAD_ERR_OK) {
$ext = strtolower(pathinfo($_FILES['gift_image']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
$errors[] = 'Недопустимый формат изображения подарка.';
} else {
$image_file = 'gift_' . time() . '_' . mt_rand(1000,9999) . '.' . $ext;
$target = __DIR__ . '/assets/gifts/' . $image_file;
if (!move_uploaded_file($_FILES['gift_image']['tmp_name'], $target)) {
$errors[] = 'Не удалось сохранить файл подарка.';
$image_file = null;
}
}
} else {
$errors[] = 'Загрузите изображение подарка.';
}
if (!$errors && $image_file) {
$stmt = $mysqli->prepare("INSERT INTO gifts (category_id, title, image) VALUES (?, ?, ?)");
$stmt->bind_param('iss', $category_id, $title, $image_file);
$stmt->execute();
$stmt->close();
$success[] = 'Подарок добавлен.';
}
}
}
/* ====== ЗАГРУЖАЕМ ДАННЫЕ ДЛЯ ОТОБРАЖЕНИЯ ====== */
/* пользователи */
$users = $mysqli->query("
SELECT id, email, name, is_banned, created_at
FROM users
ORDER BY created_at DESC
LIMIT 200
");
/* категории подарков */
$categories = [];
$res = $mysqli->query("SELECT id, name FROM gift_categories ORDER BY name ASC");
while ($row = $res->fetch_assoc()) {
$categories[] = $row;
}
$res->close();
/* подарки по категориям */
$gifts_by_cat = [];
$res = $mysqli->query("
SELECT g.id, g.title, g.image, c.name AS category_name, g.category_id
FROM gifts g
JOIN gift_categories c ON c.id = g.category_id
ORDER BY c.name, g.title
");
while ($row = $res->fetch_assoc()) {
$gifts_by_cat[$row['category_id']]['category_name'] = $row['category_name'];
$gifts_by_cat[$row['category_id']]['items'][] = $row;
}
$res->close();
include 'header.php';
?>
<style>
.admin-page {
margin-top: 18px;
}
.admin-sections {
display: grid;
grid-template-columns: minmax(0, 1.6fr) minmax(0, 1.4fr);
gap: 20px;
}
.admin-card {
background: #ffffff;
border-radius: 22px;
padding: 18px 20px;
box-shadow: 0 10px 30px rgba(0,0,0,0.08);
margin-bottom: 18px;
}
.admin-card h2 {
margin-top: 0;
margin-bottom: 10px;
font-size: 19px;
}
.user-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.user-table th,
.user-table td {
padding: 6px 6px;
border-bottom: 1px solid rgba(0,0,0,0.04);
}
.user-table th {
text-align: left;
font-weight: 600;
}
.user-badge-banned {
display: inline-block;
padding: 2px 8px;
border-radius: 999px;
background: #ffe0e5;
color: #c53d4d;
font-size: 11px;
}
/* формы подарков */
.form-row {
margin-bottom: 10px;
}
.form-row label {
display: block;
font-size: 13px;
margin-bottom: 4px;
}
.form-row input[type="text"],
.form-row select,
.form-row input[type="file"] {
width: 100%;
box-sizing: border-box;
}
.gifts-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(90px, 1fr));
gap: 8px;
}
.gift-item {
text-align: center;
font-size: 12px;
}
.gift-img {
width: 80px;
height: 80px;
object-fit: contain;
border-radius: 16px;
background: #fff7fb;
box-shadow: 0 4px 14px rgba(0,0,0,0.06);
margin-bottom: 4px;
}
.gift-cat-title {
font-weight: 600;
margin-top: 12px;
margin-bottom: 4px;
}
/* адаптив */
@media (max-width: 900px) {
.admin-sections {
grid-template-columns: 1fr;
}
}
</style>
<div class="admin-page">
<h1>Админ-панель SoftLove</h1>
<?php if ($success): ?>
<div class="alert alert-success">
<?php foreach ($success as $msg): ?>
<p><?= htmlspecialchars($msg) ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($errors): ?>
<div class="alert alert-error">
<?php foreach ($errors as $e): ?>
<p><?= htmlspecialchars($e) ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<div class="admin-sections">
<!-- БЛОК ПОЛЬЗОВАТЕЛЕЙ -->
<section class="admin-card">
<h2>Пользователи</h2>
<div style="font-size:12px;color:#7b7287;margin-bottom:6px;">
Последние 200 пользователей. Можно забанить, разбанить или удалить.
</div>
<div style="overflow-x:auto;">
<table class="user-table">
<thead>
<tr>
<th>ID</th>
<th>Имя / Email</th>
<th>Регистрация</th>
<th>Статус</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
<?php while ($u = $users->fetch_assoc()): ?>
<tr>
<td><?= (int)$u['id'] ?></td>
<td>
<div><?= htmlspecialchars($u['name'] ?: 'Без имени') ?></div>
<div style="font-size:11px;color:#7b7287;">
<?= htmlspecialchars($u['email']) ?>
</div>
</td>
<td style="font-size:12px;">
<?= htmlspecialchars(date('d.m.Y H:i', strtotime($u['created_at']))) ?>
</td>
<td>
<?php if (!empty($u['is_banned'])): ?>
<span class="user-badge-banned">Заблокирован</span>
<?php else: ?>
<span style="font-size:12px;color:#54a870;">Активен</span>
<?php endif; ?>
</td>
<td>
<div style="display:flex;flex-wrap:wrap;gap:4px;">
<?php if (empty($u['is_banned'])): ?>
<form method="post" style="display:inline;">
<input type="hidden" name="action" value="ban_user">
<input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
<button type="submit" class="btn-outline btn-small"
onclick="return confirm('Заблокировать этого пользователя?');">
Бан
</button>
</form>
<?php else: ?>
<form method="post" style="display:inline;">
<input type="hidden" name="action" value="unban_user">
<input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
<button type="submit" class="btn-outline btn-small">
Разбан
</button>
</form>
<?php endif; ?>
<form method="post" style="display:inline;">
<input type="hidden" name="action" value="delete_user">
<input type="hidden" name="user_id" value="<?= (int)$u['id'] ?>">
<button type="submit" class="btn-outline btn-small"
onclick="return confirm('Точно удалить пользователя #<?= (int)$u['id'] ?>?');">
Удалить
</button>
</form>
</div>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</section>
<!-- БЛОК ПОДАРКОВ -->
<section>
<div class="admin-card">
<h2>Категории подарков</h2>
<form method="post">
<input type="hidden" name="action" value="add_category">
<div class="form-row">
<label>Название категории</label>
<input type="text" name="category_name" required placeholder="Например, Цветы">
</div>
<button type="submit" class="btn-primary">Добавить категорию</button>
</form>
<?php if ($categories): ?>
<ul style="margin-top:10px;font-size:13px;padding-left:18px;">
<?php foreach ($categories as $cat): ?>
<li><?= htmlspecialchars($cat['name']) ?> (ID: <?= (int)$cat['id'] ?>)</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</div>
<div class="admin-card">
<h2>Добавить подарок</h2>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="action" value="add_gift">
<div class="form-row">
<label>Категория</label>
<select name="gift_category_id" required>
<option value="">Выберите категорию</option>
<?php foreach ($categories as $cat): ?>
<option value="<?= (int)$cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-row">
<label>Название подарка</label>
<input type="text" name="gift_title" required placeholder="Например, Романтичный букет">
</div>
<div class="form-row">
<label>Изображение подарка</label>
<input type="file" name="gift_image" accept="image/*" required>
<div style="font-size:12px;color:#7b7287;margin-top:2px;">
Лучше квадратное изображение, до 1–2 МБ.
</div>
</div>
<button type="submit" class="btn-primary">Добавить подарок</button>
</form>
</div>
<div class="admin-card">
<h2>Все подарки</h2>
<?php if (!$gifts_by_cat): ?>
<p>Подарков пока нет. Создайте хотя бы один подарок.</p>
<?php else: ?>
<?php foreach ($gifts_by_cat as $cat_id => $data): ?>
<div class="gift-cat-title">
<?= htmlspecialchars($data['category_name']) ?>
</div>
<div class="gifts-grid">
<?php foreach ($data['items'] as $gift): ?>
<div class="gift-item">
<img src="/assets/gifts/<?= htmlspecialchars($gift['image']) ?>" class="gift-img" alt="">
<div><?= htmlspecialchars($gift['title']) ?></div>
<div style="font-size:10px;color:#a29ab4;">ID: <?= (int)$gift['id'] ?></div>
</div>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</section>
</div>
</div>
<?php include 'footer.php'; ?>