<?php
session_start();
include_once('../includes/db.php');

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin_login.php");
    exit;
}

$categories = fetchAll("SELECT * FROM categories");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitize($_POST['name']);
    $image = '';

    if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $imageName = uniqid("cat_", true) . '.' . $ext;

        $uploadDir = '../uploads/category_images/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $uploadPath = $uploadDir . $imageName;

        if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadPath)) {
            $image = 'uploads/category_images/' . $imageName;
        } else {
            $error = "❌ Failed to upload image.";
        }
    }

    if (!isset($error)) {
        $query = "INSERT INTO categories (name, image) VALUES (?, ?)";
        if (execute($query, [$name, $image])) {
            $success = "✅ Category added successfully.";
            $categories = fetchAll("SELECT * FROM categories");
        } else {
            $error = "❌ Error adding category.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Categories - PrintShop Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f1f5f9;
        }
        .main-content {
            margin-left: 250px;
            padding: 30px;
        }
        .card {
            border-radius: 1rem;
        }
        .form-label {
            font-weight: 500;
        }
        .category-box {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .category-box img {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
        }
    </style>
</head>
<body>

<div class="d-flex">
    <!-- Sidebar -->
    <?php include('admin_sidebar.php'); ?>

    <!-- Main Content -->
    <div class="main-content flex-grow-1">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-dark text-white rounded-top">
                <h4 class="mb-0">📁 Manage Categories</h4>
            </div>
            <div class="card-body">
                <?php if (isset($success)): ?>
                    <div class="alert alert-success"><?= $success ?></div>
                <?php elseif (isset($error)): ?>
                    <div class="alert alert-danger"><?= $error ?></div>
                <?php endif; ?>

                <form method="post" enctype="multipart/form-data" class="row g-3 mb-4">
                    <div class="col-md-5">
                        <input type="text" name="name" class="form-control" placeholder="Enter category name" required>
                    </div>
                    <div class="col-md-5">
                        <input type="file" name="image" class="form-control" accept="image/*">
                    </div>
                    <div class="col-md-2 d-grid">
                        <button type="submit" class="btn btn-primary">Add Category</button>
                    </div>
                </form>

                <h5 class="mb-3">🗂 Existing Categories</h5>
                <ul class="list-group">
                    <?php foreach ($categories as $cat): ?>
                        <li class="list-group-item">
                            <div class="category-box">
                                <?php if (!empty($cat['image'])): ?>
                                    <img src="../<?= htmlspecialchars($cat['image']) ?>" alt="Category Image">
                                <?php endif; ?>
                                <span class="fw-semibold"><?= htmlspecialchars($cat['name']) ?></span>
                            </div>
                        </li>
                    <?php endforeach; ?>
                    <?php if (empty($categories)): ?>
                        <li class="list-group-item text-muted">No categories added yet.</li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
    </div>
</div>

</body>
</html>
