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

170 lines
7.9 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
// admin_actions.php
session_start();
require_once 'config/database.php';
// Проверка прав администратора
if (!isset($_SESSION['isAdmin']) || $_SESSION['isAdmin'] !== true) {
header('Location: вход.php?error=admin_only');
exit();
}
$db = Database::getInstance()->getConnection();
$action = $_GET['action'] ?? '';
try {
switch ($action) {
case 'delete_product':
if (isset($_GET['id'])) {
$productId = intval($_GET['id']);
// Делаем товар недоступным
$stmt = $db->prepare("
UPDATE products
SET is_available = FALSE, stock_quantity = 0, updated_at = CURRENT_TIMESTAMP
WHERE product_id = ?
");
$stmt->execute([$productId]);
header('Location: admin_panel.php?action=products&message=Товар помечен как недоступный');
exit();
}
break;
case 'restore_product':
if (isset($_GET['id'])) {
$productId = intval($_GET['id']);
// Восстанавливаем товар
$stmt = $db->prepare("
UPDATE products
SET is_available = TRUE, stock_quantity = 10, updated_at = CURRENT_TIMESTAMP
WHERE product_id = ?
");
$stmt->execute([$productId]);
header('Location: admin_panel.php?action=products&message=Товар восстановлен');
exit();
}
break;
case 'delete_category':
if (isset($_GET['id'])) {
$categoryId = intval($_GET['id']);
try {
// 1. Проверяем, есть ли товары в этой категории
$checkProducts = $db->prepare("SELECT COUNT(*) FROM products WHERE category_id = ?");
$checkProducts->execute([$categoryId]);
$productCount = $checkProducts->fetchColumn();
if ($productCount > 0) {
// Если есть товары, делаем категорию неактивной
$stmt = $db->prepare("UPDATE categories SET is_active = FALSE WHERE category_id = ?");
$stmt->execute([$categoryId]);
header('Location: admin_panel.php?action=categories&message=Категория скрыта (содержит товары)');
exit();
}
// 2. Проверяем, есть ли дочерние категории
$checkChildren = $db->prepare("SELECT COUNT(*) FROM categories WHERE parent_id = ?");
$checkChildren->execute([$categoryId]);
$childCount = $checkChildren->fetchColumn();
if ($childCount > 0) {
// Вариант A: Делаем категорию неактивной
$stmt = $db->prepare("UPDATE categories SET is_active = FALSE WHERE category_id = ?");
$stmt->execute([$categoryId]);
header('Location: admin_panel.php?action=categories&message=Категория скрыта (имеет дочерние категории)');
exit();
// Вариант B: Удаляем вместе с дочерними (раскомментируйте если нужно)
/*
// Сначала удаляем дочерние категории
$stmt = $db->prepare("DELETE FROM categories WHERE parent_id = ?");
$stmt->execute([$categoryId]);
// Затем удаляем саму категорию
$stmt = $db->prepare("DELETE FROM categories WHERE category_id = ?");
$stmt->execute([$categoryId]);
header('Location: admin_panel.php?action=categories&message=Категория и её дочерние категории удалены');
exit();
*/
}
// 3. Если нет товаров и дочерних категорий, удаляем
$stmt = $db->prepare("DELETE FROM categories WHERE category_id = ?");
$stmt->execute([$categoryId]);
header('Location: admin_panel.php?action=categories&message=Категория удалена');
exit();
} catch (PDOException $e) {
header('Location: admin_panel.php?action=categories&error=' . urlencode($e->getMessage()));
exit();
}
}
break;
case 'delete_category_force':
// Принудительное удаление с дочерними категориями
if (isset($_GET['id'])) {
$categoryId = intval($_GET['id']);
try {
// Сначала перемещаем товары в другую категорию (например, в первую)
$firstCategory = $db->query("SELECT category_id FROM categories WHERE category_id != ? LIMIT 1")->fetchColumn();
if ($firstCategory) {
$moveProducts = $db->prepare("UPDATE products SET category_id = ? WHERE category_id = ?");
$moveProducts->execute([$firstCategory, $categoryId]);
}
// Обнуляем parent_id у дочерних категорий
$stmt = $db->prepare("UPDATE categories SET parent_id = NULL WHERE parent_id = ?");
$stmt->execute([$categoryId]);
// Удаляем категорию
$stmt = $db->prepare("DELETE FROM categories WHERE category_id = ?");
$stmt->execute([$categoryId]);
header('Location: admin_panel.php?action=categories&message=Категория удалена. Товары перемещены.');
exit();
} catch (PDOException $e) {
header('Location: admin_panel.php?action=categories&error=' . urlencode($e->getMessage()));
exit();
}
}
break;
case 'toggle_user':
if (isset($_GET['id'])) {
$userId = intval($_GET['id']);
$stmt = $db->prepare("
UPDATE users
SET is_active = NOT is_active, updated_at = CURRENT_TIMESTAMP
WHERE user_id = ?
");
$stmt->execute([$userId]);
header('Location: admin_panel.php?action=users&message=Статус пользователя изменен');
exit();
}
break;
case 'make_admin':
if (isset($_GET['id'])) {
$userId = intval($_GET['id']);
$stmt = $db->prepare("UPDATE users SET is_admin = TRUE WHERE user_id = ?");
$stmt->execute([$userId]);
header('Location: admin_panel.php?action=users&message=Пользователь назначен администратором');
exit();
}
break;
}
} catch (PDOException $e) {
header('Location: admin_panel.php?error=' . urlencode($e->getMessage()));
exit();
}
// Если действие не распознано
header('Location: admin_panel.php');
exit();
?>