Files
web_work/catalog_admin.php
2025-12-16 01:28:06 +03:00

924 lines
38 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
// catalog_admin.php - единый файл каталога с админ-панелью
session_start();
// Подключение к базе данных
require_once 'config/database.php';
// Проверка прав администратора
$is_admin = isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true;
$action = $_GET['action'] ?? '';
$product_id = $_GET['id'] ?? 0;
$category_id = $_GET['category'] ?? '';
// Если не админ, перенаправляем
if (!$is_admin) {
header('Location: вход.php');
exit();
}
try {
$db = Database::getInstance()->getConnection();
// ОБРАБОТКА POST ЗАПРОСОВ ДЛЯ КАТЕГОРИЙ
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $is_admin) {
$form_action = $_POST['action'] ?? '';
if ($form_action === 'add_category' || $form_action === 'edit_category') {
$name = trim($_POST['name'] ?? '');
$parent_id = !empty($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
$description = trim($_POST['description'] ?? '');
$sort_order = (int)($_POST['sort_order'] ?? 0);
$is_active = isset($_POST['is_active']) ? 1 : 0;
$category_id_post = (int)($_POST['category_id'] ?? 0);
// Валидация
if (empty($name)) {
$_SESSION['error'] = 'Название категории обязательно';
header('Location: catalog_admin.php?action=' . $form_action . ($category_id_post ? '&id=' . $category_id_post : ''));
exit();
}
// Создаем slug
$slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $name));
$slug = preg_replace('/^-+|-+$/', '', $slug); // Убираем дефисы по краям
if ($form_action === 'add_category') {
// Проверяем существование slug
$check = $db->prepare("SELECT COUNT(*) FROM categories WHERE slug = ?");
$check->execute([$slug]);
if ($check->fetchColumn() > 0) {
$slug = $slug . '-' . time(); // Добавляем timestamp для уникальности
}
$sql = "INSERT INTO categories (name, slug, parent_id, description, sort_order, is_active)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $db->prepare($sql);
$stmt->execute([$name, $slug, $parent_id, $description, $sort_order, $is_active]);
$_SESSION['message'] = 'Категория успешно добавлена';
header('Location: catalog_admin.php?action=categories');
exit();
} elseif ($form_action === 'edit_category' && $category_id_post > 0) {
// Проверяем существование slug для других категорий
$check = $db->prepare("SELECT COUNT(*) FROM categories WHERE slug = ? AND category_id != ?");
$check->execute([$slug, $category_id_post]);
if ($check->fetchColumn() > 0) {
$slug = $slug . '-' . $category_id_post;
}
$sql = "UPDATE categories SET
name = ?, slug = ?, parent_id = ?, description = ?,
sort_order = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP
WHERE category_id = ?";
$stmt = $db->prepare($sql);
$stmt->execute([$name, $slug, $parent_id, $description, $sort_order, $is_active, $category_id_post]);
$_SESSION['message'] = 'Категория успешно обновлена';
header('Location: catalog_admin.php?action=categories');
exit();
}
}
// Удаление категории
if ($form_action === 'delete_category') {
$category_id_del = (int)($_POST['category_id'] ?? 0);
if ($category_id_del > 0) {
// Проверяем наличие активных товаров
$check_products = $db->prepare("
SELECT COUNT(*) as product_count
FROM products
WHERE category_id = ? AND is_available = TRUE
");
$check_products->execute([$category_id_del]);
$active_products = $check_products->fetchColumn();
if ($active_products > 0) {
$_SESSION['error'] = 'Невозможно удалить категорию с активными товарами';
header('Location: catalog_admin.php?action=categories');
exit();
}
// Проверяем дочерние категории
$check_children = $db->prepare("
SELECT COUNT(*) as child_count
FROM categories
WHERE parent_id = ? AND is_active = TRUE
");
$check_children->execute([$category_id_del]);
$active_children = $check_children->fetchColumn();
if ($active_children > 0) {
$_SESSION['error'] = 'Невозможно удалить категорию с активными дочерними категориями';
header('Location: catalog_admin.php?action=categories');
exit();
}
// Удаляем категорию
$stmt = $db->prepare("DELETE FROM categories WHERE category_id = ?");
$stmt->execute([$category_id_del]);
$_SESSION['message'] = 'Категория успешно удалена';
header('Location: catalog_admin.php?action=categories');
exit();
}
}
}
// Получаем категории для отображения
$categories_stmt = $db->query("
SELECT c1.*, c2.name as parent_name,
(SELECT COUNT(*) FROM products WHERE category_id = c1.category_id) as product_count
FROM categories c1
LEFT JOIN categories c2 ON c1.parent_id = c2.category_id
ORDER BY c1.sort_order, c1.name
");
$categories = $categories_stmt->fetchAll();
// Для редактирования категории
if ($action === 'edit_category' && $product_id > 0) {
$cat_stmt = $db->prepare("SELECT * FROM categories WHERE category_id = ?");
$cat_stmt->execute([$product_id]);
$current_category = $cat_stmt->fetch();
if (!$current_category) {
$_SESSION['error'] = 'Категория не найдена';
header('Location: catalog_admin.php?action=categories');
exit();
}
}
// Получаем товары
$sql = "SELECT p.*, c.name as category_name FROM products p
LEFT JOIN categories c ON p.category_id = c.category_id
WHERE p.is_available = TRUE";
$params = [];
if ($category_id && is_numeric($category_id)) {
$sql .= " AND p.category_id = ?";
$params[] = $category_id;
}
$sql .= " ORDER BY p.product_id DESC";
if ($params) {
$stmt = $db->prepare($sql);
$stmt->execute($params);
} else {
$stmt = $db->query($sql);
}
$products = $stmt->fetchAll();
// Сообщения из сессии
$message = $_SESSION['message'] ?? '';
$error = $_SESSION['error'] ?? '';
// Очищаем сообщения после использования
unset($_SESSION['message']);
unset($_SESSION['error']);
} catch (PDOException $e) {
$error = "Ошибка подключения к базе данных: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AETERNA - Каталог</title>
<link rel="stylesheet/less" type="text/css" href="style_for_cite.less">
<script src="https://cdn.jsdelivr.net/npm/less"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<style>
.admin-panel {
background: #f8f9fa;
padding: 20px;
margin: 20px 0;
border-radius: 8px;
border-left: 4px solid #617365;
}
.admin-btn {
background: #617365;
color: white;
padding: 8px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
margin: 5px;
text-decoration: none;
display: inline-block;
}
.admin-btn:hover {
background: #453227;
}
.admin-form {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
margin: 20px 0;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.form-group input, .form-group textarea, .form-group select {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-family: "Anonymous Pro", monospace;
font-size: 14px;
}
.form-group textarea {
min-height: 100px;
resize: vertical;
}
.form-group input[type="checkbox"] {
width: auto;
display: inline-block;
margin-right: 8px;
}
.alert {
padding: 15px;
margin-bottom: 20px;
border-radius: 4px;
}
.alert-success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.alert-danger {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.badge {
padding: 3px 8px;
border-radius: 4px;
font-size: 11px;
font-weight: bold;
margin-left: 5px;
}
.badge-warning {
background: #ffc107;
color: #212529;
}
.badge-info {
background: #17a2b8;
color: white;
}
.badge-success {
background: #28a745;
color: white;
}
.badge-danger {
background: #dc3545;
color: white;
}
.btn {
padding: 8px 15px;
border-radius: 4px;
border: none;
cursor: pointer;
font-size: 14px;
text-decoration: none;
display: inline-block;
}
.btn-sm {
padding: 5px 10px;
font-size: 12px;
}
.btn-warning {
background: #ffc107;
color: #212529;
}
.btn-danger {
background: #dc3545;
color: white;
}
.btn-secondary {
background: #6c757d;
color: white;
opacity: 0.6;
cursor: not-allowed;
}
.btn-success {
background: #28a745;
color: white;
}
.admin-table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
.admin-table th,
.admin-table td {
padding: 12px 15px;
text-align: left;
border-bottom: 1px solid #ddd;
}
.admin-table th {
background: #f8f9fa;
font-weight: bold;
color: #453227;
}
.admin-table tr:hover {
background: #f8f9fa;
}
.catalog-dropdown {
position: relative;
}
.catalog-dropdown__menu {
display: none;
position: absolute;
top: 100%;
left: 0;
width: 250px;
background: white;
border-radius: 8px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
padding: 15px;
z-index: 1000;
margin-top: 5px;
max-height: 400px;
overflow-y: auto;
}
.catalog-dropdown:hover .catalog-dropdown__menu {
display: block;
}
.catalog-dropdown__menu ul {
list-style: none;
padding: 0;
margin: 0;
}
.catalog-dropdown__menu li {
padding: 8px 0;
border-bottom: 1px solid #f0f0f0;
}
.catalog-dropdown__menu li:last-child {
border-bottom: none;
}
.catalog-dropdown__menu a {
color: #333;
text-decoration: none;
display: block;
}
.catalog-dropdown__menu a:hover {
color: #453227;
padding-left: 5px;
}
</style>
</head>
<body>
<header class="header">
<div class="header__top">
<div class="container header__top-content">
<div class="logo">AETERNA</div>
<div class="search-catalog">
<div class="catalog-dropdown">
Все категории <span>&#9660;</span>
<div class="catalog-dropdown__menu">
<ul>
<li><a href="catalog_admin.php">Все товары</a></li>
<?php foreach ($categories as $cat): ?>
<li><a href="catalog_admin.php?category=<?= $cat['category_id'] ?>">
<?= htmlspecialchars($cat['name']) ?>
</a></li>
<?php endforeach; ?>
</ul>
</div>
</div>
<div class="search-box">
<input type="text" placeholder="Поиск товаров">
<span class="search-icon"><i class="fas fa-search"></i></span>
</div>
</div>
<div class="header__icons--top">
<a href="оформлениеаказа.php" class="icon cart-icon">
<i class="fas fa-shopping-cart"></i>
<span class="cart-count">0</span>
</a>
<?php if ($is_admin): ?>
<div class="user-profile-dropdown">
<div class="user-profile-toggle">
<div class="user-avatar">
<?= strtoupper(substr($_SESSION['user_email'] ?? 'A', 0, 1)) ?>
</div>
<div class="user-info">
<div class="user-email"><?= htmlspecialchars($_SESSION['user_email'] ?? '') ?></div>
<div class="user-status admin">Админ</div>
</div>
<i class="fas fa-chevron-down dropdown-arrow"></i>
</div>
<div class="user-profile-menu">
<div class="user-profile-header">
<div class="user-profile-name">
<i class="fas fa-user-shield"></i>
<?= htmlspecialchars($_SESSION['full_name'] ?? $_SESSION['user_email']) ?>
</div>
</div>
<ul class="user-profile-links">
<li><a href="logout.php" class="logout-link">
<i class="fas fa-sign-out-alt"></i>
<span>Выйти</span>
</a></li>
</ul>
</div>
</div>
<?php endif; ?>
</div>
</div>
</div>
<div class="header__bottom">
<div class="container header__bottom-content">
<div class="catalog-menu">
<a href="catalog_admin.php" class="catalog-link active-catalog">
<div class="catalog-icon">
<span class="line"></span>
<span class="line"></span>
<span class="line"></span>
</div>
<span class="catalog-lines">☰</span>
Каталог
</a>
</div>
<nav class="nav">
<ul class="nav-list">
<li><a href="cite_mebel.php">Главная</a></li>
<li><a href="услуги.php">Услуги</a></li>
<li><a href="Доставка.php">Доставка и оплата</a></li>
<li><a href="Гарантия.php">Гарантия</a></li>
<li><a href="#footer">Контакты</a></li>
</ul>
</nav>
<div class="header-phone">+7(912)999-12-23</div>
</div>
</div>
</header>
<main class="catalog-main">
<div class="container">
<div class="breadcrumbs">
<a href="cite_mebel.php">Главная</a> • <span class="current-page">Каталог</span>
</div>
<?php if ($is_admin): ?>
<!-- Панель администратора -->
<div class="admin-panel">
<h3>Панель управления каталогом</h3>
<a href="?action=add_product" class="admin-btn">
<i class="fas fa-plus"></i> Добавить товар
</a>
<a href="?action=add_category" class="admin-btn">
<i class="fas fa-folder-plus"></i> Добавить категорию
</a>
<a href="?action=categories" class="admin-btn" style="background: #ffc107; color: #212529;">
<i class="fas fa-tags"></i> Управление категориями
</a>
</div>
<?php if ($message): ?>
<div class="alert alert-success">
<i class="fas fa-check-circle"></i> <?= htmlspecialchars($message) ?>
</div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-danger">
<i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?>
</div>
<?php endif; ?>
<?php if ($action === 'add_category' || $action === 'edit_category'): ?>
<!-- Форма добавления/редактирования категории -->
<div class="admin-form" id="categoryForm">
<h3><?= ($action === 'add_category') ? 'Добавление категории' : 'Редактирование категории' ?></h3>
<?php if (isset($error) && !empty($error)): ?>
<div class="alert alert-danger">
<i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?>
</div>
<?php endif; ?>
<form method="POST" action="catalog_admin.php" id="categoryFormElement">
<input type="hidden" name="action" value="<?= $action ?>">
<?php if ($action === 'edit_category' && isset($current_category)): ?>
<input type="hidden" name="category_id" value="<?= $current_category['category_id'] ?>">
<?php endif; ?>
<div class="form-group">
<label for="category_name">Название категории: *</label>
<input type="text" name="name" id="category_name" required
value="<?= htmlspecialchars($current_category['name'] ?? '') ?>"
placeholder="Введите название категории">
</div>
<div class="form-group">
<label for="parent_category">Родительская категория:</label>
<select name="parent_id" id="parent_category">
<option value="">Без родительской категории</option>
<?php foreach ($categories as $cat): ?>
<?php if (!isset($current_category['category_id']) || $cat['category_id'] != $current_category['category_id']): ?>
<option value="<?= $cat['category_id'] ?>"
<?= (isset($current_category['parent_id']) && $current_category['parent_id'] == $cat['category_id']) ? 'selected' : '' ?>>
<?= htmlspecialchars($cat['name']) ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="category_description">Описание:</label>
<textarea name="description" id="category_description" rows="3"
placeholder="Описание категории (необязательно)"><?= htmlspecialchars($current_category['description'] ?? '') ?></textarea>
</div>
<div class="form-group">
<label for="sort_order">Порядок сортировки:</label>
<input type="number" name="sort_order" id="sort_order"
value="<?= $current_category['sort_order'] ?? 0 ?>"
min="0" max="100">
</div>
<div class="form-group">
<label>
<input type="checkbox" name="is_active" value="1"
<?= (!isset($current_category['is_active']) || $current_category['is_active']) ? 'checked' : '' ?>>
Активна
</label>
</div>
<button type="submit" class="admin-btn">
<i class="fas fa-save"></i> Сохранить
</button>
<a href="catalog_admin.php?action=categories" class="admin-btn" style="background: #6c757d;">
<i class="fas fa-times"></i> Отмена
</a>
</form>
</div>
<?php endif; ?>
<?php endif; ?>
<div class="catalog-wrapper">
<aside class="catalog-sidebar">
<div class="filter-group">
<h4 class="filter-title">КАТЕГОРИИ</h4>
<ul class="filter-list">
<li><a href="catalog_admin.php" class="<?= (!$category_id) ? 'active-category' : '' ?>">Все товары</a></li>
<?php foreach ($categories as $cat): ?>
<li>
<a href="catalog_admin.php?category=<?= $cat['category_id'] ?>"
class="<?= ($category_id == $cat['category_id']) ? 'active-category' : '' ?>">
<?= htmlspecialchars($cat['name']) ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
<div class="filter-group">
<h4 class="filter-title">ЦЕНА</h4>
<div class="price-range">
<div class="range-slider">
<input type="range" min="1000" max="100000" value="50000" step="1000">
</div>
<div class="price-display">До 50 000 ₽</div>
</div>
</div>
<button class="btn primary-btn filter-apply-btn">ПРИМЕНИТЬ</button>
</aside>
<section class="catalog-products">
<?php if ($action === 'categories'): ?>
<!-- Раздел управления категориями -->
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>Управление категориями</h2>
<a href="?action=add_category" class="btn btn-success">
<i class="fas fa-plus"></i> Добавить категорию
</a>
</div>
<table class="admin-table">
<thead>
<tr>
<th>ID</th>
<th>Название</th>
<th>Родительская</th>
<th>Товаров</th>
<th>Порядок</th>
<th>Статус</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
<?php foreach ($categories as $cat): ?>
<tr>
<td><?= $cat['category_id'] ?></td>
<td>
<strong><?= htmlspecialchars($cat['name']) ?></strong>
<br><small style="color: #666;"><?= htmlspecialchars($cat['slug']) ?></small>
</td>
<td><?= htmlspecialchars($cat['parent_name'] ?? '—') ?></td>
<td>
<span class="badge badge-info"><?= $cat['product_count'] ?> товаров</span>
</td>
<td><?= $cat['sort_order'] ?></td>
<td>
<?php if ($cat['is_active']): ?>
<span class="badge badge-success">Активна</span>
<?php else: ?>
<span class="badge badge-warning">Неактивна</span>
<?php endif; ?>
</td>
<td>
<a href="?action=edit_category&id=<?= $cat['category_id'] ?>"
class="btn btn-sm btn-warning" title="Редактировать">
<i class="fas fa-edit"></i>
</a>
<form method="POST" action="catalog_admin.php" style="display: inline-block;"
onsubmit="return confirm('Вы уверены, что хотите удалить категорию?');">
<input type="hidden" name="action" value="delete_category">
<input type="hidden" name="category_id" value="<?= $cat['category_id'] ?>">
<?php if ($cat['product_count'] == 0): ?>
<button type="submit" class="btn btn-sm btn-danger" title="Удалить">
<i class="fas fa-trash"></i>
</button>
<?php else: ?>
<button type="button" class="btn btn-sm btn-secondary"
title="Нельзя удалить категорию с товарами" disabled>
<i class="fas fa-trash"></i>
</button>
<?php endif; ?>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<!-- Основной каталог товаров -->
<div class="products-container">
<?php foreach ($products as $product): ?>
<div class="product-card <?= getCardSizeClass($product) ?>">
<?php if ($is_admin): ?>
<div class="admin-actions">
<a href="?action=edit&id=<?= $product['product_id'] ?>"
class="admin-btn" style="background: #28a745;">
<i class="fas fa-edit"></i>
</a>
<a href="?action=delete&id=<?= $product['product_id'] ?>"
class="admin-btn" style="background: #dc3545;"
onclick="return confirm('Сделать товар недоступным?')">
<i class="fas fa-trash"></i>
</a>
</div>
<?php endif; ?>
<div class="product-image-container">
<img src="<?= htmlspecialchars($product['image_url'] ?: 'img1/default.jpg') ?>"
alt="<?= htmlspecialchars($product['name']) ?>"
class="product-img">
<?php if ($product['old_price'] && $product['old_price'] > $product['price']): ?>
<span class="product-discount">
-<?= round(($product['old_price'] - $product['price']) / $product['old_price'] * 100) ?>%
</span>
<?php endif; ?>
<i class="fas fa-shopping-cart product-wishlist-icon"
onclick="addToCart(<?= $product['product_id'] ?>)"></i>
</div>
<div class="product-info" style="padding: 15px;">
<div class="product-name"><?= htmlspecialchars($product['name']) ?></div>
<div class="product-details">
<?= htmlspecialchars(mb_substr($product['description'], 0, 100)) ?>...
</div>
<div class="product-price" style="margin-top: 10px;">
<?php if ($product['old_price'] && $product['old_price'] > $product['price']): ?>
<span style="text-decoration: line-through; color: #999; font-size: 14px;">
<?= number_format($product['old_price'], 0, '', ' ') ?> ₽
</span><br>
<?php endif; ?>
<?= number_format($product['price'], 0, '', ' ') ?> ₽
</div>
<div class="product-stock" style="font-size: 12px; color: #28a745; margin-top: 5px;">
В наличии: <?= $product['stock_quantity'] ?> шт.
</div>
<button onclick="addToCart(<?= $product['product_id'] ?>)"
class="btn btn-primary" style="width: 100%; margin-top: 10px;">
<i class="fas fa-shopping-cart"></i> В корзину
</button>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</section>
</div>
</div>
</main>
<footer class="footer" id="footer">
<div class="container footer__content">
<div class="footer__col footer--logo">
<div class="logo">AETERNA</div>
</div>
<div class="footer__col">
<h5>ПОКУПАТЕЛЮ</h5>
<ul>
<li><a href="catalog_admin.php">Каталог</a></li>
<li><a href="услуги.php">Услуги</a></li>
</ul>
</div>
<div class="footer__col">
<h5>ПОМОЩЬ</h5>
<ul>
<li><a href="Доставка.php">Доставка и оплата</a></li>
<li><a href="Гарантия.php">Гарантия и возврат</a></li>
<li><a href="cite_mebel.php#faq">Ответы на вопросы</a></li>
<li><a href="#footer">Контакты</a></li>
</ul>
</div>
<div class="footer__col">
<h5>КОНТАКТЫ</h5>
<p>aeterna@mail.ru</p>
<p>+7(912)999-12-23</p>
<div class="social-icons">
<span class="icon"><i class="fab fa-telegram"></i></span>
<span class="icon"><i class="fab fa-instagram"></i></span>
<span class="icon"><i class="fab fa-vk"></i></span>
</div>
</div>
<div class="footer__col">
<h5>ПРИНИМАЕМ К ОПЛАТЕ</h5>
<div class="payment-icons">
<span class="pay-icon"><i class="fab fa-cc-visa"></i></span>
<span class="pay-icon"><i class="fab fa-cc-mastercard"></i></span>
</div>
</div>
</div>
<div class="copyright">
<p>© 2025 AETERNA. Все права защищены.</p>
</div>
</footer>
<script>
// Функция для показа формы добавления товара
function showAddForm() {
window.location.href = 'catalog_admin.php?action=add';
}
// Функция для показа формы добавления категории
function showAddCategoryForm() {
window.location.href = 'catalog_admin.php?action=add_category';
}
// Функция для редактирования категории
function editCategory(categoryId) {
window.location.href = 'catalog_admin.php?action=edit_category&id=' + categoryId;
}
// Функция для скрытия формы
function hideForm() {
window.location.href = 'catalog_admin.php?action=categories';
}
// Функция добавления в корзину
function addToCart(productId) {
$.ajax({
url: "cart_handler.php",
method: "POST",
data: { action: "add", product_id: productId, quantity: 1 },
success: function(response) {
try {
var result = JSON.parse(response);
if (result.success) {
alert("Товар добавлен в корзину!");
// Обновляем счетчик корзины
if ($(".cart-count").length) {
var current = parseInt($(".cart-count").text()) || 0;
$(".cart-count").text(current + 1);
}
} else {
alert("Ошибка: " + result.message);
}
} catch(e) {
alert("Товар добавлен в корзину!");
}
},
error: function() {
alert("Товар добавлен в корзину!");
}
});
}
// Обработка формы категории с подтверждением
$(document).ready(function() {
$('#categoryFormElement').on('submit', function(e) {
const action = $(this).find('input[name="action"]').val();
const categoryName = $(this).find('input[name="name"]').val();
if (!categoryName.trim()) {
e.preventDefault();
alert('Пожалуйста, введите название категории');
return false;
}
const message = action === 'add_category'
? 'Добавить новую категорию "' + categoryName + '"?'
: 'Сохранить изменения в категории?';
if (!confirm(message)) {
e.preventDefault();
return false;
}
});
// Подтверждение удаления категории
$('form[action="catalog_admin.php"]').on('submit', function(e) {
const action = $(this).find('input[name="action"]').val();
if (action === 'delete_category') {
const categoryId = $(this).find('input[name="category_id"]').val();
if (!confirm('Вы уверены, что хотите удалить эту категорию?')) {
e.preventDefault();
return false;
}
}
});
<?php if ($is_admin): ?>
$('.product-card').hover(
function() {
$(this).find('.admin-actions').show();
},
function() {
$(this).find('.admin-actions').hide();
}
);
<?php endif; ?>
});
</script>
</body>
</html>
<?php
// Вспомогательная функция для определения размера карточки
function getCardSizeClass($product) {
$sizes = ['small', 'large', 'wide', 'tall', 'small1', 'wide2', 'wide3', 'wide2_1', 'full-width'];
$index = $product['product_id'] % count($sizes);
return $sizes[$index];
}