Files
web_work/public/admin/index.php
kirill.khorkov 07289608e5 Fix
2025-12-17 20:42:54 +03:00

988 lines
48 KiB
PHP
Raw 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
session_start();
require_once __DIR__ . '/../config/database.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!isset($_SESSION['isAdmin']) || $_SESSION['isAdmin'] !== true) {
echo "<script>alert('Требуется авторизация администратора'); window.location.href = '../login.php';</script>";
exit();
}
$db = Database::getInstance()->getConnection();
$action = $_GET['action'] ?? 'dashboard';
$message = $_GET['message'] ?? '';
$error = $_GET['error'] ?? '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$post_action = $_POST['action'] ?? '';
try {
if ($post_action === 'add_category') {
$name = trim($_POST['name'] ?? '');
$slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $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;
if (empty($name)) {
throw new Exception('Название категории обязательно');
}
$stmt = $db->prepare("
INSERT INTO categories (name, slug, parent_id, description, sort_order, is_active)
VALUES (?, ?, ?, ?, ?, ?)
");
$result = $stmt->execute([$name, $slug, $parent_id, $description, $sort_order, $is_active]);
if ($result) {
header('Location: index.php?action=categories&message=Категория+успешно+добавлена');
exit();
}
}
if ($post_action === 'edit_category' && isset($_POST['category_id'])) {
$category_id = (int)$_POST['category_id'];
$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;
if (empty($name)) {
throw new Exception('Название категории обязательно');
}
$slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $name));
$stmt = $db->prepare("
UPDATE categories SET
name = ?,
slug = ?,
parent_id = ?,
description = ?,
sort_order = ?,
is_active = ?,
updated_at = CURRENT_TIMESTAMP
WHERE category_id = ?
");
$stmt->execute([$name, $slug, $parent_id, $description, $sort_order, $is_active, $category_id]);
header('Location: index.php?action=categories&message=Категория+обновлена');
exit();
}
if ($post_action === 'add_product') {
$name = trim($_POST['name'] ?? '');
$slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $name));
$category_id = (int)($_POST['category_id'] ?? 0);
$description = trim($_POST['description'] ?? '');
$price = (float)($_POST['price'] ?? 0);
$old_price = !empty($_POST['old_price']) ? (float)$_POST['old_price'] : NULL;
$sku = trim($_POST['sku'] ?? '');
$stock_quantity = (int)($_POST['stock_quantity'] ?? 0);
$is_available = isset($_POST['is_available']) ? 1 : 0;
$is_featured = isset($_POST['is_featured']) ? 1 : 0;
$image_url = trim($_POST['image_url'] ?? '');
$color = trim($_POST['color'] ?? '');
$material = trim($_POST['material'] ?? '');
$card_size = trim($_POST['card_size'] ?? 'small');
if ($category_id <= 0) {
$_SESSION['error'] = 'Выберите корректную категорию';
header('Location: index.php?action=add_product');
exit();
}
$check_category = $db->prepare("SELECT COUNT(*) FROM categories WHERE category_id = ?");
$check_category->execute([$category_id]);
if ($check_category->fetchColumn() == 0) {
$_SESSION['error'] = 'Выбранная категория не существует';
header('Location: index.php?action=add_product');
exit();
}
if (empty($name)) throw new Exception('Название товара обязательно');
if ($price <= 0) throw new Exception('Цена должна быть больше 0');
if (empty($sku)) {
$sku = 'PROD-' . strtoupper(substr(preg_replace('/[^a-z0-9]/i', '', $name), 0, 6)) . '-' . rand(100, 999);
}
$stmt = $db->prepare("
INSERT INTO products (
category_id, name, slug, description, price, old_price,
sku, stock_quantity, is_available, is_featured, image_url,
color, material, card_size
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$result = $stmt->execute([
$category_id, $name, $slug, $description, $price, $old_price,
$sku, $stock_quantity, $is_available, $is_featured, $image_url,
$color, $material, $card_size
]);
if ($result) {
$_SESSION['message'] = 'Товар успешно добавлен';
header('Location: index.php?action=products');
exit();
}
}
if ($post_action === 'edit_product' && isset($_POST['product_id'])) {
$product_id = (int)$_POST['product_id'];
$name = trim($_POST['name'] ?? '');
$category_id = (int)($_POST['category_id'] ?? 1);
$description = trim($_POST['description'] ?? '');
$price = (float)($_POST['price'] ?? 0);
$old_price = !empty($_POST['old_price']) ? (float)$_POST['old_price'] : NULL;
$stock_quantity = (int)($_POST['stock_quantity'] ?? 0);
$is_available = isset($_POST['is_available']) ? 1 : 0;
$image_url = trim($_POST['image_url'] ?? '');
$color = trim($_POST['color'] ?? '');
$material = trim($_POST['material'] ?? '');
if ($category_id <= 0) {
$firstCat = $db->query("SELECT category_id FROM categories LIMIT 1")->fetchColumn();
$category_id = $firstCat ?: 1;
}
$stmt = $db->prepare("
UPDATE products SET
name = ?,
category_id = ?,
description = ?,
price = ?,
old_price = ?,
stock_quantity = ?,
is_available = ?,
image_url = ?,
color = ?,
material = ?,
updated_at = CURRENT_TIMESTAMP
WHERE product_id = ?
");
$stmt->execute([
$name, $category_id, $description, $price, $old_price,
$stock_quantity, $is_available, $image_url, $color, $material, $product_id
]);
header('Location: index.php?action=products&message=Товар+обновлен');
exit();
}
if ($post_action === 'delete_category' && isset($_POST['category_id'])) {
$categoryId = intval($_POST['category_id']);
$checkProducts = $db->prepare("SELECT COUNT(*) FROM products WHERE category_id = ?");
$checkProducts->execute([$categoryId]);
$productCount = $checkProducts->fetchColumn();
$checkChildren = $db->prepare("SELECT COUNT(*) FROM categories WHERE parent_id = ?");
$checkChildren->execute([$categoryId]);
$childCount = $checkChildren->fetchColumn();
if ($productCount > 0) {
$stmt = $db->prepare("UPDATE categories SET is_active = FALSE WHERE category_id = ?");
$stmt->execute([$categoryId]);
header('Location: index.php?action=categories&message=Категория+скрыта+(содержит+товары)');
exit();
} elseif ($childCount > 0) {
$stmt = $db->prepare("UPDATE categories SET is_active = FALSE WHERE category_id = ?");
$stmt->execute([$categoryId]);
header('Location: index.php?action=categories&message=Категория+скрыта+(имеет+дочерние+категории)');
exit();
} else {
$stmt = $db->prepare("DELETE FROM categories WHERE category_id = ?");
$stmt->execute([$categoryId]);
header('Location: index.php?action=categories&message=Категория+удалена');
exit();
}
}
} catch (PDOException $e) {
header('Location: index.php?action=' . $action . '&error=' . urlencode('Ошибка БД: ' . $e->getMessage()));
exit();
} catch (Exception $e) {
header('Location: index.php?action=' . $action . '&error=' . urlencode($e->getMessage()));
exit();
}
}
try {
$stats = [
'total_products' => $db->query("SELECT COUNT(*) FROM products")->fetchColumn(),
'active_products' => $db->query("SELECT COUNT(*) FROM products WHERE is_available = TRUE")->fetchColumn(),
'total_orders' => $db->query("SELECT COUNT(*) FROM orders")->fetchColumn(),
'total_users' => $db->query("SELECT COUNT(*) FROM users")->fetchColumn(),
'revenue' => $db->query("SELECT COALESCE(SUM(final_amount), 0) FROM orders WHERE status = 'completed'")->fetchColumn()
];
$allCategories = $db->query("SELECT * FROM categories WHERE is_active = TRUE ORDER BY name")->fetchAll();
$parentCategories = $db->query("SELECT * FROM categories WHERE parent_id IS NULL AND is_active = TRUE ORDER BY name")->fetchAll();
switch ($action) {
case 'products':
$showAll = isset($_GET['show_all']) && $_GET['show_all'] == '1';
$sql = $showAll
? "SELECT p.*, c.name as category_name FROM products p LEFT JOIN categories c ON p.category_id = c.category_id ORDER BY p.created_at DESC"
: "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 ORDER BY p.created_at DESC";
$data = $db->query($sql)->fetchAll();
break;
case 'categories':
$data = $db->query("
SELECT c1.*, c2.name as parent_name,
(SELECT COUNT(*) FROM products p WHERE p.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
")->fetchAll();
break;
case 'orders':
$data = $db->query("
SELECT o.*, u.email as user_email
FROM orders o
LEFT JOIN users u ON o.user_id = u.user_id
ORDER BY o.created_at DESC
LIMIT 50
")->fetchAll();
break;
case 'users':
$data = $db->query("SELECT * FROM users ORDER BY created_at DESC LIMIT 50")->fetchAll();
break;
case 'add_product':
case 'edit_product':
if ($action === 'edit_product' && isset($_GET['id'])) {
$productId = (int)$_GET['id'];
$stmt = $db->prepare("SELECT * FROM products WHERE product_id = ?");
$stmt->execute([$productId]);
$edit_data = $stmt->fetch();
}
break;
case 'add_category':
case 'edit_category':
if ($action === 'edit_category' && isset($_GET['id'])) {
$categoryId = (int)$_GET['id'];
$stmt = $db->prepare("SELECT * FROM categories WHERE category_id = ?");
$stmt->execute([$categoryId]);
$edit_data = $stmt->fetch();
}
break;
case 'order_details':
if (isset($_GET['id'])) {
$orderId = (int)$_GET['id'];
// Получаем информацию о заказе
$stmt = $db->prepare("
SELECT o.*, u.email as user_email, u.full_name as user_full_name
FROM orders o
LEFT JOIN users u ON o.user_id = u.user_id
WHERE o.order_id = ?
");
$stmt->execute([$orderId]);
$order = $stmt->fetch();
// Получаем товары в заказе
if ($order) {
$stmt = $db->prepare("
SELECT oi.*, p.image_url
FROM order_items oi
LEFT JOIN products p ON oi.product_id = p.product_id
WHERE oi.order_id = ?
");
$stmt->execute([$orderId]);
$order_items = $stmt->fetchAll();
}
}
break;
}
} 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">
<base href="/cite_practica/admin/">
<title>AETERNA - Админ-панель</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
body { font-family: Arial, sans-serif; margin: 0; padding: 0; background: #f5f5f5; }
.admin-header { background: #453227; color: white; padding: 20px; display: flex; justify-content: space-between; align-items: center; }
.admin-tabs { background: white; padding: 10px; border-bottom: 2px solid #453227; display: flex; gap: 10px; }
.admin-tab { padding: 10px 20px; border-radius: 5px; text-decoration: none; color: #333; }
.admin-tab:hover, .admin-tab.active { background: #453227; color: white; }
.admin-content { padding: 20px; }
.form-container { background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); max-width: 800px; margin: 0 auto; }
.form-group { margin-bottom: 15px; }
.form-group label { display: block; margin-bottom: 5px; font-weight: bold; }
.form-control { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
.btn { padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; text-decoration: none; display: inline-block; }
.btn-primary { background: #453227; color: white; }
.btn-success { background: #28a745; color: white; }
.btn-danger { background: #dc3545; color: white; }
.btn-warning { background: #ffc107; color: #333; }
.alert { padding: 15px; border-radius: 4px; margin-bottom: 20px; }
.alert-success { background: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
.alert-danger { background: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
table { width: 100%; border-collapse: collapse; background: white; }
th, td { padding: 10px; border: 1px solid #ddd; text-align: left; }
th { background: #f8f9fa; }
.action-buttons { display: flex; gap: 5px; }
</style>
</head>
<body>
<div class="admin-header">
<h1><i class="fas fa-user-shield"></i> Админ-панель AETERNA</h1>
<div>
<span><?= htmlspecialchars($_SESSION['user_email'] ?? 'Администратор') ?></span>
<a href="/cite_practica/catalog.php" class="btn btn-primary" style="margin-left: 10px;">В каталог</a>
<a href="/cite_practica/logout.php" class="btn btn-danger" style="margin-left: 10px;">Выйти</a>
</div>
</div>
<div class="admin-tabs">
<a href="index.php?action=dashboard" class="admin-tab <?= $action == 'dashboard' ? 'active' : '' ?>">
<i class="fas fa-tachometer-alt"></i> Дашборд
</a>
<a href="index.php?action=products" class="admin-tab <?= $action == 'products' ? 'active' : '' ?>">
<i class="fas fa-box"></i> Товары
</a>
<a href="index.php?action=categories" class="admin-tab <?= $action == 'categories' ? 'active' : '' ?>">
<i class="fas fa-tags"></i> Категории
</a>
<a href="index.php?action=orders" class="admin-tab <?= $action == 'orders' ? 'active' : '' ?>">
<i class="fas fa-shopping-cart"></i> Заказы
</a>
<a href="index.php?action=users" class="admin-tab <?= $action == 'users' ? 'active' : '' ?>">
<i class="fas fa-users"></i> Пользователи
</a>
</div>
<div class="admin-content">
<?php if ($message): ?>
<div class="alert alert-success">
<i class="fas fa-check-circle"></i> <?= htmlspecialchars(urldecode($message)) ?>
</div>
<?php endif; ?>
<?php if ($error): ?>
<div class="alert alert-danger">
<i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars(urldecode($error)) ?>
</div>
<?php endif; ?>
<?php if ($action == 'dashboard'): ?>
<h2>Статистика</h2>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 20px 0;">
<div style="background: white; padding: 20px; border-radius: 5px; text-align: center;">
<h3><?= $stats['total_products'] ?></h3>
<p>Всего товаров</p>
</div>
<div style="background: white; padding: 20px; border-radius: 5px; text-align: center;">
<h3><?= $stats['active_products'] ?></h3>
<p>Активных товаров</p>
</div>
<div style="background: white; padding: 20px; border-radius: 5px; text-align: center;">
<h3><?= $stats['total_orders'] ?></h3>
<p>Заказов</p>
</div>
<div style="background: white; padding: 20px; border-radius: 5px; text-align: center;">
<h3><?= $stats['total_users'] ?></h3>
<p>Пользователей</p>
</div>
</div>
<div style="text-align: center; margin: 40px 0;">
<a href="index.php?action=add_product" class="btn btn-success" style="padding: 15px 30px; font-size: 16px;">
<i class="fas fa-plus"></i> Добавить новый товар
</a>
<a href="index.php?action=add_category" class="btn btn-primary" style="padding: 15px 30px; font-size: 16px;">
<i class="fas fa-plus"></i> Добавить категорию
</a>
</div>
<?php elseif ($action == 'products'): ?>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>Управление товарами</h2>
<div>
<a href="index.php?action=add_product" class="btn btn-success">
<i class="fas fa-plus"></i> Добавить товар
</a>
<?php if (isset($_GET['show_all'])): ?>
<a href="index.php?action=products" class="btn btn-primary">Только активные</a>
<?php else: ?>
<a href="index.php?action=products&show_all=1" class="btn btn-primary">Показать все</a>
<?php endif; ?>
</div>
</div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Название</th>
<th>Категория</th>
<th>Цена</th>
<th>На складе</th>
<th>Статус</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $product): ?>
<tr>
<td><?= $product['product_id'] ?></td>
<td><?= htmlspecialchars($product['name']) ?></td>
<td><?= htmlspecialchars($product['category_name'] ?? 'Без категории') ?></td>
<td><?= number_format($product['price'], 0, '', ' ') ?> ₽</td>
<td><?= $product['stock_quantity'] ?></td>
<td>
<?php if ($product['is_available'] && $product['stock_quantity'] > 0): ?>
<span style="color: green;">✓ Доступен</span>
<?php elseif (!$product['is_available']): ?>
<span style="color: red;">✗ Недоступен</span>
<?php else: ?>
<span style="color: orange;">⚠ Нет на складе</span>
<?php endif; ?>
</td>
<td class="action-buttons">
<a href="index.php?action=edit_product&id=<?= $product['product_id'] ?>" class="btn btn-warning btn-sm">
<i class="fas fa-edit"></i>
</a>
<?php if ($product['is_available']): ?>
<form method="POST" style="display: inline;">
<input type="hidden" name="action" value="edit_product">
<input type="hidden" name="product_id" value="<?= $product['product_id'] ?>">
<input type="hidden" name="is_available" value="0">
<button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Сделать недоступным?')">
<i class="fas fa-times"></i>
</button>
</form>
<?php else: ?>
<form method="POST" style="display: inline;">
<input type="hidden" name="action" value="edit_product">
<input type="hidden" name="product_id" value="<?= $product['product_id'] ?>">
<input type="hidden" name="is_available" value="1">
<button type="submit" class="btn btn-success btn-sm" onclick="return confirm('Сделать доступным?')">
<i class="fas fa-check"></i>
</button>
</form>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php elseif ($action == 'categories'): ?>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>Управление категориями</h2>
<a href="index.php?action=add_category" class="btn btn-success">
<i class="fas fa-plus"></i> Добавить категорию
</a>
</div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Название</th>
<th>Slug</th>
<th>Родительская</th>
<th>Товаров</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $category): ?>
<tr>
<td><?= $category['category_id'] ?></td>
<td><?= htmlspecialchars($category['name']) ?></td>
<td><?= htmlspecialchars($category['slug']) ?></td>
<td><?= htmlspecialchars($category['parent_name'] ?? '—') ?></td>
<td><?= $category['product_count'] ?> </td>
<td class="action-buttons">
<a href="index.php?action=edit_category&id=<?= $category['category_id'] ?>" class="btn btn-warning btn-sm">
<i class="fas fa-edit"></i> Редактировать
</a>
<button type="button" class="btn btn-danger btn-sm delete-category-btn"
data-id="<?= $category['category_id'] ?>"
data-has-products="<?= $category['product_count'] > 0 ? '1' : '0' ?>">
<i class="fas fa-trash"></i> Удалить
</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php elseif (in_array($action, ['add_product', 'edit_product'])): ?>
<div class="form-container">
<h2><?= $action == 'add_product' ? 'Добавление товара' : 'Редактирование товара' ?></h2>
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="hidden" name="action" value="<?= $action == 'edit_product' ? 'edit_product' : 'add_product' ?>">
<?php if (isset($edit_data)): ?>
<input type="hidden" name="product_id" value="<?= $edit_data['product_id'] ?>">
<?php endif; ?>
<div class="form-group">
<label>Название товара *</label>
<input type="text" name="name" class="form-control"
value="<?= htmlspecialchars($edit_data['name'] ?? '') ?>" required>
</div>
<div class="form-group">
<label>Категория *</label>
<select name="category_id" class="form-control" required>
<option value="">Выберите категорию</option>
<?php foreach ($allCategories as $cat): ?>
<option value="<?= $cat['category_id'] ?>"
<?= (isset($edit_data['category_id']) && $edit_data['category_id'] == $cat['category_id']) ? 'selected' : '' ?>>
<?= htmlspecialchars($cat['name']) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Описание</label>
<textarea name="description" class="form-control" rows="4"><?= htmlspecialchars($edit_data['description'] ?? '') ?></textarea>
</div>
<div style="display: flex; gap: 15px;">
<div class="form-group" style="flex: 1;">
<label>Цена *</label>
<input type="number" name="price" class="form-control" min="0" step="0.01"
value="<?= $edit_data['price'] ?? '' ?>" required>
</div>
<div class="form-group" style="flex: 1;">
<label>Старая цена (для скидки)</label>
<input type="number" name="old_price" class="form-control" min="0" step="0.01"
value="<?= $edit_data['old_price'] ?? '' ?>">
</div>
</div>
<div style="display: flex; gap: 15px;">
<div class="form-group" style="flex: 1;">
<label>Артикул (SKU)</label>
<input type="text" name="sku" class="form-control"
value="<?= htmlspecialchars($edit_data['sku'] ?? '') ?>"
placeholder="Оставьте пустым для автогенерации">
</div>
<div class="form-group" style="flex: 1;">
<label>Количество на складе</label>
<input type="number" name="stock_quantity" class="form-control" min="0"
value="<?= $edit_data['stock_quantity'] ?? 0 ?>">
</div>
</div>
<div class="form-group">
<label>URL изображения</label>
<input type="text" name="image_url" class="form-control"
value="<?= htmlspecialchars($edit_data['image_url'] ?? '') ?>"
placeholder="Например: img2/product.jpg">
</div>
<div style="display: flex; gap: 15px;">
<div class="form-group" style="flex: 1;">
<label>Цвет</label>
<input type="text" name="color" class="form-control"
value="<?= htmlspecialchars($edit_data['color'] ?? '') ?>">
</div>
<div class="form-group" style="flex: 1;">
<label>Материал</label>
<input type="text" name="material" class="form-control"
value="<?= htmlspecialchars($edit_data['material'] ?? '') ?>">
</div>
</div>
<div class="form-group">
<label>
<input type="checkbox" name="is_available" value="1"
<?= (!isset($edit_data['is_available']) || $edit_data['is_available']) ? 'checked' : '' ?>>
Товар доступен
</label>
</div>
<div class="form-group">
<label>
<input type="checkbox" name="is_featured" value="1"
<?= (isset($edit_data['is_featured']) && $edit_data['is_featured']) ? 'checked' : '' ?>>
Рекомендуемый товар
</label>
</div>
<button type="submit" class="btn btn-success">
<?= $action == 'add_product' ? 'Добавить товар' : 'Сохранить изменения' ?>
</button>
<a href="index.php?action=products" class="btn btn-primary">Отмена</a>
</form>
</div>
<?php elseif (in_array($action, ['add_category', 'edit_category'])): ?>
<div class="form-container">
<h2><?= $action == 'add_category' ? 'Добавление категории' : 'Редактирование категории' ?></h2>
<form method="POST" action="index.php" id="categoryForm">
<input type="hidden" name="action" value="<?= $action == 'edit_category' ? 'edit_category' : 'add_category' ?>">
<?php if (isset($edit_data)): ?>
<input type="hidden" name="category_id" value="<?= $edit_data['category_id'] ?>">
<?php endif; ?>
<div class="form-group">
<label>Название категории *</label>
<input type="text" name="name" class="form-control"
value="<?= htmlspecialchars($edit_data['name'] ?? '') ?>" required>
</div>
<div class="form-group">
<label>Родительская категория</label>
<select name="parent_id" class="form-control">
<option value="">Без родительской категории</option>
<?php foreach ($parentCategories as $cat): ?>
<?php if (!isset($edit_data['category_id']) || $cat['category_id'] != $edit_data['category_id']): ?>
<option value="<?= $cat['category_id'] ?>"
<?= (isset($edit_data['parent_id']) && $edit_data['parent_id'] == $cat['category_id']) ? 'selected' : '' ?>>
<?= htmlspecialchars($cat['name']) ?>
</option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Описание</label>
<textarea name="description" class="form-control" rows="3"><?= htmlspecialchars($edit_data['description'] ?? '') ?></textarea>
</div>
<div class="form-group">
<label>Порядок сортировки</label>
<input type="number" name="sort_order" class="form-control" min="0" max="100"
value="<?= $edit_data['sort_order'] ?? 0 ?>">
</div>
<div class="form-group">
<label>
<input type="checkbox" name="is_active" value="1"
<?= (!isset($edit_data['is_active']) || $edit_data['is_active']) ? 'checked' : '' ?>>
Активна
</label>
</div>
<button type="submit" class="btn btn-primary">
<?= $action == 'add_category' ? 'Добавить категорию' : 'Сохранить изменения' ?>
</button>
<a href="index.php?action=categories" class="btn">Отмена</a>
</form>
</div>
<?php elseif ($action == 'orders'): ?>
<h2>Заказы</h2>
<table>
<thead>
<tr>
<th>№ заказа</th>
<th>Клиент</th>
<th>Сумма</th>
<th>Статус</th>
<th>Дата</th>
<th>Действия</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $order): ?>
<tr>
<td><?= htmlspecialchars($order['order_number']) ?></td>
<td><?= htmlspecialchars($order['customer_name']) ?></td>
<td><?= number_format($order['final_amount'], 0, '', ' ') ?> ₽</td>
<td><?= htmlspecialchars($order['status']) ?></td>
<td><?= date('d.m.Y H:i', strtotime($order['created_at'])) ?></td>
<td>
<a href="index.php?action=order_details&id=<?= $order['order_id'] ?>" class="btn btn-primary btn-sm">
<i class="fas fa-eye"></i>
</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php elseif ($action == 'users'): ?>
<h2>Пользователи</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Email</th>
<th>ФИО</th>
<th>Дата регистрации</th>
<th>Статус</th>
</tr>
</thead>
<tbody>
<?php foreach ($data as $user): ?>
<tr>
<td><?= $user['user_id'] ?></td>
<td><?= htmlspecialchars($user['email']) ?></td>
<td><?= htmlspecialchars($user['full_name']) ?></td>
<td><?= date('d.m.Y', strtotime($user['created_at'])) ?></td>
<td>
<?php if ($user['is_active']): ?>
<span style="color: green;">✓ Активен</span>
<?php else: ?>
<span style="color: red;">✗ Неактивен</span>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php elseif ($action == 'order_details'): ?>
<?php if (isset($order) && $order): ?>
<div style="margin-bottom: 20px;">
<a href="index.php?action=orders" class="btn btn-primary">
<i class="fas fa-arrow-left"></i> Назад к заказам
</a>
</div>
<h2>Детали заказа #<?= htmlspecialchars($order['order_number']) ?></h2>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
<!-- Информация о заказе -->
<div style="background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);">
<h3 style="margin-top: 0;">Информация о заказе</h3>
<table style="width: 100%; border: none;">
<tr>
<td style="border: none; padding: 8px 0;"><strong>Номер заказа:</strong></td>
<td style="border: none; padding: 8px 0;"><?= htmlspecialchars($order['order_number']) ?></td>
</tr>
<tr>
<td style="border: none; padding: 8px 0;"><strong>Дата создания:</strong></td>
<td style="border: none; padding: 8px 0;"><?= date('d.m.Y H:i', strtotime($order['created_at'])) ?></td>
</tr>
<tr>
<td style="border: none; padding: 8px 0;"><strong>Статус:</strong></td>
<td style="border: none; padding: 8px 0;">
<span style="padding: 5px 10px; border-radius: 4px; background:
<?php
echo match($order['status']) {
'pending' => '#ffc107',
'processing' => '#17a2b8',
'completed' => '#28a745',
'cancelled' => '#dc3545',
default => '#6c757d'
};
?>; color: white;">
<?= htmlspecialchars($order['status']) ?>
</span>
</td>
</tr>
<tr>
<td style="border: none; padding: 8px 0;"><strong>Способ оплаты:</strong></td>
<td style="border: none; padding: 8px 0;"><?= $order['payment_method'] == 'card' ? 'Банковская карта' : 'Наличные' ?></td>
</tr>
<tr>
<td style="border: none; padding: 8px 0;"><strong>Способ доставки:</strong></td>
<td style="border: none; padding: 8px 0;"><?= $order['delivery_method'] == 'courier' ? 'Курьерская доставка' : 'Самовывоз' ?></td>
</tr>
</table>
</div>
<!-- Информация о клиенте -->
<div style="background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);">
<h3 style="margin-top: 0;">Информация о клиенте</h3>
<table style="width: 100%; border: none;">
<tr>
<td style="border: none; padding: 8px 0;"><strong>ФИО:</strong></td>
<td style="border: none; padding: 8px 0;"><?= htmlspecialchars($order['customer_name']) ?></td>
</tr>
<tr>
<td style="border: none; padding: 8px 0;"><strong>Email:</strong></td>
<td style="border: none; padding: 8px 0;"><?= htmlspecialchars($order['customer_email']) ?></td>
</tr>
<tr>
<td style="border: none; padding: 8px 0;"><strong>Телефон:</strong></td>
<td style="border: none; padding: 8px 0;"><?= htmlspecialchars($order['customer_phone']) ?></td>
</tr>
<tr>
<td style="border: none; padding: 8px 0;"><strong>Регион:</strong></td>
<td style="border: none; padding: 8px 0;"><?= htmlspecialchars($order['delivery_region'] ?? '—') ?></td>
</tr>
<tr>
<td style="border: none; padding: 8px 0;"><strong>Адрес доставки:</strong></td>
<td style="border: none; padding: 8px 0;"><?= htmlspecialchars($order['delivery_address']) ?></td>
</tr>
<?php if (!empty($order['postal_code'])): ?>
<tr>
<td style="border: none; padding: 8px 0;"><strong>Индекс:</strong></td>
<td style="border: none; padding: 8px 0;"><?= htmlspecialchars($order['postal_code']) ?></td>
</tr>
<?php endif; ?>
</table>
</div>
</div>
<!-- Товары в заказе -->
<div style="background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); margin-bottom: 20px;">
<h3 style="margin-top: 0;">Товары в заказе</h3>
<table>
<thead>
<tr>
<th>Изображение</th>
<th>Товар</th>
<th>Цена</th>
<th>Количество</th>
<th>Сумма</th>
</tr>
</thead>
<tbody>
<?php foreach ($order_items as $item): ?>
<tr>
<td>
<?php if (!empty($item['image_url'])): ?>
<img src="/cite_practica/<?= htmlspecialchars($item['image_url']) ?>"
alt="<?= htmlspecialchars($item['product_name']) ?>"
style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px;">
<?php else: ?>
<div style="width: 60px; height: 60px; background: #f0f0f0; display: flex; align-items: center; justify-content: center; border-radius: 4px;">
<i class="fas fa-image" style="color: #ccc;"></i>
</div>
<?php endif; ?>
</td>
<td><?= htmlspecialchars($item['product_name']) ?></td>
<td><?= number_format($item['product_price'], 0, '', ' ') ?> ₽</td>
<td><?= $item['quantity'] ?> шт.</td>
<td><?= number_format($item['total_price'], 0, '', ' ') ?> ₽</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<!-- Итоговая сумма -->
<div style="background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); max-width: 400px; margin-left: auto;">
<h3 style="margin-top: 0;">Итого</h3>
<table style="width: 100%; border: none;">
<tr>
<td style="border: none; padding: 8px 0;">Товары:</td>
<td style="border: none; padding: 8px 0; text-align: right;"><?= number_format($order['subtotal'], 0, '', ' ') ?> ₽</td>
</tr>
<?php if ($order['discount_amount'] > 0): ?>
<tr>
<td style="border: none; padding: 8px 0;">Скидка:</td>
<td style="border: none; padding: 8px 0; text-align: right; color: #28a745;">-<?= number_format($order['discount_amount'], 0, '', ' ') ?> ₽</td>
</tr>
<?php endif; ?>
<tr>
<td style="border: none; padding: 8px 0;">Доставка:</td>
<td style="border: none; padding: 8px 0; text-align: right;"><?= number_format($order['delivery_price'], 0, '', ' ') ?> ₽</td>
</tr>
<tr style="font-size: 18px; font-weight: bold;">
<td style="border: none; padding: 12px 0; border-top: 2px solid #ddd;">Итого к оплате:</td>
<td style="border: none; padding: 12px 0; text-align: right; border-top: 2px solid #ddd;"><?= number_format($order['final_amount'], 0, '', ' ') ?> ₽</td>
</tr>
</table>
</div>
<?php if (!empty($order['notes'])): ?>
<div style="background: white; padding: 20px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); margin-top: 20px;">
<h3 style="margin-top: 0;">Примечания</h3>
<p><?= htmlspecialchars($order['notes']) ?></p>
</div>
<?php endif; ?>
<?php else: ?>
<div class="alert alert-danger">
<i class="fas fa-exclamation-circle"></i> Заказ не найден
</div>
<a href="index.php?action=orders" class="btn btn-primary">Вернуться к списку заказов</a>
<?php endif; ?>
<?php endif; ?>
</div>
<script>
$(document).ready(function() {
$('.delete-category-btn').click(function() {
const categoryId = $(this).data('id');
const btn = $(this);
if (confirm('Удалить эту категорию?')) {
$.ajax({
url: 'fix_delete_category.php',
method: 'POST',
data: { category_id: categoryId },
dataType: 'json',
success: function(result) {
if (result.success) {
alert(result.message);
location.reload();
} else {
alert('Ошибка: ' + result.message);
}
},
error: function(xhr, status, error) {
console.error('AJAX error:', status, error);
alert('Ошибка при удалении категории: ' + error);
}
});
}
});
$('#categoryForm').submit(function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
method: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function(result) {
if (result.success) {
alert(result.message);
window.location.href = 'index.php?action=categories';
} else {
alert('Ошибка: ' + result.message);
}
},
error: function(xhr, status, error) {
console.error('AJAX error:', status, error);
alert('Ошибка при сохранении категории');
}
});
});
});
</script>
</body>
</html>