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

// Initialize variables
$errors = [];
$success = '';
$category = null;

// Fetch category data
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    $errors[] = "Invalid category ID.";
} else {
    $stmt = $conn->prepare("SELECT id, name, description, image, status FROM product_category WHERE id = ?");
    $stmt->bind_param("i", $_GET['id']);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows === 0) {
        $errors[] = "Category not found.";
    } else {
        $category = $result->fetch_assoc();
    }
    $stmt->close();
}

// Handle Category Update Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $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 = $category['image']; // Keep existing image if no new upload
    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.";
            } else {
                // Delete old image if it exists and is different
                if (!empty($category['image']) && file_exists($category['image']) && $category['image'] !== $category_image_path) {
                    unlink($category['image']);
                }
            }
        }
    }

    // If no errors, update the category and products
    if (empty($errors)) {
        $conn->begin_transaction(); // Start transaction to ensure atomic updates
        try {
            // Update category
            $stmt = $conn->prepare("UPDATE product_category SET name = ?, description = ?, image = ?, status = ? WHERE id = ?");
            $stmt->bind_param("ssssi", $category_name, $category_description, $category_image_path, $category_status, $category['id']);
            if (!$stmt->execute()) {
                throw new Exception("Failed to update category: " . $conn->error);
            }
            $stmt->close();

            // If category name changed, update products
            if ($category_name !== $category['name']) {
                $stmt = $conn->prepare("UPDATE products SET category = ? WHERE category = ?");
                $stmt->bind_param("ss", $category_name, $category['name']);
                if (!$stmt->execute()) {
                    throw new Exception("Failed to update products: " . $conn->error);
                }
                $stmt->close();
            }

            $conn->commit();
            $success = "Category updated successfully!";
            // Refresh category data
            $stmt = $conn->prepare("SELECT id, name, description, image, status FROM product_category WHERE id = ?");
            $stmt->bind_param("i", $category['id']);
            $stmt->execute();
            $category = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            $_POST = []; // Reset form fields
            echo "<script>document.getElementById('category_image').value = '';</script>";
        } catch (Exception $e) {
            $conn->rollback();
            $errors[] = $e->getMessage();
        }
    }
}
?>

<!-- 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 { transition: transform 0.2s ease, box-shadow 0.2s ease; }
        .form-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; }
        img.current-image { max-width: 100px; height: auto; }
        @media (max-width: 768px) {
            .content { margin-left: 0; }
            .content.open { margin-left: 0; }
            .search { display: none; }
            img.current-image { 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>

    <!-- Edit Category Form -->
    <div class="form-section bg-white p-6 rounded-lg shadow-md w-full max-w-md my-6 mx-auto">
        <h2 class="text-xl font-semibold text-gray-900 mb-4">Edit Category</h2>
        
        <!-- Success/Error Messages -->
        <?php if ($success): ?>
            <p class="success text-center mb-4"><?php echo htmlspecialchars($success); ?></p>
        <?php endif; ?>
        <?php if (!empty($errors)): ?>
            <ul class="error mb-4">
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        <?php endif; ?>

        <?php if ($category): ?>
            <!-- Category Form -->
            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                <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']) : htmlspecialchars($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']) : htmlspecialchars($category['description'] ?? ''); ?></textarea>
                </div>
                <div>
                    <label for="category_image" class="block text-sm font-medium text-gray-700">Category Image (Optional - Current: <?php if ($category['image']): ?><img src="<?php echo htmlspecialchars($category['image']); ?>" alt="Current Image" class="current-image inline rounded-md"><?php else: ?>No Image<?php endif; ?>)</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') || (!isset($_POST['category_status']) && $category['status'] == 'active') ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo (isset($_POST['category_status']) && $_POST['category_status'] == 'inactive') || (!isset($_POST['category_status']) && $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">Update Category</button>
                </div>
            </form>
        <?php else: ?>
            <p class="text-center text-gray-700">No category found to edit.</p>
        <?php endif; ?>
    </div>
</div>

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