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

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

// Handle Product Deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_product'])) {
    $product_id = trim($_POST['product_id'] ?? '');
    if (empty($product_id) || !is_numeric($product_id)) {
        $errors[] = "Invalid product ID.";
    } else {
        // Check if product exists
        $stmt = $conn->prepare("SELECT image FROM products WHERE id = ?");
        $stmt->bind_param("i", $product_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows === 0) {
            $errors[] = "Product not found.";
        } else {
            $product = $result->fetch_assoc();
            $image_path = $product['image'];
            // Delete product
            $stmt = $conn->prepare("DELETE FROM products WHERE id = ?");
            $stmt->bind_param("i", $product_id);
            if ($stmt->execute()) {
                $success = "Product deleted successfully!";
                // Delete associated image file
                if (!empty($image_path) && file_exists($image_path)) {
                    unlink($image_path);
                }
            } else {
                $errors[] = "Failed to delete product: " . $conn->error;
            }
        }
        $stmt->close();
    }
}

// Fetch all products
$result = $conn->query("SELECT id, name, description, image, price, discount, category, stock, sku, status, created_at, updated_at FROM products ORDER BY created_at DESC");
$products = $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; }
        .table-section { transition: transform 0.2s ease, box-shadow 0.2s ease; }
        .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); }
        .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; }
        .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; }
            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 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>

    <!-- All Products Section -->
    <div class="table-section bg-white p-6 rounded-lg shadow-md w-full my-6">
        <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-semibold text-gray-900">All Products</h2>
            <a href="add_product.php" class="bg-yellow-500 text-white p-2 rounded-md hover:bg-yellow-600 transition-colors">Add New Product</a>
        </div>
        
        <!-- 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; ?>

        <!-- Products 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>Price ($)</th>
                        <th>Discount (%)</th>
                        <th>Category</th>
                        <th>Stock</th>
                        <th>SKU</th>
                        <th>Status</th>
                        <th>Created At</th>
                        <th>Updated At</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($products)): ?>
                        <tr>
                            <td colspan="13" class="text-center py-4">No products found.</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($products as $product): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($product['id']); ?></td>
                                <td><?php echo htmlspecialchars($product['name']); ?></td>
                                <td><?php echo htmlspecialchars(substr($product['description'], 0, 50)) . (strlen($product['description']) > 50 ? '...' : ''); ?></td>
                                <td>
                                    <?php if ($product['image']): ?>
                                        <img src="<?php echo htmlspecialchars($product['image']); ?>" alt="Product Image" class="rounded-md">
                                    <?php else: ?>
                                        No Image
                                    <?php endif; ?>
                                </td>
                                <td><?php echo htmlspecialchars(number_format($product['price'], 2)); ?></td>
                                <td><?php echo htmlspecialchars(number_format($product['discount'], 2)); ?></td>
                                <td><?php echo htmlspecialchars($product['category']); ?></td>
                                <td><?php echo htmlspecialchars($product['stock']); ?></td>
                                <td><?php echo htmlspecialchars($product['sku']); ?></td>
                                <td><?php echo htmlspecialchars($product['status']); ?></td>
                                <td><?php echo htmlspecialchars($product['created_at']); ?></td>
                                <td><?php echo htmlspecialchars($product['updated_at']); ?></td>
                                <td class="flex gap-2">
                                    <a href="edit_product.php?id=<?php echo htmlspecialchars($product['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 product?');">
                                        <input type="hidden" name="product_id" value="<?php echo htmlspecialchars($product['id']); ?>">
                                        <input type="hidden" name="delete_product" 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>

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