<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GenX Admin Portal</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700;800&family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Plus Jakarta Sans', 'sans-serif'],
                        outfit: ['Outfit', 'sans-serif'],
                    },
                    colors: {
                        brand: {
                            light: '#FFFFFF',
                            bg: '#F8FAFC',
                            indigo: '#4F46E5',
                            purple: '#7C3AED',
                            text: '#0F172A',
                            desc: '#475569',
                            muted: '#94A3B8',
                        }
                    },
                }
            }
        }
    </script>
    <style>
        body { background-color: #F8FAFC; color: #0F172A; }
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: #F8FAFC; }
        ::-webkit-scrollbar-thumb { background: #E2E8F0; border-radius: 3px; }
        ::-webkit-scrollbar-thumb:hover { background: #CBD5E1; }
        .modal-backdrop { backdrop-filter: blur(6px); }
        .lesson-row:hover .lesson-actions { opacity: 1; }
        .lesson-actions { opacity: 0; transition: opacity 0.2s; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
        .fade-in { animation: fadeIn 0.25s ease forwards; }
    </style>
</head>
<body class="font-sans antialiased min-h-screen">

    <!-- Decorative blobs -->
    <div class="fixed top-0 right-1/4 w-[500px] h-[500px] bg-purple-50/40 rounded-full blur-[120px] pointer-events-none -translate-y-1/2 z-0"></div>
    <div class="fixed bottom-0 left-1/4 w-[500px] h-[500px] bg-indigo-50/30 rounded-full blur-[120px] pointer-events-none translate-y-1/3 z-0"></div>

    <!-- Header -->
    <header class="border-b border-slate-200 bg-white/80 backdrop-blur-md sticky top-0 z-40">
        <div class="max-w-7xl mx-auto px-6 h-20 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <a href="<?= base_url() ?>" class="font-outfit text-xl font-extrabold tracking-wider text-brand-text">
                    GEN<span class="text-brand-indigo">X</span>
                </a>
                <span class="text-[9px] tracking-widest font-bold uppercase text-brand-purple border border-purple-200 bg-purple-50 px-2 py-0.5 rounded">Admin Panel</span>
            </div>
            <div class="flex items-center gap-4">
                <a href="<?= base_url() ?>" class="text-xs font-bold text-brand-desc hover:text-brand-text transition-colors flex items-center gap-1.5">← Site</a>
                <a href="<?= site_url('admin?action=logout') ?>" class="text-xs font-bold text-red-500 hover:text-red-700 border border-red-100 bg-red-50/50 px-3 py-1.5 rounded-lg transition-colors">Sign Out</a>
            </div>
        </div>
    </header>

    <?php
    $courseTitles = [
        'digital_marketing_foundational' => 'Digital Marketing Foundation',
        'web_development_foundational'   => 'Web Dev Foundation',
        'ai_python_fullstack'            => 'AI Python Full Stack',
        'digital_marketing_expert'       => 'Digital Marketing Expert',
    ];

    $total   = count($registrations);
    $revenue = 0;
    $recorded = 0; $live = 0;
    foreach ($registrations as $reg) {
        $amt = (float)($reg['amount'] ?? 0);
        if ($amt < 1000) { $recorded++; } else { $live++; }
        $revenue += $amt;
    }

    // Group lessons by course code
    $lessonsByCourse = [];
    foreach ($allLessons as $lesson) {
        $lessonsByCourse[$lesson['course_code']][] = $lesson;
    }
    $totalLessons = count($allLessons);
    ?>

    <main class="max-w-7xl mx-auto px-6 py-10 relative z-10">

        <!-- Stats -->
        <div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-10">
            <div class="bg-white border border-slate-200 p-5 rounded-2xl shadow-sm">
                <div class="text-[10px] text-brand-desc uppercase font-bold tracking-wider mb-1">Total Students</div>
                <div class="font-outfit text-3xl font-extrabold text-brand-text"><?= $total ?></div>
                <div class="text-[10px] text-brand-indigo font-bold mt-1">⚡ Active registrations</div>
            </div>
            <div class="bg-white border border-slate-200 p-5 rounded-2xl shadow-sm">
                <div class="text-[10px] text-brand-desc uppercase font-bold tracking-wider mb-1">Foundation Track</div>
                <div class="font-outfit text-3xl font-extrabold text-brand-text"><?= $recorded ?></div>
                <div class="text-[10px] text-brand-desc mt-1">Self-paced courses</div>
            </div>
            <div class="bg-white border border-slate-200 p-5 rounded-2xl shadow-sm">
                <div class="text-[10px] text-brand-desc uppercase font-bold tracking-wider mb-1">Expert Programs</div>
                <div class="font-outfit text-3xl font-extrabold text-brand-text"><?= $live ?></div>
                <div class="text-[10px] text-brand-desc mt-1">Live mentoring</div>
            </div>
            <div class="bg-white border border-slate-200 p-5 rounded-2xl shadow-sm">
                <div class="text-[10px] text-brand-desc uppercase font-bold tracking-wider mb-1">Total Revenue</div>
                <div class="font-outfit text-3xl font-extrabold text-brand-indigo">₹<?= number_format($revenue, 0) ?></div>
                <div class="text-[10px] text-emerald-600 font-bold mt-1">✓ Collected fees</div>
            </div>
        </div>

        <!-- Tab Navigation -->
        <div class="flex gap-1 bg-slate-100 p-1 rounded-xl w-fit mb-8" id="admin-tab-nav">
            <button onclick="switchAdminTab('students')" id="tab-btn-students"
                class="px-5 py-2.5 rounded-lg text-xs font-bold transition-all duration-200 bg-white text-brand-indigo shadow-sm">
                👥 Student Logbook
            </button>
            <button onclick="switchAdminTab('courses')" id="tab-btn-courses"
                class="px-5 py-2.5 rounded-lg text-xs font-bold transition-all duration-200 text-brand-desc hover:text-brand-text">
                🎬 Course Content
            </button>
        </div>

        <!-- ═══════════════════════════════════════════════ -->
        <!-- TAB 1: STUDENT LOGBOOK -->
        <!-- ═══════════════════════════════════════════════ -->
        <div id="tab-students" class="fade-in">
            <div class="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-sm">
                <div class="px-6 py-4 border-b border-slate-200 flex items-center justify-between bg-slate-50/50">
                    <div>
                        <h3 class="font-bold text-sm text-brand-text">Enrollment List</h3>
                        <p class="text-[10px] text-brand-desc mt-0.5"><?= $total ?> students enrolled</p>
                    </div>
                    <button onclick="openAddStudentModal()"
                        class="flex items-center gap-2 bg-brand-indigo hover:bg-indigo-700 text-white text-xs font-bold px-4 py-2 rounded-xl transition-all duration-200 shadow-md shadow-indigo-200">
                        <span class="text-sm leading-none">+</span> Add Student
                    </button>
                </div>
                <div class="overflow-x-auto">
                    <?php if (empty($registrations)): ?>
                        <div class="p-12 text-center text-brand-desc space-y-2">
                            <span class="text-3xl block">📁</span>
                            <div class="text-xs font-semibold">No student records found.</div>
                        </div>
                    <?php else: ?>
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-slate-50 text-[10px] font-bold uppercase tracking-wider text-brand-desc border-b border-slate-200">
                                    <th class="px-5 py-4">ID</th>
                                    <th class="px-5 py-4">Name</th>
                                    <th class="px-5 py-4">Email</th>
                                    <th class="px-5 py-4">Phone</th>
                                    <th class="px-5 py-4">Course</th>
                                    <th class="px-5 py-4">Batch</th>
                                    <th class="px-5 py-4">Amount</th>
                                    <th class="px-5 py-4">Date</th>
                                    <th class="px-5 py-4">Status</th>
                                    <th class="px-5 py-4">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 text-xs text-brand-desc bg-white">
                                <?php foreach ($registrations as $reg): ?>
                                    <tr class="hover:bg-slate-50/60 transition-colors group">
                                        <td class="px-5 py-3.5 font-mono text-slate-400"><?= esc($reg['id']) ?></td>
                                        <td class="px-5 py-3.5 font-semibold text-brand-text"><?= esc($reg['name']) ?></td>
                                        <td class="px-5 py-3.5"><?= esc($reg['email']) ?></td>
                                        <td class="px-5 py-3.5 font-mono"><?= esc($reg['phone']) ?></td>
                                        <td class="px-5 py-3.5 font-semibold text-brand-text"><?= esc($courseTitles[$reg['course']] ?? $reg['course']) ?></td>
                                        <td class="px-5 py-3.5">
                                            <?php if ($reg['batch'] === 'weekend'): ?>
                                                <span class="px-2 py-0.5 rounded-full text-[10px] font-bold bg-indigo-50 text-brand-indigo border border-indigo-100">Weekend</span>
                                            <?php else: ?>
                                                <span class="px-2 py-0.5 rounded-full text-[10px] font-bold bg-purple-50 text-brand-purple border border-purple-100">Weekday</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-5 py-3.5 font-bold text-brand-text">₹<?= number_format($reg['amount'], 0) ?></td>
                                        <td class="px-5 py-3.5 font-mono text-slate-400 text-[10px]"><?= esc($reg['created_at']) ?></td>
                                        <td class="px-5 py-3.5">
                                            <?php $statusColor = $reg['status'] === 'completed' ? 'bg-emerald-50 text-emerald-700 border-emerald-200' : 'bg-amber-50 text-amber-700 border-amber-200'; ?>
                                            <span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-bold border <?= $statusColor ?>">
                                                <span class="w-1.5 h-1.5 rounded-full <?= $reg['status'] === 'completed' ? 'bg-emerald-500' : 'bg-amber-500' ?>"></span>
                                                <?= esc(ucfirst($reg['status'])) ?>
                                            </span>
                                        </td>
                                        <td class="px-5 py-3.5">
                                            <div class="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                                <button onclick='openEditStudentModal(<?= json_encode(['id'=>$reg['id'],'name'=>$reg['name'],'email'=>$reg['email'],'phone'=>$reg['phone'],'course'=>$reg['course'],'batch'=>$reg['batch'],'amount'=>$reg['amount'],'status'=>$reg['status']]) ?>)'
                                                    class="text-[10px] font-bold text-brand-desc hover:text-brand-text border border-slate-200 bg-white px-3 py-1.5 rounded-lg transition-colors hover:border-slate-300 whitespace-nowrap">
                                                    ✏️ Edit
                                                </button>
                                                <button onclick="confirmStudentDelete(<?= $reg['id'] ?>, '<?= esc($reg['name'], 'js') ?>')"
                                                    class="text-[10px] font-bold text-red-500 hover:text-red-700 border border-red-100 bg-red-50 px-3 py-1.5 rounded-lg transition-colors hover:border-red-200 whitespace-nowrap">
                                                    🗑 Delete
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- ═══════════════════════════════════════════════ -->
        <!-- TAB 2: COURSE CONTENT MANAGER -->
        <!-- ═══════════════════════════════════════════════ -->
        <div id="tab-courses" class="hidden fade-in">

            <!-- Top Bar -->
            <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 mb-6">
                <div>
                    <h2 class="font-outfit text-lg font-extrabold text-brand-text">Course Content Manager</h2>
                    <p class="text-xs text-brand-desc mt-0.5"><?= $totalLessons ?> lessons uploaded across <?= count($courseTitles) ?> courses.</p>
                </div>
                <button onclick="openAddModal()" class="flex items-center gap-2 bg-brand-indigo hover:bg-indigo-700 text-white text-xs font-bold px-5 py-2.5 rounded-xl transition-all duration-200 shadow-md shadow-indigo-200 hover:shadow-lg hover:shadow-indigo-300 hover:-translate-y-0.5">
                    <span class="text-base leading-none">+</span> Add Lesson
                </button>
            </div>

            <!-- Course Sections -->
            <?php foreach ($courseTitles as $code => $title): ?>
                <?php $lessons = $lessonsByCourse[$code] ?? []; ?>
                <div class="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-sm mb-6">
                    <!-- Course Header -->
                    <div class="px-6 py-4 border-b border-slate-200 bg-slate-50/60 flex items-center justify-between">
                        <div>
                            <h3 class="font-bold text-sm text-brand-text"><?= esc($title) ?></h3>
                            <p class="text-[10px] text-brand-desc font-mono mt-0.5"><?= esc($code) ?></p>
                        </div>
                        <div class="flex items-center gap-3">
                            <?php if (!empty($lessons)): ?>
                                <?php $type = $lessons[0]['course_type'] ?? 'modular'; ?>
                                <span class="text-[10px] font-bold uppercase tracking-widest px-2.5 py-0.5 rounded-full border <?= $type === 'modular' ? 'bg-indigo-50 text-brand-indigo border-indigo-200' : 'bg-amber-50 text-amber-700 border-amber-200' ?>">
                                    <?= $type === 'modular' ? '📦 Modular' : '🎯 One-Shot' ?>
                                </span>
                            <?php endif; ?>
                            <span class="text-[10px] font-bold text-brand-desc"><?= count($lessons) ?> lesson<?= count($lessons) !== 1 ? 's' : '' ?></span>
                            <button onclick="openAddModal('<?= esc($code) ?>')" class="text-[10px] font-bold text-brand-indigo hover:text-indigo-800 border border-indigo-200 bg-indigo-50 px-3 py-1 rounded-lg transition-colors">+ Add</button>
                        </div>
                    </div>

                    <?php if (empty($lessons)): ?>
                        <div class="py-10 text-center text-brand-desc">
                            <div class="text-2xl mb-2">🎬</div>
                            <div class="text-xs font-semibold">No lessons yet for this course.</div>
                            <div class="text-[10px] mt-1">Click "+ Add" to upload the first YouTube lesson.</div>
                        </div>
                    <?php else: ?>
                        <!-- Group by module -->
                        <?php
                        $grouped = [];
                        foreach ($lessons as $l) {
                            $key = ($l['module_order'] ?? 1) . '||' . ($l['module_name'] ?? '');
                            $grouped[$key][] = $l;
                        }
                        ksort($grouped);
                        $isModular = ($lessons[0]['course_type'] ?? 'modular') === 'modular';
                        ?>
                        <div class="divide-y divide-slate-100">
                            <?php foreach ($grouped as $groupKey => $groupLessons): ?>
                                <?php
                                [,$moduleName] = explode('||', $groupKey, 2);
                                ?>
                                <?php if ($isModular && !empty($moduleName)): ?>
                                    <div class="px-6 pt-4 pb-1">
                                        <p class="text-[10px] font-bold text-brand-indigo uppercase tracking-widest"><?= esc($moduleName) ?></p>
                                    </div>
                                <?php endif; ?>

                                <?php foreach ($groupLessons as $lesson): ?>
                                    <?php
                                    $ytId  = \App\Models\CourseModel::extractYouTubeId($lesson['youtube_url']);
                                    $thumb = $ytId ? "https://img.youtube.com/vi/{$ytId}/mqdefault.jpg" : null;
                                    ?>
                                    <div class="lesson-row px-6 py-4 flex items-center gap-4 hover:bg-slate-50/60 transition-colors group" id="lesson-row-<?= $lesson['id'] ?>">
                                        <!-- Thumbnail -->
                                        <div class="shrink-0 w-20 h-12 rounded-lg overflow-hidden bg-slate-100 border border-slate-200">
                                            <?php if ($thumb): ?>
                                                <img src="<?= $thumb ?>" alt="thumb" class="w-full h-full object-cover">
                                            <?php else: ?>
                                                <div class="w-full h-full flex items-center justify-center text-slate-400 text-xl">🎬</div>
                                            <?php endif; ?>
                                        </div>

                                        <!-- Info -->
                                        <div class="flex-grow min-w-0">
                                            <div class="flex items-center gap-2 flex-wrap">
                                                <span class="text-xs font-bold text-brand-text truncate"><?= esc($lesson['lesson_title']) ?></span>
                                                <?php if ($lesson['duration']): ?>
                                                    <span class="text-[9px] font-bold text-brand-desc">⏱ <?= esc($lesson['duration']) ?></span>
                                                <?php endif; ?>
                                            </div>
                                            <?php if ($lesson['notes']): ?>
                                                <p class="text-[10px] text-brand-desc mt-0.5 truncate max-w-lg"><?= esc($lesson['notes']) ?></p>
                                            <?php endif; ?>
                                            <?php if ($lesson['youtube_url']): ?>
                                                <a href="<?= esc($lesson['youtube_url']) ?>" target="_blank" class="text-[10px] text-brand-indigo hover:underline font-mono mt-0.5 block truncate max-w-sm"><?= esc($lesson['youtube_url']) ?></a>
                                            <?php endif; ?>
                                        </div>

                                        <!-- Actions -->
                                        <div class="lesson-actions shrink-0 flex items-center gap-2">
                                            <button onclick='openEditModal(<?= json_encode($lesson) ?>)'
                                                class="text-[10px] font-bold text-brand-desc hover:text-brand-text border border-slate-200 bg-white px-3 py-1.5 rounded-lg transition-colors hover:border-slate-300">
                                                ✏️ Edit
                                            </button>
                                            <button onclick="confirmDelete(<?= $lesson['id'] ?>, '<?= esc($lesson['lesson_title'], 'js') ?>')"
                                                class="text-[10px] font-bold text-red-500 hover:text-red-700 border border-red-100 bg-red-50 px-3 py-1.5 rounded-lg transition-colors hover:border-red-200">
                                                🗑 Delete
                                            </button>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>

    </main>

    <!-- Footer -->
    <footer class="border-t border-slate-200 bg-white py-8 text-center text-xs text-brand-desc mt-16">
        <div class="max-w-7xl mx-auto px-6">
            &copy; 2026 GenX Institute Admin Panel. Built with CodeIgniter 4.
        </div>
    </footer>

    <!-- ═══════════════════════════════════════════════ -->
    <!-- ADD / EDIT STUDENT MODAL                       -->
    <!-- ═══════════════════════════════════════════════ -->
    <div id="student-modal" class="fixed inset-0 z-50 hidden flex items-center justify-center p-4">
        <div class="absolute inset-0 bg-slate-900/50 modal-backdrop" onclick="closeStudentModal()"></div>
        <div class="relative bg-white rounded-2xl shadow-2xl w-full max-w-lg z-10 overflow-y-auto max-h-[90vh]">
            <!-- Header -->
            <div class="px-6 py-5 border-b border-slate-200 flex items-center justify-between sticky top-0 bg-white z-10">
                <h3 id="student-modal-title" class="font-outfit text-base font-extrabold text-brand-text">Add Student</h3>
                <button onclick="closeStudentModal()" class="w-7 h-7 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-brand-desc transition-colors text-sm">✕</button>
            </div>

            <!-- Form -->
            <form id="student-form" class="px-6 py-5 space-y-4">
                <input type="hidden" id="sform-id" value="">

                <div class="grid grid-cols-2 gap-3">
                    <div class="col-span-2">
                        <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Full Name *</label>
                        <input type="text" id="sform-name" placeholder="e.g. Rahul Sharma"
                            class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors placeholder-slate-300">
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Email *</label>
                        <input type="email" id="sform-email" placeholder="student@email.com"
                            class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors placeholder-slate-300">
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Phone *</label>
                        <input type="text" id="sform-phone" placeholder="10-digit number"
                            class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors placeholder-slate-300">
                    </div>
                </div>

                <div>
                    <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Course *</label>
                    <select id="sform-course" class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-semibold text-brand-text focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors">
                        <?php foreach ($courseTitles as $code => $title): ?>
                            <option value="<?= $code ?>"><?= $title ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="grid grid-cols-3 gap-3">
                    <div>
                        <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Batch</label>
                        <select id="sform-batch" class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-semibold text-brand-text focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors">
                            <option value="weekday">Weekday</option>
                            <option value="weekend">Weekend</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Amount (₹)</label>
                        <input type="number" id="sform-amount" placeholder="0" min="0"
                            class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors">
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Status</label>
                        <select id="sform-status" class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-semibold text-brand-text focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors">
                            <option value="completed">Completed</option>
                            <option value="pending">Pending</option>
                        </select>
                    </div>
                </div>

                <div>
                    <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">
                        Login Password
                        <span id="sform-pwd-hint" class="normal-case font-normal text-brand-muted ml-1">(required for new student)</span>
                    </label>
                    <input type="password" id="sform-password" placeholder="Leave blank to keep existing password"
                        class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors placeholder-slate-300">
                </div>

                <!-- Error -->
                <div id="sform-error" class="hidden text-xs text-red-600 font-semibold bg-red-50 border border-red-100 px-4 py-2.5 rounded-xl"></div>

                <!-- Actions -->
                <div class="flex gap-3 pt-1">
                    <button type="button" onclick="closeStudentModal()" class="flex-1 border border-slate-200 text-xs font-bold text-brand-desc hover:text-brand-text py-2.5 rounded-xl transition-colors">Cancel</button>
                    <button type="button" onclick="submitStudent()" id="sform-submit-btn"
                        class="flex-1 bg-brand-indigo hover:bg-indigo-700 text-white text-xs font-bold py-2.5 rounded-xl transition-all duration-200 shadow-md shadow-indigo-200">
                        Save Student
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════ -->
    <!-- ADD / EDIT LESSON MODAL -->
    <!-- ═══════════════════════════════════════════════ -->
    <div id="lesson-modal" class="fixed inset-0 z-50 hidden flex items-center justify-center p-4">
        <!-- Backdrop -->
        <div class="absolute inset-0 bg-slate-900/50 modal-backdrop" onclick="closeModal()"></div>

        <!-- Modal card -->
        <div class="relative bg-white rounded-2xl shadow-2xl w-full max-w-lg z-10 overflow-y-auto max-h-[90vh]">
            <!-- Modal header -->
            <div class="px-6 py-5 border-b border-slate-200 flex items-center justify-between sticky top-0 bg-white z-10">
                <h3 id="modal-title" class="font-outfit text-base font-extrabold text-brand-text">Add New Lesson</h3>
                <button onclick="closeModal()" class="w-7 h-7 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-brand-desc transition-colors text-sm">✕</button>
            </div>

            <!-- Form -->
            <form id="lesson-form" class="px-6 py-5 space-y-5">
                <input type="hidden" id="form-lesson-id" value="">

                <!-- Course Code -->
                <div>
                    <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Course *</label>
                    <select id="form-course-code" class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs font-semibold text-brand-text focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors">
                        <?php foreach ($courseTitles as $code => $title): ?>
                            <option value="<?= $code ?>"><?= $title ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Course Type -->
                <div>
                    <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Course Type *</label>
                    <div class="flex gap-3">
                        <label class="flex items-center gap-2 cursor-pointer border border-slate-200 rounded-xl px-4 py-2.5 flex-1 hover:border-brand-indigo/40 has-[:checked]:border-brand-indigo has-[:checked]:bg-indigo-50 transition-all">
                            <input type="radio" name="course_type" id="type-modular" value="modular" checked onchange="toggleModuleFields()" class="text-brand-indigo">
                            <span class="text-xs font-bold text-brand-text">📦 Modular</span>
                        </label>
                        <label class="flex items-center gap-2 cursor-pointer border border-slate-200 rounded-xl px-4 py-2.5 flex-1 hover:border-amber-400/40 has-[:checked]:border-amber-400 has-[:checked]:bg-amber-50 transition-all">
                            <input type="radio" name="course_type" id="type-oneshot" value="one_shot" onchange="toggleModuleFields()" class="text-amber-500">
                            <span class="text-xs font-bold text-brand-text">🎯 One-Shot</span>
                        </label>
                    </div>
                </div>

                <!-- Module fields (only for modular) -->
                <div id="module-fields" class="space-y-4">
                    <div>
                        <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Module Name *
                            <span class="normal-case font-normal text-brand-muted ml-1">(this is the video/lesson title)</span>
                        </label>
                        <input type="text" id="form-module-name" placeholder="e.g. Module 1: Introduction to SEO"
                            class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors placeholder-slate-300">
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Module Order</label>
                        <input type="number" id="form-module-order" value="1" min="1"
                            class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors">
                    </div>
                </div>

                <!-- Lesson Title (One-Shot only) -->
                <div id="oneshot-title-field" style="display:none">
                    <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Video Title *</label>
                    <input type="text" id="form-lesson-title" placeholder="e.g. Complete Digital Marketing Course"
                        class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors placeholder-slate-300">
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Lesson Order</label>
                        <input type="number" id="form-lesson-order" value="1" min="1"
                            class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors">
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Duration (optional)</label>
                        <input type="text" id="form-duration" placeholder="e.g. 15:30"
                            class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors placeholder-slate-300">
                    </div>
                </div>

                <!-- YouTube URL -->
                <div>
                    <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">YouTube URL</label>
                    <input type="url" id="form-youtube-url" placeholder="https://youtu.be/xxxxxx or https://youtube.com/watch?v=xxxxxx"
                        class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors placeholder-slate-300"
                        oninput="previewYouTube(this.value)">
                    <!-- YouTube preview -->
                    <div id="yt-preview" class="hidden mt-2 aspect-video rounded-xl overflow-hidden border border-slate-200 bg-slate-100">
                        <iframe id="yt-preview-frame" src="" allowfullscreen class="w-full h-full"></iframe>
                    </div>
                </div>

                <!-- Notes -->
                <div>
                    <label class="block text-[10px] font-bold text-brand-desc uppercase tracking-wider mb-1.5">Lesson Notes (optional)</label>
                    <textarea id="form-notes" rows="3" placeholder="Summary or key takeaways for this lesson..."
                        class="w-full border border-slate-200 rounded-xl px-4 py-2.5 text-xs focus:outline-none focus:ring-2 focus:ring-brand-indigo/30 focus:border-brand-indigo transition-colors resize-none placeholder-slate-300"></textarea>
                </div>

                <!-- Error msg -->
                <div id="form-error" class="hidden text-xs text-red-600 font-semibold bg-red-50 border border-red-100 px-4 py-2.5 rounded-xl"></div>

                <!-- Actions -->
                <div class="flex gap-3 pt-1">
                    <button type="button" onclick="closeModal()" class="flex-1 border border-slate-200 text-xs font-bold text-brand-desc hover:text-brand-text py-2.5 rounded-xl transition-colors">Cancel</button>
                    <button type="button" onclick="submitLesson()" id="form-submit-btn"
                        class="flex-1 bg-brand-indigo hover:bg-indigo-700 text-white text-xs font-bold py-2.5 rounded-xl transition-all duration-200 shadow-md shadow-indigo-200">
                        Save Lesson
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Delete Confirm Modal -->
    <div id="delete-modal" class="fixed inset-0 z-50 hidden flex items-center justify-center p-4">
        <div class="absolute inset-0 bg-slate-900/50 modal-backdrop" onclick="closeDeleteModal()"></div>
        <div class="relative bg-white rounded-2xl shadow-2xl w-full max-w-sm z-10 p-6 space-y-4">
            <div class="text-2xl text-center">🗑</div>
            <h3 class="font-outfit text-base font-extrabold text-brand-text text-center">Delete Lesson?</h3>
            <p id="delete-confirm-text" class="text-xs text-brand-desc text-center leading-relaxed"></p>
            <div class="flex gap-3">
                <button onclick="closeDeleteModal()" class="flex-1 border border-slate-200 text-xs font-bold text-brand-desc py-2.5 rounded-xl transition-colors hover:bg-slate-50">Cancel</button>
                <button onclick="executeDelete()" class="flex-1 bg-red-500 hover:bg-red-600 text-white text-xs font-bold py-2.5 rounded-xl transition-colors">Delete</button>
            </div>
        </div>
    </div>

    <script>
    // PHP-generated endpoint URLs (avoids index.php slash bug)
    const URL_ADD    = '<?= site_url("admin/lesson/add") ?>';
    const URL_UPDATE = '<?= site_url("admin/lesson/update") ?>';
    const URL_DELETE = '<?= site_url("admin/lesson/delete") ?>';
    let deleteLessonId = null;

    // ─── Tab switching ───────────────────────────────
    function switchAdminTab(tabName) {
        ['students', 'courses'].forEach(t => {
            const panel = document.getElementById(`tab-${t}`);
            const btn   = document.getElementById(`tab-btn-${t}`);
            if (t === tabName) {
                panel.classList.remove('hidden');
                btn.classList.add('bg-white', 'text-brand-indigo', 'shadow-sm');
                btn.classList.remove('text-brand-desc', 'hover:text-brand-text');
            } else {
                panel.classList.add('hidden');
                btn.classList.remove('bg-white', 'text-brand-indigo', 'shadow-sm');
                btn.classList.add('text-brand-desc', 'hover:text-brand-text');
            }
        });
    }

    // ─── YouTube preview ─────────────────────────────
    function extractYtId(url) {
        let m;
        if ((m = url.match(/youtu\.be\/([a-zA-Z0-9_-]{11})/))) return m[1];
        if ((m = url.match(/[?&]v=([a-zA-Z0-9_-]{11})/)))    return m[1];
        if ((m = url.match(/embed\/([a-zA-Z0-9_-]{11})/)))    return m[1];
        return null;
    }

    function previewYouTube(url) {
        const preview = document.getElementById('yt-preview');
        const frame   = document.getElementById('yt-preview-frame');
        const id = extractYtId(url);
        if (id) {
            frame.src = `https://www.youtube.com/embed/${id}`;
            preview.classList.remove('hidden');
        } else {
            frame.src = '';
            preview.classList.add('hidden');
        }
    }

    // ─── Toggle module fields ────────────────────────
    function toggleModuleFields() {
        const isModular = document.getElementById('type-modular').checked;
        document.getElementById('module-fields').style.display        = isModular ? '' : 'none';
        document.getElementById('oneshot-title-field').style.display  = isModular ? 'none' : '';
    }

    // ─── Add Modal ───────────────────────────────────
    function openAddModal(courseCode = '') {
        resetForm();
        document.getElementById('modal-title').textContent = 'Add New Lesson';
        document.getElementById('form-submit-btn').textContent = 'Save Lesson';
        if (courseCode) {
            document.getElementById('form-course-code').value = courseCode;
        }
        showModal();
    }

    // ─── Edit Modal ──────────────────────────────────
    function openEditModal(lesson) {
        resetForm();
        document.getElementById('modal-title').textContent = 'Edit Lesson';
        document.getElementById('form-submit-btn').textContent = 'Update Lesson';
        document.getElementById('form-lesson-id').value    = lesson.id;
        document.getElementById('form-course-code').value  = lesson.course_code;
        document.getElementById('form-module-order').value = lesson.module_order || 1;
        document.getElementById('form-lesson-order').value = lesson.lesson_order;
        document.getElementById('form-youtube-url').value  = lesson.youtube_url || '';
        document.getElementById('form-duration').value     = lesson.duration || '';
        document.getElementById('form-notes').value        = lesson.notes || '';

        if (lesson.course_type === 'one_shot') {
            document.getElementById('type-oneshot').checked = true;
            document.getElementById('form-lesson-title').value = lesson.lesson_title || '';
        } else {
            document.getElementById('type-modular').checked = true;
            // For modular: module_name is the lesson title
            document.getElementById('form-module-name').value = lesson.module_name || lesson.lesson_title || '';
        }
        toggleModuleFields();
        if (lesson.youtube_url) previewYouTube(lesson.youtube_url);
        showModal();
    }


    function showModal() {
        document.getElementById('lesson-modal').classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }
    function closeModal() {
        document.getElementById('lesson-modal').classList.add('hidden');
        document.body.style.overflow = '';
    }
    function resetForm() {
        document.getElementById('form-lesson-id').value    = '';
        document.getElementById('form-lesson-title').value = '';
        document.getElementById('form-module-name').value  = '';
        document.getElementById('form-module-order').value = 1;
        document.getElementById('form-lesson-order').value = 1;
        document.getElementById('form-youtube-url').value  = '';
        document.getElementById('form-duration').value     = '';
        document.getElementById('form-notes').value        = '';
        document.getElementById('form-error').classList.add('hidden');
        document.getElementById('yt-preview').classList.add('hidden');
        document.getElementById('yt-preview-frame').src   = '';
        document.getElementById('type-modular').checked = true;
        toggleModuleFields(); // default: modular
    }

    // ─── Submit ──────────────────────────────────────
    async function submitLesson() {
        const id   = document.getElementById('form-lesson-id').value;
        const code = document.getElementById('form-course-code').value;
        const type = document.querySelector('input[name="course_type"]:checked').value;

        // For modular: lesson_title = module_name. For one-shot: lesson_title = video title field.
        const moduleName = document.getElementById('form-module-name').value.trim();
        const oneshotTitle = document.getElementById('form-lesson-title').value.trim();
        const lessonTitle  = type === 'modular' ? moduleName : oneshotTitle;

        if (!lessonTitle) {
            showFormError(type === 'modular'
                ? 'Module Name is required.'
                : 'Video Title is required.');
            return;
        }

        const ytUrl = document.getElementById('form-youtube-url').value.trim();
        if (!ytUrl) {
            showFormError('YouTube URL is required.');
            return;
        }

        const body = new FormData();
        body.append('course_code',  code);
        body.append('course_type',  type);
        body.append('module_name',  type === 'modular' ? moduleName : '');
        body.append('module_order', type === 'modular' ? document.getElementById('form-module-order').value : 1);
        body.append('lesson_title', lessonTitle);   // module name IS the lesson title for modular
        body.append('lesson_order', document.getElementById('form-lesson-order').value);
        body.append('youtube_url',  ytUrl);
        body.append('duration',     document.getElementById('form-duration').value.trim());
        body.append('notes',        document.getElementById('form-notes').value.trim());

        const url = id
            ? `${URL_UPDATE}/${id}`
            : URL_ADD;

        const btn = document.getElementById('form-submit-btn');
        btn.textContent = 'Saving...';
        btn.disabled = true;

        try {
            const res  = await fetch(url, { method: 'POST', body });

            // Guard: if server returns non-JSON (e.g. redirect/HTML error page)
            const text = await res.text();
            let json;
            try { json = JSON.parse(text); }
            catch (_) {
                showFormError('Server error (non-JSON response). Check PHP logs.');
                return;
            }

            if (json.success) {
                closeModal();
                location.reload();
            } else {
                showFormError(json.error || 'Something went wrong.');
            }
        } catch (e) {
            showFormError('Network error: ' + e.message);
        } finally {
            btn.textContent = id ? 'Update Lesson' : 'Save Lesson';
            btn.disabled = false;
        }
    }

    function showFormError(msg) {
        const el = document.getElementById('form-error');
        el.textContent = msg;
        el.classList.remove('hidden');
    }

    // ─── Delete ──────────────────────────────────────
    function confirmDelete(id, title) {
        deleteLessonId = id;
        document.getElementById('delete-confirm-text').textContent = `Are you sure you want to delete "${title}"? This cannot be undone.`;
        document.getElementById('delete-modal').classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }
    function closeDeleteModal() {
        deleteLessonId = null;
        document.getElementById('delete-modal').classList.add('hidden');
        document.body.style.overflow = '';
    }
    async function executeDelete() {
        if (!deleteLessonId) return;
        try {
            const res  = await fetch(`${URL_DELETE}/${deleteLessonId}`, { method: 'POST' });
            const text = await res.text();
            let json;
            try { json = JSON.parse(text); } catch (_) { json = { success: false }; }
            if (json.success) {
                closeDeleteModal();
                location.reload();
            }
        } catch (e) { console.error('Delete failed', e); }
    }

    // Init: check URL param for active tab
    document.addEventListener('DOMContentLoaded', () => {
        const params = new URLSearchParams(window.location.search);
        if (params.get('tab') === 'courses') {
            switchAdminTab('courses');
        }
    });

    // ═══════════════════════════════════════════════
    // STUDENT CRUD JS
    // ═══════════════════════════════════════════════
    const URL_STU_ADD    = '<?= site_url("admin/student/add") ?>';
    const URL_STU_UPDATE = '<?= site_url("admin/student/update") ?>';
    const URL_STU_DELETE = '<?= site_url("admin/student/delete") ?>';
    let deleteStudentId  = null;

    function openAddStudentModal() {
        resetStudentForm();
        document.getElementById('student-modal-title').textContent = 'Add New Student';
        document.getElementById('sform-submit-btn').textContent    = 'Save Student';
        document.getElementById('sform-pwd-hint').textContent      = '(required for new student)';
        document.getElementById('student-modal').classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }

    function openEditStudentModal(student) {
        resetStudentForm();
        document.getElementById('student-modal-title').textContent = 'Edit Student';
        document.getElementById('sform-submit-btn').textContent    = 'Update Student';
        document.getElementById('sform-pwd-hint').textContent      = '(leave blank to keep existing)';
        document.getElementById('sform-id').value     = student.id;
        document.getElementById('sform-name').value   = student.name   || '';
        document.getElementById('sform-email').value  = student.email  || '';
        document.getElementById('sform-phone').value  = student.phone  || '';
        document.getElementById('sform-course').value = student.course || '';
        document.getElementById('sform-batch').value  = student.batch  || 'weekday';
        document.getElementById('sform-amount').value = student.amount || 0;
        document.getElementById('sform-status').value = student.status || 'completed';
        document.getElementById('student-modal').classList.remove('hidden');
        document.body.style.overflow = 'hidden';
    }

    function closeStudentModal() {
        document.getElementById('student-modal').classList.add('hidden');
        document.body.style.overflow = '';
    }

    function resetStudentForm() {
        ['sform-id','sform-name','sform-email','sform-phone','sform-password'].forEach(id => {
            document.getElementById(id).value = '';
        });
        document.getElementById('sform-amount').value  = '';
        document.getElementById('sform-batch').value   = 'weekday';
        document.getElementById('sform-status').value  = 'completed';
        document.getElementById('sform-error').classList.add('hidden');
    }

    async function submitStudent() {
        const id    = document.getElementById('sform-id').value;
        const name  = document.getElementById('sform-name').value.trim();
        const email = document.getElementById('sform-email').value.trim();
        const phone = document.getElementById('sform-phone').value.trim();

        if (!name)  { showStudentError('Full name is required.');  return; }
        if (!email) { showStudentError('Email is required.');       return; }
        if (!phone) { showStudentError('Phone is required.');       return; }

        const password = document.getElementById('sform-password').value;
        if (!id && !password) {
            showStudentError('Password is required for a new student.');
            return;
        }

        const body = new FormData();
        body.append('name',     name);
        body.append('email',    email);
        body.append('phone',    phone);
        body.append('course',   document.getElementById('sform-course').value);
        body.append('batch',    document.getElementById('sform-batch').value);
        body.append('amount',   document.getElementById('sform-amount').value || 0);
        body.append('status',   document.getElementById('sform-status').value);
        body.append('password', document.getElementById('sform-password').value);

        const url = id ? `${URL_STU_UPDATE}/${id}` : URL_STU_ADD;
        const btn = document.getElementById('sform-submit-btn');
        btn.textContent = 'Saving...';
        btn.disabled    = true;

        try {
            const res  = await fetch(url, { method: 'POST', body });
            const text = await res.text();
            let json;
            try { json = JSON.parse(text); }
            catch (_) { showStudentError('Server error (non-JSON). Check PHP logs.'); return; }

            if (json.success) {
                closeStudentModal();
                location.reload();
            } else {
                showStudentError(json.error || 'Something went wrong.');
            }
        } catch (e) {
            showStudentError('Network error: ' + e.message);
        } finally {
            btn.textContent = id ? 'Update Student' : 'Save Student';
            btn.disabled    = false;
        }
    }

    function showStudentError(msg) {
        const el = document.getElementById('sform-error');
        el.textContent = msg;
        el.classList.remove('hidden');
    }

    function confirmStudentDelete(id, name) {
        deleteStudentId = id;
        document.getElementById('delete-confirm-text').textContent = `Are you sure you want to delete "${name}"? This cannot be undone.`;
        document.getElementById('delete-modal').classList.remove('hidden');
        document.body.style.overflow = 'hidden';
        // Override execute to use student delete
        window._deleteTarget = 'student';
    }

    // Patch executeDelete to handle both lesson and student deletes
    async function executeDelete() {
        const isStudent = window._deleteTarget === 'student';
        const id        = isStudent ? deleteStudentId : deleteLessonId;
        const url       = isStudent ? `${URL_STU_DELETE}/${id}` : `${URL_DELETE}/${id}`;
        if (!id) return;
        try {
            const res  = await fetch(url, { method: 'POST' });
            const text = await res.text();
            let json;
            try { json = JSON.parse(text); } catch (_) { json = { success: false }; }
            if (json.success) {
                closeDeleteModal();
                location.reload();
            }
        } catch (e) { console.error('Delete failed', e); }
        window._deleteTarget = null;
    }
    </script>

</body>
</html>
