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

$message = '';
$selectedPackId = $_GET['pack_id'] ?? null;

// --- CRUD Operations ---
if (isset($_POST['add_lesson'])) {
    $packId = (int)$_POST['pack_id'];
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    
    // NEW FIELDS
    $isLive = (int)($_POST['is_live'] ?? 0);
    $zoomLink = trim($_POST['zoom_link'] ?? '');
    
    // ORIGINAL FIELDS (Conditionally used)
    $youtubeLink = trim($_POST['youtube_link'] ?? '');
    $thumbnailPath = null; // Initialize thumbnail path

    $hasValidationError = false;

    // 1. Validation Logic Adjustment based on lesson type
    if ($isLive == 0) { // Recorded Video
        if (!get_youtube_embed_link($youtubeLink)) {
            $message = 'Error: The provided YouTube link is invalid.';
            $hasValidationError = true;
        }
        $zoomLink = null; // Ensure Zoom link is null for video lessons
    } else { // Live Class (Zoom)
        // Basic check for a URL-like structure for Zoom link
        if (empty($zoomLink) || !filter_var($zoomLink, FILTER_VALIDATE_URL)) {
            $message = 'Error: A valid URL is required for the Zoom meeting link.';
            $hasValidationError = true;
        }
        $youtubeLink = null; // Ensure YouTube link is null for live lessons
    }
    
    // Proceed if no structural validation error occurred
    if (!$hasValidationError) {
        // 2. Custom Thumbnail Upload Handling
        if (isset($_FILES['custom_thumbnail']) && $_FILES['custom_thumbnail']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = 'uploads/tumbs/';

            // Ensure the upload directory exists
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $fileTmpPath = $_FILES['custom_thumbnail']['tmp_name'];
            $fileName = $_FILES['custom_thumbnail']['name'];
            $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

            $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
            $maxFileSize = 5 * 1024 * 1024; // 5MB

            if (!in_array($fileExtension, $allowedExtensions)) {
                $message = 'Error: Invalid file type for thumbnail. Only JPG, JPEG, PNG, and GIF are allowed.';
                $hasValidationError = true;
            } elseif ($_FILES['custom_thumbnail']['size'] > $maxFileSize) {
                $message = 'Error: The uploaded file is too large. Maximum size is 5MB.';
                $hasValidationError = true;
            } else {
                // Generate a unique filename
                $newFileName = uniqid('tumb_') . '.' . $fileExtension;
                $destPath = $uploadDir . $newFileName;

                if (move_uploaded_file($fileTmpPath, $destPath)) {
                    $thumbnailPath = $destPath; // Save the relative path
                } else {
                    $message = 'Error moving the uploaded thumbnail file. Check folder permissions.';
                    $hasValidationError = true;
                }
            }
        }
        
        // 3. Database Insertion (only proceed if no file upload error occurred or if no file was uploaded)
        if (!$hasValidationError) {
            try {
                // INSERT statement updated to include thumbnail_path, is_live, and zoom_link
                $stmt = $pdo->prepare("INSERT INTO lessons (pack_id, title, description, youtube_link, thumbnail_path, is_live, zoom_link) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$packId, $title, $description, $youtubeLink, $thumbnailPath, $isLive, $zoomLink]);
                $message = 'Lesson added successfully to the pack!';
                $selectedPackId = $packId; // Keep the selected pack
            } catch (PDOException $e) {
                $message = 'Error adding lesson: ' . $e->getMessage();
            }
        }
    }
}

// --- NEW: Update Lesson Operation ---
if (isset($_POST['update_lesson'])) {
    $lessonId = (int)$_POST['lesson_id'];
    $packId = (int)$_POST['pack_id'];
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $isLive = (int)($_POST['is_live'] ?? 0);
    $zoomLink = trim($_POST['zoom_link'] ?? '');
    $youtubeLink = trim($_POST['youtube_link'] ?? '');
    $currentThumbnailPath = trim($_POST['current_thumbnail_path'] ?? ''); // Hidden field for existing path
    $deleteCurrentThumbnail = isset($_POST['delete_current_thumbnail']); // Checkbox to delete thumbnail

    $thumbnailPath = $currentThumbnailPath; // Start with the existing path
    $hasValidationError = false;

    // 1. Validation Logic Adjustment
    if ($isLive == 0) { // Recorded Video
        if (!get_youtube_embed_link($youtubeLink)) {
            $message = 'Error: The provided YouTube link is invalid.';
            $hasValidationError = true;
        }
        $zoomLink = null;
    } else { // Live Class (Zoom)
        if (empty($zoomLink) || !filter_var($zoomLink, FILTER_VALIDATE_URL)) {
            $message = 'Error: A valid URL is required for the Zoom meeting link.';
            $hasValidationError = true;
        }
        $youtubeLink = null;
    }

    if (!$hasValidationError) {
        // 2. Thumbnail Deletion/Update Handling

        // Check if user explicitly chose to delete the existing custom thumbnail
        if ($deleteCurrentThumbnail && !empty($currentThumbnailPath)) {
            if (file_exists($currentThumbnailPath)) {
                unlink($currentThumbnailPath);
            }
            $thumbnailPath = null; // Set path to null in DB
        }

        // Handle NEW Custom Thumbnail Upload
        if (isset($_FILES['custom_thumbnail']) && $_FILES['custom_thumbnail']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = 'uploads/tumbs/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $fileTmpPath = $_FILES['custom_thumbnail']['tmp_name'];
            $fileName = $_FILES['custom_thumbnail']['name'];
            $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

            $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
            $maxFileSize = 5 * 1024 * 1024;

            if (!in_array($fileExtension, $allowedExtensions)) {
                $message = 'Error: Invalid file type for thumbnail. Only JPG, JPEG, PNG, and GIF are allowed.';
                $hasValidationError = true;
            } elseif ($_FILES['custom_thumbnail']['size'] > $maxFileSize) {
                $message = 'Error: The uploaded file is too large. Maximum size is 5MB.';
                $hasValidationError = true;
            } else {
                // Delete old thumbnail if a new one is successfully uploaded
                if (!empty($currentThumbnailPath) && file_exists($currentThumbnailPath)) {
                    unlink($currentThumbnailPath);
                }

                $newFileName = uniqid('tumb_') . '.' . $fileExtension;
                $destPath = $uploadDir . $newFileName;

                if (move_uploaded_file($fileTmpPath, $destPath)) {
                    $thumbnailPath = $destPath; // Update path to new file
                } else {
                    $message = 'Error moving the uploaded thumbnail file. Check folder permissions.';
                    $hasValidationError = true;
                }
            }
        }
        // If no new file uploaded and no deletion requested, $thumbnailPath remains $currentThumbnailPath

        // 3. Database Update
        if (!$hasValidationError) {
            try {
                $stmt = $pdo->prepare("UPDATE lessons SET title = ?, description = ?, youtube_link = ?, thumbnail_path = ?, is_live = ?, zoom_link = ? WHERE id = ? AND pack_id = ?");
                $stmt->execute([$title, $description, $youtubeLink, $thumbnailPath, $isLive, $zoomLink, $lessonId, $packId]);
                $message = 'Lesson updated successfully!';
                $selectedPackId = $packId;
            } catch (PDOException $e) {
                $message = 'Error updating lesson: ' . $e->getMessage();
            }
        }
    }
}


// --- NEW: Delete Lesson Operation (Existing Logic) ---
if (isset($_POST['delete_lesson'])) {
    $lessonId = (int)$_POST['lesson_id'];
    $packId = (int)$_POST['pack_id']; // To maintain context after deletion

    try {
        // 1. Get the thumbnail path before deleting the record
        $stmt = $pdo->prepare("SELECT thumbnail_path FROM lessons WHERE id = ?");
        $stmt->execute([$lessonId]);
        $lesson = $stmt->fetch(PDO::FETCH_ASSOC);

        $deletedFilePath = $lesson['thumbnail_path'] ?? null;

        // 2. Delete the lesson from the database
        $stmt = $pdo->prepare("DELETE FROM lessons WHERE id = ?");
        $stmt->execute([$lessonId]);

        // 3. Delete the physical thumbnail file if it exists and is not empty
        if (!empty($deletedFilePath) && file_exists($deletedFilePath)) {
            // Note: In a real environment, you might want more checks on the path
            // to ensure you don't delete critical system files.
            unlink($deletedFilePath);
        }

        $message = 'Lesson deleted successfully.';
        $selectedPackId = $packId; // Keep the selected pack active
    } catch (PDOException $e) {
        $message = 'Error deleting lesson: ' . $e->getMessage();
    }
}

// --- Fetch all Lesson Packs ---
$stmt = $pdo->query("SELECT id, title FROM lesson_packs ORDER BY title");
$packs = $stmt->fetchAll();

// --- Fetch Lessons for Selected Pack (for viewing/managing) ---
$lessons = [];
$packTitle = 'No Pack Selected';
if ($selectedPackId) {
    $stmt = $pdo->prepare("SELECT title FROM lesson_packs WHERE id = ?");
    $stmt->execute([$selectedPackId]);
    $packTitle = $stmt->fetchColumn() ?: 'Unknown Pack';

    // SELECT statement updated to include thumbnail_path, is_live, and zoom_link
    $stmt = $pdo->prepare("SELECT id, title, description, youtube_link, thumbnail_path, is_live, zoom_link FROM lessons WHERE pack_id = ? ORDER BY id DESC");
    $stmt->execute([$selectedPackId]);
    $lessons = $stmt->fetchAll(PDO::FETCH_ASSOC); // Ensure associative array for JSON encoding
}

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

<style>
/* Custom CSS for enhanced radio buttons */
.form-radio {
    /* Base style for radio button */
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    display: inline-block;
    height: 1.5rem; /* Larger touch target */
    width: 1.5rem;
    border-radius: 50%;
    border-width: 2px;
    border-color: #9ca3af; /* gray-400 */
    background-color: #fff;
    transition: all 0.2s ease-in-out;
    cursor: pointer;
}
.form-radio:checked {
    border-color: transparent;
    background-color: currentColor; /* Uses text color for fill */
    transform: scale(1.1);
}
.form-radio:focus {
    outline: none;
    box-shadow: 0 0 0 3px rgba(165, 180, 252, 0.5); /* blue-300 shadow */
}
/* Style for live radio specifically */
#is_live_1:checked {
    background-color: #ef4444; /* red-500 */
}
#is_live_0:checked {
    background-color: #4f46e5; /* indigo-600 */
}

/* Custom Modal Animation (for entrance) */
.modal-enter {
    opacity: 0;
    transform: scale(0.9);
}
.modal-enter-active {
    opacity: 1;
    transform: scale(1);
    transition: opacity 0.3s ease-out, transform 0.3s ease-out;
}
.modal-leave-active {
    opacity: 0;
    transform: scale(0.9);
    transition: opacity 0.2s ease-in, transform 0.2s ease-in;
}

</style>

<div class="space-y-12">
    <?php if ($message): ?>
        <div class="bg-indigo-100 border-l-4 border-indigo-500 text-indigo-700 p-4 mb-6 rounded-lg shadow-md transition duration-300 transform hover:scale-[1.01]" role="alert">
            <p class="font-semibold">Status Update:</p>
            <p><?php echo htmlspecialchars($message); ?></p>
        </div>
    <?php endif; ?>

    <!-- Add New Lesson Form -->
    <div class="bg-white p-6 md:p-10 rounded-3xl shadow-2xl transition duration-500 hover:shadow-indigo-300/50">
        <h2 class="text-3xl font-extrabold text-gray-900 mb-8 border-b pb-3 text-indigo-700">🚀 Create New Lesson</h2>
        <!-- IMPORTANT: Added enctype="multipart/form-data" -->
        <form method="POST" action="addclass.php" class="space-y-6" enctype="multipart/form-data">
            
            <!-- Pack Selection -->
            <div class="relative group">
                <label for="pack_id" class="absolute left-3 -top-2.5 text-xs font-semibold text-gray-500 bg-white px-1 transition-all group-focus-within:text-indigo-600">
                    Select Lesson Pack
                </label>
                <select name="pack_id" id="pack_id" required 
                    class="mt-1 block w-full px-4 py-3 border border-gray-300 rounded-xl shadow-sm focus:ring-indigo-500 focus:border-indigo-500 transition duration-150 appearance-none" 
                    onchange="window.location.href='addclass.php?pack_id=' + this.value">
                    <option value="" class="text-gray-400">-- Select a Pack --</option>
                    <?php foreach ($packs as $pack): ?>
                        <option value="<?php echo $pack['id']; ?>" <?php echo ($pack['id'] == $selectedPackId) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($pack['title']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <!-- Custom Down Arrow -->
                <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
                    <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 10.94l3.71-3.71a.75.75 0 111.06 1.06l-4.25 4.25a.75.75 0 01-1.06 0L5.21 8.27a.75.75 0 01.02-1.06z" clip-rule="evenodd" /></svg>
                </div>
            </div>

            <?php if ($selectedPackId): ?>
            
            <!-- Lesson Title -->
            <div class="relative group">
                <input type="text" name="title" id="title" required placeholder=" "
                    class="block w-full px-4 py-3 text-gray-900 border border-gray-300 rounded-xl shadow-sm focus:ring-indigo-500 focus:border-indigo-500 transition duration-150 peer" />
                <label for="title" class="absolute left-3 -top-2.5 text-xs font-semibold text-gray-500 bg-white px-1 transition-all peer-placeholder-shown:top-3 peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-focus:-top-2.5 peer-focus:text-xs peer-focus:text-indigo-600">
                    Lesson Title
                </label>
            </div>

            <!-- Lesson Description -->
            <div class="relative group">
                <textarea name="description" id="description" rows="3" required placeholder=" "
                    class="block w-full px-4 py-3 text-gray-900 border border-gray-300 rounded-xl shadow-sm focus:ring-indigo-500 focus:border-indigo-500 transition duration-150 peer"></textarea>
                <label for="description" class="absolute left-3 -top-2.5 text-xs font-semibold text-gray-500 bg-white px-1 transition-all peer-placeholder-shown:top-3 peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-focus:-top-2.5 peer-focus:text-xs peer-focus:text-indigo-600">
                    Lesson Description
                </label>
            </div>
            
            <!-- NEW: Lesson Type Selection (Video vs. Live) -->
            <div>
                <label class="block text-base font-semibold text-gray-700 mb-3">Choose Lesson Type</label>
                <div class="flex flex-col sm:flex-row items-start sm:items-center space-y-4 sm:space-y-0 sm:space-x-8">
                    
                    <label class="inline-flex items-center p-3 border-2 border-indigo-200 bg-indigo-50 rounded-xl cursor-pointer hover:bg-indigo-100 transition duration-150">
                        <input type="radio" name="is_live" id="is_live_0" value="0" checked class="form-radio text-indigo-600" onchange="toggleLessonFields(0)">
                        <div class="ml-3">
                            <span class="font-bold text-indigo-700 block">Recorded Video</span>
                            <span class="text-sm text-indigo-600">Requires YouTube Link</span>
                        </div>
                    </label>

                    <label class="inline-flex items-center p-3 border-2 border-red-200 bg-red-50 rounded-xl cursor-pointer hover:bg-red-100 transition duration-150">
                        <input type="radio" name="is_live" id="is_live_1" value="1" class="form-radio text-red-600" onchange="toggleLessonFields(1)">
                        <div class="ml-3">
                            <span class="font-bold text-red-700 block">Live Class</span>
                            <span class="text-sm text-red-600">Requires Zoom Link</span>
                        </div>
                    </label>
                </div>
            </div>

            <!-- Custom Thumbnail Upload Field (Optional for both) -->
            <div class="border border-dashed border-gray-300 p-6 rounded-xl bg-gray-50 hover:bg-gray-100 transition duration-150">
                <label for="custom_thumbnail" class="block text-sm font-medium text-gray-700 mb-2">🖼️ Custom Thumbnail Image (Optional)</label>
                <input type="file" name="custom_thumbnail" id="custom_thumbnail" accept="image/png, image/jpeg, image/gif" 
                    class="mt-1 block w-full text-sm text-gray-600 
                           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-150">
                <p class="mt-2 text-xs text-gray-500">Max 5MB. Accepts JPG, JPEG, PNG, GIF. This overrides the YouTube thumbnail.</p>
            </div>
            
            <!-- Dynamic Fields Container (Video) -->
            <div id="video-fields">
                <!-- Original YouTube Link Field -->
                <div class="relative group">
                    <input type="url" name="youtube_link" id="youtube_link" required placeholder="e.g., https://www.youtube.com/watch?v=dQw4w9WgXcQ"
                        class="block w-full px-4 py-3 text-gray-900 border border-gray-300 rounded-xl shadow-sm focus:ring-indigo-500 focus:border-indigo-500 transition duration-150 peer"
                        oninput="previewThumbnail(this.value)" />
                    <label for="youtube_link" class="absolute left-3 -top-2.5 text-xs font-semibold text-gray-500 bg-white px-1 transition-all peer-placeholder-shown:top-3 peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-focus:-top-2.5 peer-focus:text-xs peer-focus:text-indigo-600">
                        YouTube Video Link (Full URL)
                    </label>
                </div>
                <!-- Thumbnail Preview -->
                <div id="thumbnail-preview" class="mt-4 h-48 w-full bg-gray-100 rounded-xl flex items-center justify-center text-gray-500 text-lg font-medium overflow-hidden border-2 border-dashed border-gray-300">
                    Video Thumbnail Preview
                </div>
            </div>

            <!-- Dynamic Fields Container (Zoom) -->
            <div id="zoom-fields" class="hidden">
                <!-- NEW: Zoom Link Field -->
                <div class="relative group">
                    <input type="url" name="zoom_link" id="zoom_link" placeholder="e.g., https://us02web.zoom.us/j/1234567890" 
                        class="block w-full px-4 py-3 text-gray-900 border border-red-300 rounded-xl shadow-sm focus:ring-red-500 focus:border-red-500 transition duration-150 peer" />
                    <label for="zoom_link" class="absolute left-3 -top-2.5 text-xs font-semibold text-gray-500 bg-white px-1 transition-all peer-placeholder-shown:top-3 peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-focus:-top-2.5 peer-focus:text-xs peer-focus:text-red-600">
                        Zoom Meeting Link (Required for Live Class)
                    </label>
                </div>
            </div>
            
            <!-- Submit Button -->
            <button type="submit" name="add_lesson" 
                    class="w-full sm:w-64 py-3 px-6 bg-indigo-600 text-white rounded-xl font-bold text-lg 
                           hover:bg-indigo-700 transition duration-300 shadow-lg shadow-indigo-500/50 
                           transform hover:scale-[1.02] active:scale-[0.98] focus:outline-none focus:ring-4 focus:ring-indigo-500 focus:ring-opacity-50">
                💾 Submit Lesson
            </button>
            <?php endif; ?>
        </form>
    </div>

    <!-- Lessons in Selected Pack -->
    <?php if ($selectedPackId && $lessons): ?>
    <h2 class="text-3xl font-extrabold text-gray-900 pt-4 border-t-2 border-indigo-100 mt-12 mb-6">📚 Lessons in: <span class="text-indigo-600"><?php echo htmlspecialchars($packTitle); ?></span></h2>
    <div class="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
        <?php foreach ($lessons as $lesson): ?>
            <?php 
                // Logic to prioritize custom thumbnail over YouTube thumbnail
                $is_live = (int)($lesson['is_live'] ?? 0);
                
                if ($is_live) {
                    $thumbnailSrc = 'https://placehold.co/600x250/F87171/ffffff?text=LIVE+ZOOM+CLASS';
                    $typeBadge = '<span class="text-xs font-bold text-white px-3 py-1 rounded-full bg-red-600 shadow-md">🔴 LIVE CLASS</span>';
                } else {
                    $thumbnailSrc = !empty($lesson['thumbnail_path'])
                        ? htmlspecialchars($lesson['thumbnail_path'])
                        : get_youtube_thumbnail($lesson['youtube_link']);
                    $typeBadge = '<span class="text-xs font-bold text-white px-3 py-1 rounded-full bg-indigo-600 shadow-md">▶️ RECORDED VIDEO</span>';
                }
                
                // Prepare lesson data for JSON encoding (use JSON_HEX_QUOT for safety in HTML attributes)
                $lessonDataJson = htmlspecialchars(json_encode($lesson), ENT_QUOTES, 'UTF-8');
            ?>
            
            <!-- Lesson Card (Enhanced) -->
            <div class="bg-white p-5 rounded-3xl shadow-xl border border-gray-100 hover:shadow-2xl hover:border-indigo-300 transition duration-300 transform hover:scale-[1.01] flex flex-col">
                
                <!-- Thumbnail & Badge -->
                <div class="relative h-40 overflow-hidden rounded-2xl mb-4">
                    <img src="<?php echo $thumbnailSrc; ?>" alt="Lesson Thumbnail" class="w-full h-full object-cover transition duration-500 hover:scale-105">
                    <div class="absolute top-2 left-2">
                        <?php echo $typeBadge; ?>
                    </div>
                </div>

                <!-- Content -->
                <div class="flex-grow">
                    <h4 class="text-xl font-bold text-gray-900 mb-2 line-clamp-1"><?php echo htmlspecialchars($lesson['title']); ?></h4>
                    <p class="text-sm text-gray-600 line-clamp-3 mb-4 min-h-[4.5rem]"><?php echo htmlspecialchars($lesson['description']); ?></p>
                    <div class="text-xs font-medium truncate">
                        <?php if ($is_live): ?>
                            <p class="text-red-500">🔗 Zoom Link: <span class="font-normal"><?php echo htmlspecialchars(substr($lesson['zoom_link'], 0, 40)) . '...'; ?></span></p>
                        <?php else: ?>
                            <p class="text-indigo-500">🔗 YouTube Link: <span class="font-normal"><?php echo htmlspecialchars(substr($lesson['youtube_link'], 0, 40)) . '...'; ?></span></p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Actions -->
                <div class="pt-4 border-t border-gray-100 mt-4 flex justify-end space-x-3">
                    <!-- Edit Lesson Button -->
                    <button type="button" onclick="openEditModal(<?php echo $lessonDataJson; ?>)" 
                            class="p-2 h-10 w-10 flex-shrink-0 text-white bg-blue-500 hover:bg-blue-600 rounded-full transition duration-150 flex items-center justify-center shadow-lg hover:shadow-blue-400/50" 
                            title="Edit Lesson">
                        <!-- Edit Icon (Pencil) -->
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                            <path d="M17.414 2.586a2 2 0 00-2.828 0L7 10.172V13h2.828l7.586-7.586a2 2 0 000-2.828z" />
                            <path fill-rule="evenodd" d="M2 6a2 2 0 012-2h4a1 1 0 010 2H4v10h10v-4a1 1 0 112 0v4a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" clip-rule="evenodd" />
                        </svg>
                    </button>
                    
                    <!-- Delete Lesson Form/Button -->
                    <form method="POST" action="addclass.php" onsubmit="return confirm('Are you sure you want to delete this lesson: <?php echo addslashes(htmlspecialchars($lesson['title'])); ?>?');">
                        <input type="hidden" name="lesson_id" value="<?php echo $lesson['id']; ?>">
                        <input type="hidden" name="pack_id" value="<?php echo $selectedPackId; ?>">
                        <button type="submit" name="delete_lesson" 
                                class="p-2 h-10 w-10 flex-shrink-0 text-white bg-red-500 hover:bg-red-600 rounded-full transition duration-150 flex items-center justify-center shadow-lg hover:shadow-red-400/50" 
                                title="Delete Lesson">
                            <!-- Trash Can SVG Icon -->
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                            </svg>
                        </button>
                    </form>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <?php elseif ($selectedPackId && empty($lessons)): ?>
        <div class="bg-yellow-50 border-l-4 border-yellow-400 text-yellow-800 p-4 rounded-xl shadow-inner mt-8">
            <p class="font-medium">🔔 Heads up!</p>
            <p class="text-sm">No lessons added to this pack yet. Use the form above to create your first lesson.</p>
        </div>
    <?php endif; ?>
</div>

<!-- Edit Lesson Modal -->
<div id="edit-lesson-modal" class="fixed inset-0 bg-gray-900 bg-opacity-80 hidden z-50 overflow-y-auto transition-opacity" onclick="if(event.target.id === 'edit-lesson-modal') closeEditModal()">
    <div class="flex items-center justify-center min-h-screen p-4">
        <div class="bg-white rounded-3xl shadow-2xl w-full max-w-2xl transform modal-enter" id="edit-modal-content">
            <div class="flex justify-between items-center p-6 border-b border-gray-100 bg-indigo-50 rounded-t-3xl">
                <h3 class="text-2xl font-bold text-indigo-700">✍️ Edit Lesson</h3>
                <button onclick="closeEditModal()" class="text-gray-500 hover:text-gray-800 transition duration-150 p-1 rounded-full hover:bg-white">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                </button>
            </div>
            
            <form method="POST" action="addclass.php" class="p-6 space-y-6" enctype="multipart/form-data" id="edit-lesson-form">
                <input type="hidden" name="lesson_id" id="edit_lesson_id">
                <input type="hidden" name="pack_id" id="edit_pack_id">
                <input type="hidden" name="current_thumbnail_path" id="edit_current_thumbnail_path">

                <!-- Title -->
                <div class="relative group">
                    <input type="text" name="title" id="edit_title" required placeholder=" "
                        class="block w-full px-4 py-3 text-gray-900 border border-gray-300 rounded-xl shadow-sm focus:ring-blue-500 focus:border-blue-500 transition duration-150 peer" />
                    <label for="edit_title" class="absolute left-3 -top-2.5 text-xs font-semibold text-gray-500 bg-white px-1 transition-all peer-placeholder-shown:top-3 peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-focus:-top-2.5 peer-focus:text-xs peer-focus:text-blue-600">
                        Lesson Title
                    </label>
                </div>

                <!-- Description -->
                <div class="relative group">
                    <textarea name="description" id="edit_description" rows="3" required placeholder=" "
                        class="block w-full px-4 py-3 text-gray-900 border border-gray-300 rounded-xl shadow-sm focus:ring-blue-500 focus:border-blue-500 transition duration-150 peer"></textarea>
                    <label for="edit_description" class="absolute left-3 -top-2.5 text-xs font-semibold text-gray-500 bg-white px-1 transition-all peer-placeholder-shown:top-3 peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-focus:-top-2.5 peer-focus:text-xs peer-focus:text-blue-600">
                        Lesson Description
                    </label>
                </div>

                <!-- Lesson Type Selection -->
                <div>
                    <label class="block text-base font-semibold text-gray-700 mb-3">Lesson Type</label>
                    <div class="flex flex-wrap items-center space-x-4">
                        <label class="inline-flex items-center p-3 border-2 border-indigo-200 bg-indigo-50 rounded-xl cursor-pointer hover:bg-indigo-100 transition duration-150">
                            <input type="radio" name="is_live" value="0" class="form-radio text-indigo-600" onchange="toggleEditLessonFields(0)" id="edit_is_live_0">
                            <span class="ml-2 font-medium text-gray-700">Recorded Video</span>
                        </label>
                        <label class="inline-flex items-center p-3 border-2 border-red-200 bg-red-50 rounded-xl cursor-pointer hover:bg-red-100 transition duration-150">
                            <input type="radio" name="is_live" value="1" class="form-radio text-red-600" onchange="toggleEditLessonFields(1)" id="edit_is_live_1">
                            <span class="ml-2 font-medium text-gray-700">Live Class</span>
                        </label>
                    </div>
                </div>

                <!-- Custom Thumbnail Management -->
                <div class="border p-4 rounded-xl bg-gray-50 space-y-3 shadow-inner">
                    <label class="block text-sm font-semibold text-gray-800">🖼️ Thumbnail Management</label>

                    <!-- Existing Thumbnail Preview -->
                    <div id="edit-thumbnail-current-preview">
                        <!-- Content updated by JS -->
                    </div>

                    <!-- Delete Checkbox -->
                    <div id="edit-thumbnail-delete-option" class="hidden">
                        <label class="inline-flex items-center bg-red-100 p-2 rounded-lg border border-red-300 hover:bg-red-200 cursor-pointer transition duration-150">
                            <input type="checkbox" name="delete_current_thumbnail" id="delete_current_thumbnail" class="form-checkbox text-red-600 rounded">
                            <span class="ml-2 text-sm text-red-700 font-medium">Delete current custom thumbnail</span>
                        </label>
                    </div>
                    
                    <!-- New Thumbnail Upload -->
                    <div>
                        <label for="edit_custom_thumbnail" class="block text-sm font-medium text-gray-700 mt-2">Upload New Custom Thumbnail (Optional)</label>
                        <input type="file" name="custom_thumbnail" id="edit_custom_thumbnail" accept="image/png, image/jpeg, image/gif" 
                               class="mt-1 block w-full text-sm text-gray-600 
                                      file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 
                                      file:text-sm file:font-semibold file:bg-blue-100 file:text-blue-700 
                                      hover:file:bg-blue-200 transition duration-150">
                    </div>
                </div>


                <div id="edit-video-fields">
                    <!-- YouTube Link Field -->
                    <div class="relative group">
                        <input type="url" name="youtube_link" id="edit_youtube_link" placeholder=" "
                            class="block w-full px-4 py-3 text-gray-900 border border-gray-300 rounded-xl shadow-sm focus:ring-blue-500 focus:border-blue-500 transition duration-150 peer"
                            oninput="previewEditThumbnail(this.value)" />
                        <label for="edit_youtube_link" class="absolute left-3 -top-2.5 text-xs font-semibold text-gray-500 bg-white px-1 transition-all peer-placeholder-shown:top-3 peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-focus:-top-2.5 peer-focus:text-xs peer-focus:text-blue-600">
                            YouTube Video Link (Full URL)
                        </label>
                    </div>
                    <!-- Thumbnail Preview -->
                    <div id="edit-thumbnail-youtube-preview" class="mt-4 h-40 w-full bg-gray-100 rounded-xl flex items-center justify-center text-gray-500 text-sm overflow-hidden border-2 border-dashed border-gray-300">
                        Video Thumbnail Preview
                    </div>
                </div>

                <div id="edit-zoom-fields" class="hidden">
                    <!-- Zoom Link Field -->
                    <div class="relative group">
                        <input type="url" name="zoom_link" id="edit_zoom_link" placeholder=" " 
                            class="block w-full px-4 py-3 text-gray-900 border border-red-300 rounded-xl shadow-sm focus:ring-red-500 focus:border-red-500 transition duration-150 peer" />
                        <label for="edit_zoom_link" class="absolute left-3 -top-2.5 text-xs font-semibold text-gray-500 bg-white px-1 transition-all peer-placeholder-shown:top-3 peer-placeholder-shown:text-base peer-placeholder-shown:text-gray-400 peer-focus:-top-2.5 peer-focus:text-xs peer-focus:text-red-600">
                            Zoom Meeting Link (Required for Live Class)
                        </label>
                    </div>
                </div>
                
                <div class="pt-4 border-t flex justify-end space-x-3">
                    <button type="button" onclick="closeEditModal()" 
                            class="py-2 px-6 bg-gray-200 text-gray-700 rounded-xl font-semibold hover:bg-gray-300 transition duration-150 transform hover:scale-[1.05]">
                        Cancel
                    </button>
                    <button type="submit" name="update_lesson" 
                            class="py-2 px-6 bg-blue-600 text-white rounded-xl font-bold hover:bg-blue-700 transition duration-300 shadow-md shadow-blue-500/50 transform hover:scale-[1.05]">
                        Save Changes
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // Function to handle the visibility and required status of input fields (for ADD form)
    function toggleLessonFields(isLive) {
        const videoFields = document.getElementById('video-fields');
        const zoomFields = document.getElementById('zoom-fields');
        const youtubeLinkInput = document.getElementById('youtube_link');
        const zoomLinkInput = document.getElementById('zoom_link');

        if (isLive === 1) { // Live Class selected
            videoFields.classList.add('hidden');
            zoomFields.classList.remove('hidden');
            
            // Set required attributes
            youtubeLinkInput.removeAttribute('required');
            zoomLinkInput.setAttribute('required', 'required');

            // Clear video preview when switching to live
            document.getElementById('thumbnail-preview').innerHTML = 'Video Thumbnail Preview';

        } else { // Recorded Video selected
            videoFields.classList.remove('hidden');
            zoomFields.classList.add('hidden');
            
            // Set required attributes
            youtubeLinkInput.setAttribute('required', 'required');
            zoomLinkInput.removeAttribute('required');
            
            // Re-run preview on switch if link is present
            if (youtubeLinkInput.value) {
                 previewThumbnail(youtubeLinkInput.value);
            }
        }
    }

    // Function to preview YouTube thumbnail (for ADD form)
    function previewThumbnail(url) {
        const previewDiv = document.getElementById('thumbnail-preview');
        // Simple regex to get video ID (basic implementation)
        const match = url.match(/(?:youtube\.com\/(?:[^\/]+\/.+\/|\w\/\w+\?v=)|youtu\.be\/)([^&?]+)/);
        if (match && match[1]) {
            const videoId = match[1];
            const thumbnailUrl = `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`; // High quality thumbnail
            previewDiv.innerHTML = `<img src="${thumbnailUrl}" alt="Video Thumbnail" class="w-full h-full object-cover">`;
        } else {
            previewDiv.innerHTML = 'Video Thumbnail Preview';
        }
    }
    
    // --- NEW FUNCTIONS FOR EDIT MODAL ---
    
    function toggleEditLessonFields(isLive) {
        const videoFields = document.getElementById('edit-video-fields');
        const zoomFields = document.getElementById('edit-zoom-fields');
        const youtubeLinkInput = document.getElementById('edit_youtube_link');
        const zoomLinkInput = document.getElementById('edit_zoom_link');

        if (isLive === 1) { // Live Class selected
            videoFields.classList.add('hidden');
            zoomFields.classList.remove('hidden');
            
            youtubeLinkInput.removeAttribute('required');
            zoomLinkInput.setAttribute('required', 'required');

        } else { // Recorded Video selected
            videoFields.classList.remove('hidden');
            zoomFields.classList.add('hidden');
            
            youtubeLinkInput.setAttribute('required', 'required');
            zoomLinkInput.removeAttribute('required');

            // Re-run preview on switch if link is present
            if (youtubeLinkInput.value) {
                 previewEditThumbnail(youtubeLinkInput.value);
            }
        }
    }

    function previewEditThumbnail(url) {
        const previewDiv = document.getElementById('edit-thumbnail-youtube-preview');
        const match = url.match(/(?:youtube\.com\/(?:[^\/]+\/.+\/|\w\/\w+\?v=)|youtu\.be\/)([^&?]+)/);
        if (match && match[1]) {
            const videoId = match[1];
            const thumbnailUrl = `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`;
            previewDiv.innerHTML = `<img src="${thumbnailUrl}" alt="Video Thumbnail" class="w-full h-full object-cover">`;
        } else {
            previewDiv.innerHTML = 'Video Thumbnail Preview';
        }
    }
    
    function openEditModal(lesson) {
        // Modal Entrance Animation
        const modalContent = document.getElementById('edit-modal-content');
        modalContent.classList.remove('modal-leave-active');
        modalContent.classList.add('modal-enter-active');

        // Hidden fields
        document.getElementById('edit_lesson_id').value = lesson.id;
        document.getElementById('edit_pack_id').value = lesson.pack_id;
        document.getElementById('edit_current_thumbnail_path').value = lesson.thumbnail_path || '';
        
        // Main content fields
        document.getElementById('edit_title').value = lesson.title;
        document.getElementById('edit_description').value = lesson.description;
        document.getElementById('edit_custom_thumbnail').value = ''; // Clear file input
        
        // Reset delete checkbox
        document.getElementById('delete_current_thumbnail').checked = false;

        const isLive = parseInt(lesson.is_live);
        
        // Set lesson type radio button and trigger visibility toggle
        document.getElementById(`edit_is_live_${isLive}`).checked = true;
        // This function will also handle required attributes and YouTube preview
        toggleEditLessonFields(isLive); 

        if (isLive === 1) {
            document.getElementById('edit_zoom_link').value = lesson.zoom_link || '';
            document.getElementById('edit_youtube_link').value = ''; // Clear YouTube field
        } else {
            document.getElementById('edit_youtube_link').value = lesson.youtube_link || '';
            document.getElementById('edit_zoom_link').value = ''; // Clear Zoom field
            // The call in toggleEditLessonFields handles the preview
        }
        
        // Thumbnail Preview and Delete Option visibility
        const currentThumbnailPath = lesson.thumbnail_path;
        const currentThumbnailPreviewDiv = document.getElementById('edit-thumbnail-current-preview');
        const deleteOptionDiv = document.getElementById('edit-thumbnail-delete-option');

        if (currentThumbnailPath) {
            currentThumbnailPreviewDiv.innerHTML = `
                <p class="text-sm font-medium text-gray-700 mb-1">Current Custom Thumbnail:</p>
                <img src="${currentThumbnailPath}" alt="Current Custom Thumbnail" class="h-24 w-auto rounded-lg mb-2 object-cover border border-gray-300 shadow-md">
            `;
            deleteOptionDiv.classList.remove('hidden');
        } else {
            currentThumbnailPreviewDiv.innerHTML = `<p class="text-sm text-gray-500">No custom thumbnail currently set.</p>`;
            deleteOptionDiv.classList.add('hidden');
        }

        // Show the modal
        document.getElementById('edit-lesson-modal').classList.remove('hidden');
    }

    function closeEditModal() {
        const modalContent = document.getElementById('edit-modal-content');
        modalContent.classList.remove('modal-enter-active');
        modalContent.classList.add('modal-leave-active');

        // Hide after animation finishes (or immediately if preferred for speed)
        setTimeout(() => {
            document.getElementById('edit-lesson-modal').classList.add('hidden');
            modalContent.classList.remove('modal-leave-active'); // Cleanup
        }, 300); // Duration matches CSS transition
    }

    // Initial setup on load
    document.addEventListener('DOMContentLoaded', () => {
        // Run the toggle function once on load to ensure initial state is correct (default is video/isLive=0)
        toggleLessonFields(0);
        
        const linkInput = document.getElementById('youtube_link');
        if (linkInput && linkInput.value) {
            previewThumbnail(linkInput.value);
        }
    });
</script>

<?php render_main_content_end(); ?>