<?php
require_once 'config.php';
require_admin(); // Only administrators can access this page

$message = '';

// --- Handle Manual Assignment ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['assign_lesson'])) {
    $studentId = filter_input(INPUT_POST, 'student_id', FILTER_VALIDATE_INT);
    $packId = filter_input(INPUT_POST, 'pack_id', FILTER_VALIDATE_INT);

    if ($studentId && $packId) {
        try {
            $pdo->beginTransaction();

            // 1. Grant access to the lesson pack. Use ON DUPLICATE KEY UPDATE to handle existing access gracefully.
            $stmt = $pdo->prepare("INSERT INTO student_packs (student_id, pack_id, access_granted_at) VALUES (?, ?, NOW()) 
                                   ON DUPLICATE KEY UPDATE access_granted_at = access_granted_at"); // Keep the original grant time if it exists
            $stmt->execute([$studentId, $packId]);

            // 2. Log the manual assignment event
            log_analytics($pdo, 'manual_assignment', $studentId, $packId);
            
            // 3. Find the names for the success message
            $studentNameStmt = $pdo->prepare("SELECT name FROM users WHERE id = ?");
            $studentNameStmt->execute([$studentId]);
            $studentName = $studentNameStmt->fetchColumn() ?: 'Shishya'; // 'Student' in Sinhala (Latin)

            $packNameStmt = $pdo->prepare("SELECT title FROM lesson_packs WHERE id = ?");
            $packNameStmt->execute([$packId]);
            $packName = $packNameStmt->fetchColumn() ?: 'Paatha Patiya'; // 'Lesson Pack' in Sinhala (Latin)


            $pdo->commit();
            $message = "<span class='font-extrabold'>Sārthakai!</span> '{$packName}' පාඨමාලාව '{$studentName}' හට සාර්ථකව ලබා දෙන ලදී."; 

        } catch (PDOException $e) {
            $pdo->rollBack();
            $message = 'Paatha Patiya Labhā Dīmē Dōṣayak: ' . $e->getMessage();
        }
    } else {
        $message = 'Dōṣayak: Avadharana Shishyayek hā Paatha Patiya Therīma.';
    }
}

// --- Fetch necessary data for the form ---

// Fetch all students
$studentsStmt = $pdo->query("SELECT id, name, email FROM users WHERE role = 'student' OR role = 'user' ORDER BY name ASC");
$students = $studentsStmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch all lesson packs. Adding a mock thumbnail URL for visual appeal.
$packsStmt = $pdo->query("SELECT id, title, price FROM lesson_packs ORDER BY title ASC");
$lessonPacks = $packsStmt->fetchAll(PDO::FETCH_ASSOC);

// Add mock thumbnail URL and format price for JS
$lessonPacksWithThumbnails = array_map(function($pack) {
    // Generate a unique but consistent placeholder image for each pack
    $pack['thumbnail_url'] = 'https://placehold.co/100x60/374151/ffffff?text=' . urlencode(substr($pack['title'], 0, 8));
    $pack['price_formatted'] = 'LKR ' . number_format($pack['price'], 2);
    return $pack;
}, $lessonPacks);

// Pass Lesson Packs to JavaScript for client-side filtering
$lessonPacksJson = json_encode($lessonPacksWithThumbnails);

require_once 'layouts.php';
render_header('Manual Assignment');
render_sidebar($_SESSION['user_role'], basename(__FILE__));
render_topbar('Manually Assign Lesson');
?>

<style>
    /* ----------------------------------- */
    /* Custom Styling and Animations */
    /* ----------------------------------- */
    
    /* Custom Scrollbar (Super Theme) */
    .pack-list-container::-webkit-scrollbar {
        width: 10px;
    }
    .pack-list-container::-webkit-scrollbar-thumb {
        background-color: #4f46e5; /* Indigo 600 */
        border-radius: 5px;
        border: 2px solid #e0e7ff; /* Indigo 100 */
    }
    .pack-list-container::-webkit-scrollbar-track {
        background: #e0e7ff; /* Indigo 100 */
    }

    /* Keyframe for subtle 'entry' animation */
    @keyframes fadeInSlideUp {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .animate-entry {
        animation: fadeInSlideUp 0.6s ease-out;
    }

    /* Button Gradient and Hover Effect */
    .btn-super-submit {
        background-image: linear-gradient(to right, #4f46e5 0%, #6366f1 51%, #4f46e5 100%);
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -2px rgba(0, 0, 0, 0.1);
        background-size: 200% auto;
        transition: all 0.5s ease;
    }
    .btn-super-submit:not(:disabled):hover {
        background-position: right center; /* change the direction of the change */
        box-shadow: 0 10px 15px -3px rgba(79, 70, 229, 0.5), 0 4px 6px -4px rgba(79, 70, 229, 0.5);
        transform: translateY(-2px);
    }
    .btn-super-submit:disabled {
        opacity: 0.7;
        cursor: not-allowed;
        background-image: none;
        background-color: #93c5fd; /* Light blue/gray for disabled */
    }
</style>

<div class="min-h-screen bg-gray-50 p-4 sm:p-8 animate-entry">
    <?php if ($message): ?>
        <!-- Super styled notification box -->
        <div class="bg-gradient-to-r from-indigo-500 to-blue-500 text-white p-5 mb-8 rounded-2xl shadow-xl border-l-8 border-yellow-300 transform transition duration-500 hover:scale-[1.01]" role="alert">
            <div class="flex items-center">
                <i class="fa-solid fa-circle-info text-2xl mr-3"></i>
                <p class="font-medium text-lg"><?php echo $message; ?></p>
            </div>
        </div>
    <?php endif; ?>

    <h2 class="text-4xl font-extrabold text-indigo-800 mb-6 text-center tracking-tight">
        Paatha Patiya Labhya Karanna (Manual Assignment)
    </h2>

    <div class="bg-white rounded-3xl shadow-2xl p-6 sm:p-10 max-w-5xl mx-auto border-4 border-indigo-100/50">
        <form id="assignment-form" method="POST" action="assign_lesson.php" class="grid grid-cols-1 lg:grid-cols-5 gap-8">

            <!-- Hidden Input for Selected Pack ID -->
            <input type="hidden" id="selected_pack_id" name="pack_id" required>

            <!-- Column 1: Student Selection & Summary (2/5 width) -->
            <div class="space-y-8 lg:col-span-2">
                <h3 class="text-2xl font-bold text-indigo-700 border-b-2 border-indigo-200 pb-3">Shishyaya Theranna Karanna</h3>
                
                <!-- Student Selection Dropdown -->
                <div class="relative">
                    <label for="student_id" class="block text-sm font-semibold text-gray-700 mb-2">Shishya (Student)</label>
                    <select id="student_id" name="student_id" required class="block w-full py-3 px-4 text-base border-2 border-gray-300 focus:ring-indigo-500 focus:border-indigo-500 rounded-xl shadow-lg transition duration-150 ease-in-out bg-white hover:border-indigo-400 appearance-none">
                        <option value="">-- Shishyaya Theranna Karanna --</option>
                        <?php foreach ($students as $student): ?>
                            <option value="<?php echo htmlspecialchars($student['id']); ?>">
                                <?php echo htmlspecialchars($student['name']); ?> (<?php echo htmlspecialchars($student['email']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <div class="pointer-events-none absolute inset-y-0 right-0 top-7 flex items-center px-4 text-indigo-600">
                        <i class="fa-solid fa-chevron-down"></i>
                    </div>
                    <?php if (empty($students)): ?>
                        <p class="mt-2 text-sm text-red-600 font-medium">Shishyayan (Students) labhya netha.</p>
                    <?php endif; ?>
                </div>

                <!-- Assignment Summary (Selected Pack Display) -->
                <div class="p-5 border-4 border-indigo-400 bg-indigo-50 rounded-2xl shadow-inner mt-10">
                    <p class="text-md font-extrabold text-indigo-800 mb-2 uppercase tracking-wider">Therū Paatha Patiya (Selected Pack):</p>
                    <p id="selected-pack-display" class="text-xl font-black text-indigo-900 transition duration-300">
                        <i class="fa-solid fa-circle-question mr-2 text-indigo-500"></i> Paatha Patiya Theranna Karanna...
                    </p>
                </div>

                <!-- Submission Button -->
                <button type="submit" name="assign_lesson" id="assign-button" disabled class="btn-super-submit w-full flex items-center justify-center py-4 px-6 rounded-xl text-xl font-extrabold text-white transition duration-500">
                    <i class="fa-solid fa-rocket mr-3"></i> Labhya Karanna
                </button>
            </div>

            <!-- Column 2: Lesson Pack Search and Selection (3/5 width) -->
            <div class="space-y-6 lg:col-span-3">
                <h3 class="text-2xl font-bold text-gray-700 border-b-2 border-gray-200 pb-3">Paatha Patiya Sōdanna (Search & Select)</h3>

                <!-- Search Input -->
                <div class="relative">
                    <i class="fa-solid fa-magnifying-glass absolute left-4 top-1/2 transform -translate-y-1/2 text-indigo-400 text-lg"></i>
                    <input type="text" id="pack_search" onkeyup="filterPacks()" placeholder="Paatha Patiya Sōdanna Karanna... (e.g. Maths, Science)" class="w-full py-3 pl-12 pr-4 border-2 border-gray-300 rounded-full shadow-md focus:ring-indigo-500 focus:border-indigo-500 transition duration-200">
                </div>

                <!-- Lesson Pack List -->
                <div id="pack-list" class="pack-list-container space-y-4 h-[450px] overflow-y-auto pr-3 bg-gray-100 p-4 rounded-2xl border-2 border-gray-200 shadow-inner">
                    <!-- Packs will be inserted here by JavaScript -->
                    <?php if (empty($lessonPacks)): ?>
                        <p class="text-center text-gray-500 py-20 font-medium">Paatha Pāti labhya netha. (No Lesson Packs Available).</p>
                    <?php endif; ?>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
    const lessonPacks = <?php echo $lessonPacksJson; ?>;
    const packListContainer = document.getElementById('pack-list');
    const selectedPackInput = document.getElementById('selected_pack_id');
    const selectedPackDisplay = document.getElementById('selected-pack-display');
    const assignButton = document.getElementById('assign-button');
    let selectedPackElement = null;

    /**
     * Renders the initial list of lesson packs.
     */
    function renderPacks(packs) {
        packListContainer.innerHTML = '';
        if (packs.length === 0) {
            packListContainer.innerHTML = '<p class="text-center text-gray-500 py-20 font-medium">Matchi Paatha Pāti labhya netha. (No matching packs found).</p>';
            return;
        }

        packs.forEach(pack => {
            const isSelected = pack.id === parseInt(selectedPackInput.value);
            
            const packCard = document.createElement('div');
            packCard.id = `pack-${pack.id}`;
            packCard.onclick = () => selectPack(pack.id, pack.title, packCard);
            
            // Base classes for advanced styling and animation
            let baseClasses = 'flex items-center space-x-4 p-4 rounded-xl cursor-pointer transition-all duration-300 ease-in-out border-2';
            
            if (isSelected) {
                // Selected state (Super style)
                packCard.className = `${baseClasses} bg-indigo-600 text-white shadow-xl ring-4 ring-indigo-300 transform scale-[1.01] border-indigo-700`;
                selectedPackElement = packCard;
            } else {
                // Default state and hover effect (Super style)
                packCard.className = `${baseClasses} bg-white border-gray-200 hover:bg-indigo-50 hover:shadow-lg hover:border-indigo-400 hover:translate-x-1`;
            }

            packCard.innerHTML = `
                <!-- Thumbnail -->
                <div class="relative w-20 h-12 flex-shrink-0 rounded-lg overflow-hidden bg-gray-700 border border-gray-400 shadow-inner">
                    <img src="${pack.thumbnail_url}" alt="${pack.title} Thumbnail" class="w-full h-full object-cover opacity-70">
                    <span class="absolute inset-0 flex items-center justify-center text-xs font-bold text-white">${pack.title.substring(0, 4)}</span>
                </div>
                
                <div class="flex-grow">
                    <!-- Title -->
                    <p class="text-md font-bold truncate ${isSelected ? 'text-white' : 'text-gray-900'}">${pack.title}</p>
                    <!-- Price -->
                    <p class="text-sm font-semibold ${isSelected ? 'text-indigo-200' : 'text-indigo-600'}">${pack.price_formatted}</p>
                </div>

                <!-- Checkmark Icon -->
                <div class="${isSelected ? 'block' : 'hidden'} text-white">
                    <i class="fa-solid fa-bookmark text-2xl"></i>
                </div>
            `;
            
            packListContainer.appendChild(packCard);
        });
    }

    /**
     * Filters the list of packs based on the search input.
     */
    function filterPacks() {
        const query = document.getElementById('pack_search').value.toLowerCase();
        const filteredPacks = lessonPacks.filter(pack => 
            pack.title.toLowerCase().includes(query) || 
            pack.price_formatted.toLowerCase().includes(query)
        );
        renderPacks(filteredPacks);
    }

    /**
     * Selects a lesson pack and updates the form state.
     */
    function selectPack(packId, packTitle, newSelectedElement) {
        // Deselect previous element
        if (selectedPackElement) {
            // Revert styles to default/hoverable state
            selectedPackElement.classList.remove('bg-indigo-600', 'text-white', 'shadow-xl', 'ring-4', 'ring-indigo-300', 'transform', 'scale-[1.01]', 'border-indigo-700');
            selectedPackElement.classList.add('bg-white', 'border-gray-200', 'hover:bg-indigo-50', 'hover:shadow-lg', 'hover:border-indigo-400', 'hover:translate-x-1');
            
            // Revert text colors and hide checkmark
            selectedPackElement.querySelector('p:nth-child(1)').classList.remove('text-white');
            selectedPackElement.querySelector('p:nth-child(1)').classList.add('text-gray-900');
            selectedPackElement.querySelector('p:nth-child(2)').classList.remove('text-indigo-200');
            selectedPackElement.querySelector('p:nth-child(2)').classList.add('text-indigo-600');
            selectedPackElement.querySelector('.fa-bookmark').parentNode.classList.add('hidden');
        }
        
        // Update selection
        selectedPackInput.value = packId;
        selectedPackDisplay.innerHTML = `<i class="fa-solid fa-layer-group mr-2 text-indigo-600"></i> ${packTitle}`;
        
        // Enable button
        assignButton.disabled = false;
        assignButton.classList.remove('bg-indigo-400', 'cursor-not-allowed');
        
        // Select new element
        selectedPackElement = newSelectedElement;
        if (selectedPackElement) {
            // Apply selected state styles
            selectedPackElement.classList.remove('bg-white', 'border-gray-200', 'hover:bg-indigo-50', 'hover:shadow-lg', 'hover:border-indigo-400', 'hover:translate-x-1');
            selectedPackElement.classList.add('bg-indigo-600', 'text-white', 'shadow-xl', 'ring-4', 'ring-indigo-300', 'transform', 'scale-[1.01]', 'border-indigo-700');
            
            // Update text colors and show checkmark
            selectedPackElement.querySelector('p:nth-child(1)').classList.remove('text-gray-900');
            selectedPackElement.querySelector('p:nth-child(1)').classList.add('text-white');
            selectedPackElement.querySelector('p:nth-child(2)').classList.remove('text-indigo-600');
            selectedPackElement.querySelector('p:nth-child(2)').classList.add('text-indigo-200');
            selectedPackElement.querySelector('.fa-bookmark').parentNode.classList.remove('hidden');
        }
    }

    // Initial render when the page loads
    window.onload = () => {
        renderPacks(lessonPacks);
    };
</script>

<?php render_main_content_end(); ?>