<?php
session_start();
require_once 'db/config.php';

// --- Простая аутентификация ---
$admin_password = 'admin'; // В реальном проекте используйте более надежный способ хранения пароля

$is_authenticated = isset($_SESSION['is_authenticated']) && $_SESSION['is_authenticated'] === true;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
    if ($_POST['password'] === $admin_password) {
        $_SESSION['is_authenticated'] = true;
        header('Location: admin.php');
        exit;
    } else {
        $login_error = 'Неверный пароль';
    }
}

if (!$is_authenticated) {
    ?>
    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Админ-панель - Вход</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container mt-5">
            <div class="row justify-content-center">
                <div class="col-md-4">
                    <h1 class="text-center mb-4">Вход в админ-панель</h1>
                    <form method="POST">
                        <div class="mb-3">
                            <label for="password" class="form-label">Пароль</label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <?php if (isset($login_error)): ?>
                            <div class="alert alert-danger"><?php echo $login_error; ?></div>
                        <?php endif; ?>
                        <button type="submit" class="btn btn-primary w-100">Войти</button>
                    </form>
                </div>
            </div>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// --- Логика CRUD ---

// Добавление букета
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_bouquet'])) {
    $name = $_POST['name'];
    $description = $_POST['description'];
    $price = $_POST['price'];
    $image_url = $_POST['image_url'];

    $pdo = db();
    $stmt = $pdo->prepare('INSERT INTO bouquets (name, description, price, image_url) VALUES (?, ?, ?, ?)');
    $stmt->execute([$name, $description, $price, $image_url]);
    header('Location: admin.php');
    exit;
}

// Редактирование букета
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_bouquet'])) {
    $id = $_POST['id'];
    $name = $_POST['name'];
    $description = $_POST['description'];
    $price = $_POST['price'];
    $image_url = $_POST['image_url'];

    $pdo = db();
    $stmt = $pdo->prepare('UPDATE bouquets SET name = ?, description = ?, price = ?, image_url = ? WHERE id = ?');
    $stmt->execute([$name, $description, $price, $image_url, $id]);
    header('Location: admin.php');
    exit;
}

// Удаление букета
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_bouquet'])) {
    $id = $_POST['id'];
    $pdo = db();
    $stmt = $pdo->prepare('DELETE FROM bouquets WHERE id = ?');
    $stmt->execute([$id]);
    header('Location: admin.php');
    exit;
}


// --- Получение данных ---
$pdo = db();
$bouquets = $pdo->query('SELECT * FROM bouquets ORDER BY id DESC')->fetchAll();

$edit_bouquet_data = null;
if (isset($_GET['edit'])) {
    $id = $_GET['edit'];
    $stmt = $pdo->prepare('SELECT * FROM bouquets WHERE id = ?');
    $stmt->execute([$id]);
    $edit_bouquet_data = $stmt->fetch();
}

?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Админ-панель</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="admin.php">Админ-панель</a>
            <a href="index.php" class="btn btn-outline-light">На сайт</a>
        </div>
    </nav>

    <div class="container mt-5">
        <div class="row">
            <!-- Форма добавления/редактирования -->
            <div class="col-md-4">
                <h3><?php echo $edit_bouquet_data ? 'Редактировать букет' : 'Добавить букет'; ?></h3>
                <form method="POST">
                    <?php if ($edit_bouquet_data): ?>
                        <input type="hidden" name="id" value="<?php echo $edit_bouquet_data['id']; ?>">
                    <?php endif; ?>
                    <div class="mb-3">
                        <label for="name" class="form-label">Название</label>
                        <input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($edit_bouquet_data['name'] ?? ''); ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">Описание</label>
                        <textarea class="form-control" id="description" name="description" rows="3" required><?php echo htmlspecialchars($edit_bouquet_data['description'] ?? ''); ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="price" class="form-label">Цена</label>
                        <input type="number" step="0.01" class="form-control" id="price" name="price" value="<?php echo htmlspecialchars($edit_bouquet_data['price'] ?? ''); ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="image_url" class="form-label">URL изображения</label>
                        <input type="text" class="form-control" id="image_url" name="image_url" value="<?php echo htmlspecialchars($edit_bouquet_data['image_url'] ?? ''); ?>" required>
                    </div>
                    <?php if ($edit_bouquet_data): ?>
                        <button type="submit" name="edit_bouquet" class="btn btn-primary">Сохранить</button>
                        <a href="admin.php" class="btn btn-secondary">Отмена</a>
                    <?php else: ?>
                        <button type="submit" name="add_bouquet" class="btn btn-success">Добавить</button>
                    <?php endif; ?>
                </form>
            </div>

            <!-- Список букетов -->
            <div class="col-md-8">
                <h3>Список букетов</h3>
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Фото</th>
                            <th>Название</th>
                            <th>Цена</th>
                            <th>Действия</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($bouquets as $bouquet): ?>
                        <tr>
                            <td><?php echo $bouquet['id']; ?></td>
                            <td><img src="<?php echo htmlspecialchars($bouquet['image_url']); ?>" alt="" width="50"></td>
                            <td><?php echo htmlspecialchars($bouquet['name']); ?></td>
                            <td><?php echo htmlspecialchars($bouquet['price']); ?></td>
                            <td>
                                <a href="admin.php?edit=<?php echo $bouquet['id']; ?>" class="btn btn-sm btn-primary">Ред.</a>
                                <form method="POST" style="display:inline-block;" onsubmit="return confirm('Вы уверены?');">
                                    <input type="hidden" name="id" value="<?php echo $bouquet['id']; ?>">
                                    <button type="submit" name="delete_bouquet" class="btn btn-sm btn-danger">Удал.</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
