<?php
require_once 'config.php';
require_admin();

$message = $_GET['msg'] ?? '';

// --- CRUD Operations ---
if (isset($_POST['add_pack'])) {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $price = (float)$_POST['price'];

    // Thumbnail upload logic (Basic implementation)
    // Placeholder URL with subtle gradient background and rounded corners
    $thumbnail_url = 'https://placehold.co/400x250/374151/D1D5DB?text=' . urlencode($title);
    if (!empty($_FILES['thumbnail']['name']) && $_FILES['thumbnail']['error'] == UPLOAD_ERR_OK) {
        $uploadDir = 'uploads/packs/';
        if (!is_dir($uploadDir)) { mkdir($uploadDir, 0777, true); }
        $fileName = uniqid('pack_') . '_' . basename($_FILES['thumbnail']['name']);
        $targetPath = $uploadDir . $fileName;
        if (move_uploaded_file($_FILES['thumbnail']['tmp_name'], $targetPath)) {
            $thumbnail_url = $targetPath;
        } else {
            $message = 'Warning: Failed to upload thumbnail image. Using placeholder.';
        }
    }

    try {
        $stmt = $pdo->prepare("INSERT INTO lesson_packs (title, description, thumbnail_url, price) VALUES (?, ?, ?, ?)");
        $stmt->execute([$title, $description, $thumbnail_url, $price]);
        $message = 'Lesson Pack added successfully!';
    } catch (PDOException $e) {
        $message = 'Error adding pack: ' . $e->getMessage();
    }
}

if (isset($_POST['delete_pack'])) {
    $packId = $_POST['pack_id'];
    try {
        $stmt = $pdo->prepare("DELETE FROM lesson_packs WHERE id = ?");
        $stmt->execute([$packId]);
        $message = 'Lesson Pack deleted successfully.';
    } catch (PDOException $e) {
        $message = 'Error deleting pack: ' . $e->getMessage();
    }
}

// --- Fetch All Lesson Packs with Counts ---
$stmt = $pdo->query("
    SELECT
        lp.id,
        lp.title,
        lp.thumbnail_url,
        lp.price,
        COUNT(DISTINCT l.id) AS num_lessons,
        COUNT(DISTINCT sp.student_id) AS assigned_student_count
    FROM lesson_packs lp
    LEFT JOIN lessons l ON lp.id = l.pack_id
    LEFT JOIN student_packs sp ON lp.id = sp.pack_id
    GROUP BY lp.id
    ORDER BY lp.id DESC
");
$packs = $stmt->fetchAll();

require_once 'layouts.php';
render_header('Lesson Pack Management');
render_sidebar($_SESSION['user_role'], basename(__FILE__));
render_topbar('Lesson Pack Management');
?>

<div class="space-y-10">
    <?php if ($message): ?>
        <!-- Animated Alert Banner -->
        <div class="bg-indigo-50 border-l-8 border-indigo-600 text-indigo-800 p-4 mb-6 rounded-xl shadow-lg animate-fade-in transition duration-300" role="alert">
            <div class="flex items-center">
                <i class="fa-solid fa-circle-check text-2xl mr-3"></i>
                <p class="font-semibold"><?php echo htmlspecialchars($message); ?></p>
            </div>
        </div>
    <?php endif; ?>

    <!-- Add New Pack Form -->
    <div class="bg-white p-8 rounded-2xl shadow-2xl border-t-4 border-indigo-600 transition duration-300 hover:shadow-indigo-300/50">
        <h2 class="text-3xl font-extrabold text-gray-900 mb-8 flex items-center">
            <i class="fa-solid fa-box-open text-indigo-600 mr-3"></i>
            Add New Lesson Pack
        </h2>
        <form method="POST" action="addpack.php" enctype="multipart/form-data" class="space-y-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Title Field -->
                <div>
                    <label for="title" class="block text-sm font-semibold text-gray-700 mb-1">Title</label>
                    <input type="text" name="title" id="title" required class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition duration-200">
                </div>
                <!-- Price Field -->
                <div>
                    <label for="price" class="block text-sm font-semibold text-gray-700 mb-1">Price (Rs.)</label>
                    <div class="relative">
                        <span class="absolute left-0 inset-y-0 flex items-center pl-3 text-gray-500 font-bold">Rs.</span>
                        <input type="number" name="price" id="price" step="0.01" min="0" required class="w-full px-4 py-2 pl-12 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition duration-200">
                    </div>
                </div>
            </div>

            <!-- Description Field -->
            <div>
                <label for="description" class="block text-sm font-semibold text-gray-700 mb-1">Description</label>
                <textarea name="description" id="description" rows="4" required class="w-full px-4 py-2 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition duration-200"></textarea>
            </div>

            <!-- Thumbnail Field -->
            <div>
                <label for="thumbnail" class="block text-sm font-semibold text-gray-700 mb-1">Thumbnail Image</label>
                <input type="file" name="thumbnail" id="thumbnail" accept="image/*" class="w-full text-sm text-gray-900 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-indigo-100 file:text-indigo-700 hover:file:bg-indigo-200 transition duration-200 cursor-pointer">
                <p class="mt-1 text-xs text-gray-500">Max size 5MB. Accepts PNG, JPG, GIF.</p>
            </div>

            <!-- Submit Button with Animation -->
            <button type="submit" name="add_pack" class="w-full md:w-64 py-3 text-lg bg-green-600 text-white rounded-xl font-bold hover:bg-green-700 transform hover:scale-[1.02] transition duration-300 shadow-lg hover:shadow-xl hover:shadow-green-500/50">
                <i class="fa-solid fa-plus-circle mr-2"></i>
                Create Lesson Pack
            </button>
        </form>
    </div>

    <!-- All Lesson Packs List -->
    <h2 class="text-3xl font-extrabold text-gray-900 pt-6 border-t border-gray-200 mt-8 flex items-center">
        All Lesson Packs
        <span class="ml-3 text-base font-semibold text-indigo-600 bg-indigo-100 px-3 py-1 rounded-full"><?php echo count($packs); ?> Packs</span>
    </h2>

    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
        <?php if ($packs): ?>
            <?php foreach ($packs as $pack): ?>
                <!-- Lesson Pack Card with Enhanced Styling and Hover Effects -->
                <div class="bg-white rounded-2xl overflow-hidden shadow-xl border border-gray-100 transform hover:scale-[1.03] transition duration-300 ease-in-out hover:shadow-2xl group">
                    <div class="relative">
                        <img src="<?php echo htmlspecialchars($pack['thumbnail_url']); ?>" alt="<?php echo htmlspecialchars($pack['title']); ?>" class="w-full h-48 object-cover transition duration-500 group-hover:opacity-80">
                        <!-- Price Tag Badge -->
                        <div class="absolute top-3 right-3 bg-indigo-600 text-white text-sm font-extrabold px-3 py-1 rounded-full shadow-lg transform rotate-2 group-hover:rotate-0 transition duration-300">
                            Rs. <?php echo number_format($pack['price'], 2); ?>
                        </div>
                    </div>
                    <div class="p-5">
                        <h3 class="text-xl font-bold text-gray-900 line-clamp-2 mb-2 group-hover:text-indigo-600 transition duration-300"><?php echo htmlspecialchars($pack['title']); ?></h3>

                        <!-- Stats Block -->
                        <div class="flex justify-between text-sm text-gray-600 border-t border-b border-gray-100 py-3 mb-4">
                            <span class="flex items-center text-gray-700">
                                <i class="fa-solid fa-video text-indigo-500 mr-2"></i>
                                Lessons: <span class="font-extrabold ml-1"><?php echo $pack['num_lessons']; ?></span>
                            </span>
                            <span class="flex items-center text-gray-700">
                                <i class="fa-solid fa-user-graduate text-green-500 mr-2"></i>
                                Students: <span class="font-extrabold ml-1"><?php echo $pack['assigned_student_count']; ?></span>
                            </span>
                        </div>

                        <!-- Action Buttons -->
                        <div class="flex space-x-3">
                            <a href="addclass.php?pack_id=<?php echo $pack['id']; ?>" class="flex-1 flex items-center justify-center py-2 bg-indigo-500 text-white rounded-xl text-center hover:bg-indigo-600 text-sm font-bold transition duration-200 transform hover:shadow-md">
                                <i class="fa-solid fa-plus mr-1"></i> Add Lesson
                            </a>
                            <button onclick="confirmDeletePack(<?php echo $pack['id']; ?>, '<?php echo htmlspecialchars(addslashes($pack['title'])); ?>')"
                                    class="p-3 bg-red-100 text-red-600 rounded-xl hover:bg-red-200 transition duration-200 transform hover:scale-110" title="Delete Pack">
                                <i class="fa-solid fa-trash"></i>
                            </button>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="md:col-span-4 text-center py-12 bg-gray-50 rounded-xl border border-dashed border-gray-300">
                <i class="fa-solid fa-box-open text-5xl text-gray-300 mb-4"></i>
                <p class="text-gray-500 font-medium">No lesson packs created yet. Start by adding one above!</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Delete Confirmation Modal (Enhanced) -->
<div id="delete-modal" class="fixed inset-0 bg-gray-900 bg-opacity-80 hidden items-center justify-center p-4 z-50 transition-opacity duration-300">
    <div class="bg-white rounded-3xl shadow-3xl max-w-sm w-full p-8 text-center transform scale-95 transition-transform duration-300 modal-content">
        <div class="relative">
            <i class="fa-solid fa-fire-extinguisher text-7xl text-red-500 mb-6 animate-pulse"></i>
            <h3 class="text-2xl font-extrabold text-gray-900 mb-3">Permanent Deletion Warning</h3>
            <p class="text-gray-600 mb-8 leading-relaxed">You are about to delete the lesson pack: <span id="pack-title-to-delete" class="font-extrabold text-red-600"></span>. This action cannot be undone and will remove all associated content and student assignments.</p>
        </div>
        <form method="POST" action="addpack.php" class="flex flex-col space-y-3">
            <input type="hidden" name="pack_id" id="delete-pack-id">
            <button type="submit" name="delete_pack" class="w-full py-3 bg-red-600 text-white rounded-xl font-bold hover:bg-red-700 transition duration-200 transform hover:scale-[1.01] shadow-lg hover:shadow-red-500/50">
                <i class="fa-solid fa-trash-can mr-2"></i> Yes, Delete This Pack
            </button>
            <button type="button" onclick="closeDeleteModal()" class="w-full py-3 bg-gray-200 text-gray-800 rounded-xl font-semibold hover:bg-gray-300 transition duration-200">
                Cancel
            </button>
        </form>
    </div>
</div>

<script>
    // Utility function to handle modal open/close with transitions
    const modal = document.getElementById('delete-modal');
    const modalContent = modal.querySelector('.modal-content');

    function openDeleteModal() {
        modal.classList.remove('hidden');
        modal.classList.add('flex', 'opacity-0');
        setTimeout(() => {
            modal.classList.remove('opacity-0');
            modalContent.classList.remove('scale-95');
            modalContent.classList.add('scale-100');
        }, 10); // Small delay to trigger CSS transition
    }

    function closeDeleteModal() {
        modal.classList.add('opacity-0');
        modalContent.classList.remove('scale-100');
        modalContent.classList.add('scale-95');
        setTimeout(() => {
            modal.classList.remove('flex');
            modal.classList.add('hidden');
        }, 300); // Wait for transition to finish
    }

    function confirmDeletePack(packId, packTitle) {
        document.getElementById('delete-pack-id').value = packId;
        document.getElementById('pack-title-to-delete').textContent = packTitle;
        openDeleteModal();
    }
</script>

<?php render_main_content_end(); ?>