<?php
// index.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'] ?? '';

// Обработка POST запросов - ДОБАВЛЕНО ПРОСТОЕ И РАБОТАЮЩЕЕ!
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();
            }
        }

         // ИСПРАВЬТЕ БЛОК edit_category или добавьте его если его нет:
                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');


            // ВАЖНО: Проверяем category_id
            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');

            // Генерируем SKU если пустой
            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();
            }
        }

        // ИСПРАВЛЕННЫЙ КОД для edit_product в index.php:
        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); // ПО УМОЛЧАНИЮ 1, чтобы избежать 0
            $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'] ?? '');

            // ВАЖНО: Проверяем category_id
            if ($category_id <= 0) {
                // Если 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']);

                    // 1. Проверяем, есть ли товары в этой категории
                    $checkProducts = $db->prepare("SELECT COUNT(*) FROM products WHERE category_id = ?");
                    $checkProducts->execute([$categoryId]);
                    $productCount = $checkProducts->fetchColumn();

                    // 2. Проверяем, есть ли дочерние категории
                    $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;

    }

} 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" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <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="../catalog.php" class="btn btn-primary" style="margin-left: 10px;">В каталог</a>
            <a href="../logout.php" class="btn btn-danger" style="margin-left: 10px;">Выйти</a>
        </div>
    </div>

    <div class="admin-tabs">
        <a href="?action=dashboard" class="admin-tab <?= $action == 'dashboard' ? 'active' : '' ?>">
            <i class="fas fa-tachometer-alt"></i> Дашборд
        </a>
        <a href="?action=products" class="admin-tab <?= $action == 'products' ? 'active' : '' ?>">
            <i class="fas fa-box"></i> Товары
        </a>
        <a href="?action=categories" class="admin-tab <?= $action == 'categories' ? 'active' : '' ?>">
            <i class="fas fa-tags"></i> Категории
        </a>
        <a href="?action=orders" class="admin-tab <?= $action == 'orders' ? 'active' : '' ?>">
            <i class="fas fa-shopping-cart"></i> Заказы
        </a>
        <a href="?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="?action=add_product" class="btn btn-success" style="padding: 15px 30px; font-size: 16px;">
                <i class="fas fa-plus"></i> Добавить новый товар
            </a>
            <a href="?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="?action=add_product" class="btn btn-success">
                    <i class="fas fa-plus"></i> Добавить товар
                </a>
                <?php if (isset($_GET['show_all'])): ?>
                <a href="?action=products" class="btn btn-primary">Только активные</a>
                <?php else: ?>
                <a href="?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="?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="?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="?action=edit_category&id=<?= $category['category_id'] ?>" class="btn btn-warning btn-sm">
                            <i class="fas fa-edit"></i> Редактировать
                        </a>

                        <!-- Кнопка удаления с AJAX -->
                        <button type="button" class="btn btn-danger btn-sm delete-category-btn"
                                data-id="<?= $category['category_id'] ?>"
                                <?= $category['product_count'] > 0 ? 'disabled' : '' ?>>
                            <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="?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="?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="?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 endif; ?>
    </div>
<script>
// Удаление категории через AJAX
$('.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 },
            success: function(response) {
                const result = JSON.parse(response);
                if (result.success) {
                    alert(result.message);
                    location.reload();
                } else {
                    alert('Ошибка: ' + result.message);
                }
            }
        });
    }
});

// Обработка формы категории
$('#categoryForm').submit(function(e) {
    e.preventDefault();

    $.ajax({
        url: $(this).attr('action'),
        method: 'POST',
        data: $(this).serialize(),
        success: function(response) {
            const result = JSON.parse(response);
            if (result.success) {
                alert(result.message);
                window.location.href = 'index.php?action=categories';
            } else {
                alert('Ошибка: ' + result.message);
            }
        }
    });
});
</script>
</body>
</html>