View file zip0.ru/admin_gifts.php

File size: 8.12Kb
<?php
require_once 'db.php';

if (empty($_SESSION['user_id']) || !is_admin($_SESSION['user_id'])) {
    echo 'Доступ только для администратора.';
    exit;
}

$errors = [];
$success = false;

/* === Добавление категории === */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['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 = true;
    }
}

/* === Добавление подарка === */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['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[] = 'Не удалось сохранить файл подарка.';
            }
        }
    } 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 = true;
    }
}

/* === Загрузка категорий и подарков === */
$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-grid {
    display: grid;
    grid-template-columns: minmax(0, 1.1fr) 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);
}

.admin-card h2 {
    margin-top: 0;
    margin-bottom: 10px;
    font-size: 19px;
}

.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;
}
</style>

<div class="admin-page">
    <h1>Админка подарков</h1>

    <?php if ($success): ?>
        <div class="alert alert-success">Изменения сохранены ✅</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-grid">
        <section 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:14px;font-size:14px;padding-left:18px;">
                    <?php foreach ($categories as $cat): ?>
                        <li><?= htmlspecialchars($cat['name']) ?> (ID: <?= (int)$cat['id'] ?>)</li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </section>

        <section 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>
        </section>
    </div>

    <div class="admin-card" style="margin-top:20px;">
        <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>
</div>

<?php include 'footer.php'; ?>