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

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

// Handle Category Form Submission (Modal)
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)) $category_errors[] = "Category Name is required.";
    if ($category_status && !in_array($category_status, ['active', 'inactive'])) $category_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)) {
            $category_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)) {
                $category_errors[] = "Failed to upload category image.";
            }
        }
    }

    // If no category errors, save to database
    if (empty($category_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()) {
            $category_success = "Category added successfully!";
            $_POST = []; // Reset category form fields
        } else {
            $category_errors[] = "Failed to save category to database: " . $conn->error;
        }
        $stmt->close();
    }
}

// Handle Product Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['add_category'])) {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $price = trim($_POST['price'] ?? '');
    $discount = trim($_POST['discount'] ?? '');
    $category = trim($_POST['category'] ?? '');
    $stock = trim($_POST['stock'] ?? '');
    $sku = trim($_POST['sku'] ?? '');
    $status = trim($_POST['status'] ?? '');
    
    // Product validation
    if (empty($name)) $errors[] = "Product Name is required.";
    if (empty($description)) $errors[] = "Description is required.";
    if ($price === '' || !is_numeric($price) || $price < 0) $errors[] = "Valid Price is required.";
    if ($discount === '' || !is_numeric($discount) || $discount < 0 || $discount > 100) $errors[] = "Discount must be between 0 and 100.";
    if (empty($category)) $errors[] = "Please select a valid category.";
    if ($stock === '' || !is_numeric($stock) || $stock < 0) $errors[] = "Valid Stock quantity is required.";
    if (empty($sku)) $errors[] = "SKU is required.";
    if (empty($status) || !in_array($status, ['active', 'inactive'])) $errors[] = "Status must be 'active' or 'inactive'.";
    
    // Product image upload handling
    $image_path = '';
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $image_name = $_FILES['image']['name'];
        $image_tmp = $_FILES['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 product image.";
        } else {
            $upload_dir = 'uploads/';
            $image_path = $upload_dir . uniqid() . '.' . $image_ext;
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
            if (!move_uploaded_file($image_tmp, $image_path)) {
                $errors[] = "Failed to upload product image.";
            }
        }
    } else {
        $errors[] = "Product Image is required.";
    }

    // If no product errors, save to database
    if (empty($errors)) {
        $stmt = $conn->prepare("INSERT INTO products (name, description, image, price, discount, category, stock, sku, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssddssss", $name, $description, $image_path, $price, $discount, $category, $stock, $sku, $status);
        if ($stmt->execute()) {
            $success = "Product added successfully!";
            $_POST = []; // Reset product form fields
            // Clear file input
            echo "<script>document.getElementById('image').value = '';</script>";
        } else {
            $errors[] = "Failed to save product to database: " . $conn->error;
        }
        $stmt->close();
    }
}

// Fetch all categories for the dropdown
$category_result = $conn->query("SELECT name FROM product_category ORDER BY name");
$categories = $category_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 { 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; }
        .modal { transition: opacity 0.3s ease; }
        .modal-open { overflow: hidden; }
        @media (max-width: 768px) {
            .content { margin-left: 0; }
            .content.open { margin-left: 0; }
            .search { display: none; }
        }
        @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 users..." 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>

    <!-- Add Product Form -->
    <div class="form-section bg-white p-6 rounded-lg shadow-md w-full my-6">
        <h2 class="text-xl font-semibold text-gray-900 mb-4">Add New Product</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; ?>

        <!-- Product Form -->
        <form method="POST" enctype="multipart/form-data" class="space-y-4">
            <div>
                <label for="name" class="block text-sm font-medium text-gray-700">Product Name</label>
                <input type="text" id="name" name="name" value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['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="description" class="block text-sm font-medium text-gray-700">Description</label>
                <textarea id="description" name="description" rows="4" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required><?php echo isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ''; ?></textarea>
            </div>
            <div>
                <label for="image" class="block text-sm font-medium text-gray-700">Product Image</label>
                <input type="file" id="image" name="image" accept="image/*" 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="price" class="block text-sm font-medium text-gray-700">Price ($)</label>
                <input type="number" id="price" name="price" value="<?php echo isset($_POST['price']) ? htmlspecialchars($_POST['price']) : ''; ?>" min="0" step="0.01" 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="discount" class="block text-sm font-medium text-gray-700">Discount (%)</label>
                <input type="number" id="discount" name="discount" value="<?php echo isset($_POST['discount']) ? htmlspecialchars($_POST['discount']) : ''; ?>" min="0" max="100" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
            </div>
            <div class="flex items-end gap-4">
                <div class="flex-1">
                    <label for="category" class="block text-sm font-medium text-gray-700">Category</label>
                    <select id="category" name="category" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                        <option value="">Select category</option>
                        <?php foreach ($categories as $category): ?>
                            <option value="<?php echo htmlspecialchars($category['name']); ?>" <?php echo isset($_POST['category']) && $_POST['category'] == $category['name'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($category['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="button" onclick="document.getElementById('categoryModal').classList.remove('hidden'); document.body.classList.add('modal-open');" class="bg-blue-900 text-white p-2 rounded-md hover:bg-blue-800 transition-colors">Add Category</button>
            </div>
            <div>
                <label for="stock" class="block text-sm font-medium text-gray-700">Stock</label>
                <input type="number" id="stock" name="stock" value="<?php echo isset($_POST['stock']) ? htmlspecialchars($_POST['stock']) : ''; ?>" min="0" 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="sku" class="block text-sm font-medium text-gray-700">SKU</label>
                <input type="text" id="sku" name="sku" value="<?php echo isset($_POST['sku']) ? htmlspecialchars($_POST['sku']) : ''; ?>" 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="status" class="block text-sm font-medium text-gray-700">Status</label>
                <select id="status" name="status" class="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500" required>
                    <option value="">Select status</option>
                    <option value="active" <?php echo isset($_POST['status']) && $_POST['status'] == 'active' ? 'selected' : ''; ?>>Active</option>
                    <option value="inactive" <?php echo isset($_POST['status']) && $_POST['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 Product</button>
            </div>
        </form>
    </div>

    <!-- Category Modal -->
    <div id="categoryModal" class="modal hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white p-6 rounded-lg shadow-lg w-full max-w-md">
            <h2 class="text-xl font-semibold text-gray-900 mb-4">Add New Category</h2>
            
            <!-- Category Success/Error Messages -->
            <?php if ($category_success): ?>
                <p class="success text-center font-semibold mb-4"><?php echo htmlspecialchars($category_success); ?></p>
            <?php endif; ?>
            <?php if (!empty($category_errors)): ?>
                <ul class="error mb-4">
                    <?php foreach ($category_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 class="flex gap-4">
                    <button type="submit" class="flex-1 bg-blue-900 text-white p-2 rounded-md hover:bg-blue-800 transition-colors">Add Category</button>
                    <button type="button" onclick="document.getElementById('categoryModal').classList.add('hidden'); document.body.classList.remove('modal-open');" class="flex-1 bg-gray-500 text-white p-2 rounded-md hover:bg-gray-600 transition-colors">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

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