<?php
include "include/db.php"; // Include database connection
include "include/header.php";

// Initialize variables for form submission
$errors = [];
$success = '';

// Handle Category Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_category'])) {
    $category_name = trim($_POST['category_name'] ?? '');
    $category_description = trim($_POST['category_description'] ?? '') ?: null;
    $category_status = trim($_POST['category_status'] ?? '') ?: null;
    
    // Category validation
    if (empty($category_name)) $errors[] = "Category Name is required.";
    if ($category_status && !in_array($category_status, ['active', 'inactive'])) $errors[] = "Category Status must be 'active' or 'inactive'.";
    
    // Category image upload handling (optional)
    $category_image_path = null;
    if (isset($_FILES['category_image']) && $_FILES['category_image']['error'] === UPLOAD_ERR_OK) {
        $image_name = $_FILES['category_image']['name'];
        $image_tmp = $_FILES['category_image']['tmp_name'];
        $image_ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
        $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];
        if (!in_array($image_ext, $allowed_exts)) {
            $errors[] = "Only JPG, JPEG, PNG, or GIF files are allowed for category image.";
        } else {
            $upload_dir = 'uploads/';
            $category_image_path = $upload_dir . uniqid() . '.' . $image_ext;
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
            if (!move_uploaded_file($image_tmp, $category_image_path)) {
                $errors[] = "Failed to upload category image.";
            }
        }
    }

    // If no errors, save to database
    if (empty($errors)) {
        $stmt = $conn->prepare("INSERT INTO product_category (name, description, image, status) VALUES (?, ?, ?, ?)");
        $stmt->bind_param("ssss", $category_name, $category_description, $category_image_path, $category_status);
        if ($stmt->execute()) {
            $success = "Category added successfully!";
            $_POST = []; // Reset form fields
            echo "<script>document.getElementById('category_image').value = '';</script>";
        } else {
            $errors[] = "Failed to save category to database: " . $conn->error;
        }
        $stmt->close();
    }
}

// Handle Category Deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_category'])) {
    $category_id = trim($_POST['category_id'] ?? '');
    if (empty($category_id) || !is_numeric($category_id)) {
        $errors[] = "Invalid category ID.";
    } else {
        // Check if category exists
        $stmt = $conn->prepare("SELECT image, name FROM product_category WHERE id = ?");
        $stmt->bind_param("i", $category_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows === 0) {
            $errors[] = "Category not found.";
        } else {
            $category = $result->fetch_assoc();
            $image_path = $category['image'];
            $category_name = $category['name'];
            // Check if category is used in products
            $stmt = $conn->prepare("SELECT id FROM products WHERE category = ?");
            $stmt->bind_param("s", $category_name);
            $stmt->execute();
            if ($stmt->get_result()->num_rows > 0) {
                $errors[] = "Cannot delete category because it is used by products.";
            } else {
                // Delete category
                $stmt = $conn->prepare("DELETE FROM product_category WHERE id = ?");
                $stmt->bind_param("i", $category_id);
                if ($stmt->execute()) {
                    $success = "Category deleted successfully!";
                    // Delete associated image file
                    if (!empty($image_path) && file_exists($image_path)) {
                        unlink($image_path);
                    }
                } else {
                    $errors[] = "Failed to delete category: " . $conn->error;
                }
            }
        }
        $stmt->close();
    }
}

// Fetch all categories
$result = $conn->query("SELECT id, name, description, image, status, created_at, updated_at FROM product_category ORDER BY created_at DESC");
$categories = $result->fetch_all(MYSQLI_ASSOC);
?>

<!-- Content -->
<div id="content" class="content ml-64 p-6 min-h-screen">
    <style>
        /* Tailwind CSS CDN (embedded for top-class design) */
        @import url('https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css');

        /* Custom styles for enhanced design */
        body { overflow-x: hidden; font-family: 'Inter', sans-serif; }
        .content { transition: margin-left 0.3s ease; }
        .form-section, .table-section { transition: transform 0.2s ease, box-shadow 0.2s ease; }
        .form-section:hover, .table-section:hover { transform: translateY(-5px); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15); }
        .top-nav { background: linear-gradient(90deg, #1F2937, #374151); }
        input, textarea, select { transition: all 0.2s ease; }
        input:focus, textarea:focus, select:focus { ring: 2px solid #F59E0B; }
        .error { color: #DC2626; }
        .success { color: #10B981; font-size: 1.25rem; font-weight: bold; }
        table { width: 100%; border-collapse: separate; border-spacing: 0; }
        th, td { padding: 12px; text-align: left; }
        th { background: #1F2937; color: white; }
        tr:nth-child(even) { background: #F9FAFB; }
        tr:hover { background: #E5E7EB; }
        img { max-width: 100px; height: auto; }
        .split-container { display: flex; gap: 2rem; }
        .form-section { flex: 1; max-width: 500px; }
        .table-section { flex: 2; }
        @media (max-width: 1024px) {
            .split-container { flex-direction: column; }
            .form-section, .table-section { max-width: 100%; }
        }
        @media (max-width: 768px) {
            .content { margin-left: 0; }
            .content.open { margin-left: 0; }
            .search { display: none; }
            table { font-size: 0.875rem; }
            img { max-width: 60px; }
        }
        @media (min-width: 769px) {
            .content { margin-left: 250px; }
        }
    </style>

    <!-- Top Nav -->
    <nav class="top-nav sticky top-0 text-white p-4 flex justify-between items-center shadow-lg z-40">
        <div class="logo text-2xl font-bold">CourseLMS Admin</div>
        <div class="search flex-1 max-w-xs mx-4">
            <input type="text" placeholder="Search products or categories..." class="w-full p-2 border border-gray-300 rounded-md bg-white text-gray-900 focus:outline-none focus:ring-2 focus:ring-yellow-500">
        </div>
        <div class="right-nav flex items-center gap-4">
            <i class="fas fa-bell text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Notifications"></i>
            <i class="fas fa-envelope text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Messages"></i>
            <div class="profile flex items-center gap-2">
                <img src="https://via.placeholder.com/40" alt="Profile" class="w-10 h-10 rounded-full">
                <span class="text-white">Admin</span>
            </div>
            <i id="toggle" class="fas fa-bars text-xl p-2 rounded-full hover:bg-yellow-500 cursor-pointer" title="Toggle Menu"></i>
        </div>
    </nav>

    <!-- Split Layout: Add Category Form (Left) and Categories Table (Right) -->
    <div class="split-container my-6">
        <!-- Add Category Form -->
        <div class="form-section bg-white p-6 rounded-lg shadow-md">
            <h2 class="text-xl font-semibold text-gray-900 mb-4">Add New Category</h2>
            
            <!-- Success/Error Messages -->
            <?php if ($success && isset($_POST['add_category'])): ?>
                <p class="success text-center mb-4"><?php echo htmlspecialchars($success); ?></p>
            <?php endif; ?>
            <?php if (!empty($errors) && isset($_POST['add_category'])): ?>
                <ul class="error mb-4">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>

            <!-- Category Form -->
            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                <input type="hidden" name="add_category" value="1">
                <div>
                    <label for="category_name" class="block text-sm font-medium text-gray-700">Category Name</label>
                    <input type="text" id="category_name" name="category_name" value="<?php echo isset($_POST['category_name']) ? htmlspecialchars($_POST['category_name']) : ''; ?>" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                </div>
                <div>
                    <label for="category_description" class="block text-sm font-medium text-gray-700">Description (Optional)</label>
                    <textarea id="category_description" name="category_description" rows="4" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500"><?php echo isset($_POST['category_description']) ? htmlspecialchars($_POST['category_description']) : ''; ?></textarea>
                </div>
                <div>
                    <label for="category_image" class="block text-sm font-medium text-gray-700">Category Image (Optional)</label>
                    <input type="file" id="category_image" name="category_image" accept="image/*" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
                </div>
                <div>
                    <label for="category_status" class="block text-sm font-medium text-gray-700">Status (Optional)</label>
                    <select id="category_status" name="category_status" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500">
                        <option value="">Select status</option>
                        <option value="active" <?php echo isset($_POST['category_status']) && $_POST['category_status'] == 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo isset($_POST['category_status']) && $_POST['category_status'] == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
                <div>
                    <button type="submit" class="w-full bg-yellow-500 text-white p-2 rounded-md hover:bg-yellow-600 transition-colors">Add Category</button>
                </div>
            </form>
        </div>

        <!-- Categories Table -->
        <div class="table-section bg-white p-6 rounded-lg shadow-md">
            <h2 class="text-xl font-semibold text-gray-900 mb-4">All Categories</h2>
            
            <!-- Success/Error Messages -->
            <?php if ($success && !isset($_POST['add_category'])): ?>
                <p class="success text-center mb-4"><?php echo htmlspecialchars($success); ?></p>
            <?php endif; ?>
            <?php if (!empty($errors) && !isset($_POST['add_category'])): ?>
                <ul class="error mb-4">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>

            <!-- Categories Table -->
            <div class="overflow-x-auto">
                <table class="min-w-full">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Description</th>
                            <th>Image</th>
                            <th>Status</th>
                            <th>Created At</th>
                            <th>Updated At</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($categories)): ?>
                            <tr>
                                <td colspan="8" class="text-center py-4">No categories found.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($categories as $category): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($category['id']); ?></td>
                                    <td><?php echo htmlspecialchars($category['name']); ?></td>
                                    <td><?php echo htmlspecialchars(substr($category['description'] ?? '', 0, 50)) . (strlen($category['description'] ?? '') > 50 ? '...' : ''); ?></td>
                                    <td>
                                        <?php if ($category['image']): ?>
                                            <img src="<?php echo htmlspecialchars($category['image']); ?>" alt="Category Image" class="rounded-md">
                                        <?php else: ?>
                                            No Image
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($category['status'] ?? 'N/A'); ?></td>
                                    <td><?php echo htmlspecialchars($category['created_at']); ?></td>
                                    <td><?php echo htmlspecialchars($category['updated_at']); ?></td>
                                    <td class="flex gap-2">
                                        <a href="edit_category.php?id=<?php echo htmlspecialchars($category['id']); ?>" class="bg-blue-900 text-white px-3 py-1 rounded-md hover:bg-blue-800 transition-colors">Edit</a>
                                        <form method="POST" onsubmit="return confirm('Are you sure you want to delete this category?');">
                                            <input type="hidden" name="category_id" value="<?php echo htmlspecialchars($category['id']); ?>">
                                            <input type="hidden" name="delete_category" value="1">
                                            <button type="submit" class="bg-red-600 text-white px-3 py-1 rounded-md hover:bg-red-700 transition-colors">Delete</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php
include "include/footer.php";
$conn->close(); // Close database connection
?>