<?php
// admin/manage-lessons.php - Complete Lesson Management System
session_start();
require_once '../includes/config.php';

if(!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'admin') {
    header('Location: ../auth.php');
    exit;
}

$course_id = $_GET['course_id'] ?? 0;
$action = $_GET['action'] ?? 'list'; // list, add, edit, delete
$lesson_id = $_GET['id'] ?? 0;
$message = '';
$msg_type = 'info';

// Get course info
$stmt = $pdo->prepare("SELECT * FROM courses WHERE id = ?");
$stmt->execute([$course_id]);
$course = $stmt->fetch();

if(!$course && $action != 'list') {
    header('Location: courses.php');
    exit;
}

// ==================== ADD LESSON ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_lesson'])) {
    $title_bn = trim($_POST['title_bn'] ?? '');
    $title_en = trim($_POST['title_en'] ?? '');
    $youtube_url = trim($_POST['youtube_url'] ?? '');
    $description = $_POST['description'] ?? '';
    $order_number = (int)($_POST['order_number'] ?? 1);
    $is_free = isset($_POST['is_free']) ? 1 : 0;
    $video_duration = trim($_POST['video_duration'] ?? '');
    $module_id = $_POST['module_id'] ?? null;
    $lesson_type = $_POST['lesson_type'] ?? 'video';
    $content_text = $_POST['content_text'] ?? '';
    $require_quiz = isset($_POST['require_quiz']) ? 1 : 0;
    
    // Handle attachment
    $attachment_file = '';
    $attachment_name = '';
    if(isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0) {
        $file = $_FILES['attachment'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowed = ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'zip', 'rar', 'txt', 'jpg', 'png', 'mp4', 'mp3'];
        
        if(in_array($ext, $allowed)) {
            $upload_dir = '../uploads/materials/';
            if(!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            
            $attachment_file = time() . '_' . uniqid() . '.' . $ext;
            $attachment_name = $file['name'];
            move_uploaded_file($file['tmp_name'], $upload_dir . $attachment_file);
        }
    }
    
    if(empty($title_bn)) {
        $message = 'লেসনের নাম প্রয়োজন';
        $msg_type = 'danger';
    } else {
        $stmt = $pdo->prepare("
            INSERT INTO lessons (course_id, module_id, title_bn, title_en, youtube_url, description, order_number, is_free, video_duration, attachment_file, attachment_name, lesson_type, content_text, require_quiz) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$course_id, $module_id, $title_bn, $title_en, $youtube_url, $description, $order_number, $is_free, $video_duration, $attachment_file, $attachment_name, $lesson_type, $content_text, $require_quiz]);
        
        header("Location: manage-lessons.php?course_id=$course_id&msg=লেসন+যোগ+হয়েছে&type=success");
        exit;
    }
}

// ==================== EDIT LESSON ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_lesson'])) {
    $lesson_id = $_POST['lesson_id'];
    $title_bn = trim($_POST['title_bn'] ?? '');
    $title_en = trim($_POST['title_en'] ?? '');
    $youtube_url = trim($_POST['youtube_url'] ?? '');
    $description = $_POST['description'] ?? '';
    $order_number = (int)($_POST['order_number'] ?? 1);
    $is_free = isset($_POST['is_free']) ? 1 : 0;
    $video_duration = trim($_POST['video_duration'] ?? '');
    $module_id = $_POST['module_id'] ?? null;
    $lesson_type = $_POST['lesson_type'] ?? 'video';
    $content_text = $_POST['content_text'] ?? '';
    $require_quiz = isset($_POST['require_quiz']) ? 1 : 0;
    
    // Handle attachment
    $attachment_file = $_POST['existing_attachment'] ?? '';
    $attachment_name = $_POST['existing_attachment_name'] ?? '';
    
    if(isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0) {
        // Delete old file
        if(!empty($attachment_file) && file_exists('../uploads/materials/' . $attachment_file)) {
            unlink('../uploads/materials/' . $attachment_file);
        }
        
        $file = $_FILES['attachment'];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowed = ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'zip', 'rar', 'txt', 'jpg', 'png', 'mp4', 'mp3'];
        
        if(in_array($ext, $allowed)) {
            $upload_dir = '../uploads/materials/';
            if(!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            
            $attachment_file = time() . '_' . uniqid() . '.' . $ext;
            $attachment_name = $file['name'];
            move_uploaded_file($file['tmp_name'], $upload_dir . $attachment_file);
        }
    }
    
    // Handle remove attachment
    if(isset($_POST['remove_attachment']) && $_POST['remove_attachment'] == 1) {
        if(!empty($attachment_file) && file_exists('../uploads/materials/' . $attachment_file)) {
            unlink('../uploads/materials/' . $attachment_file);
        }
        $attachment_file = '';
        $attachment_name = '';
    }
    
    if(empty($title_bn)) {
        $message = 'লেসনের নাম প্রয়োজন';
        $msg_type = 'danger';
    } else {
        $stmt = $pdo->prepare("
            UPDATE lessons SET 
                module_id = ?, title_bn = ?, title_en = ?, youtube_url = ?, 
                description = ?, order_number = ?, is_free = ?, video_duration = ?,
                attachment_file = ?, attachment_name = ?, lesson_type = ?, 
                content_text = ?, require_quiz = ?
            WHERE id = ? AND course_id = ?
        ");
        $stmt->execute([$module_id, $title_bn, $title_en, $youtube_url, $description, $order_number, $is_free, $video_duration, $attachment_file, $attachment_name, $lesson_type, $content_text, $require_quiz, $lesson_id, $course_id]);
        
        header("Location: manage-lessons.php?course_id=$course_id&msg=লেসন+আপডেট+হয়েছে&type=success");
        exit;
    }
}

// ==================== DELETE LESSON ====================
if($action == 'delete' && $lesson_id > 0) {
    // Get lesson to delete attachment
    $stmt = $pdo->prepare("SELECT attachment_file FROM lessons WHERE id = ? AND course_id = ?");
    $stmt->execute([$lesson_id, $course_id]);
    $lesson = $stmt->fetch();
    
    if($lesson) {
        // Delete attachment file
        if(!empty($lesson['attachment_file']) && file_exists('../uploads/materials/' . $lesson['attachment_file'])) {
            unlink('../uploads/materials/' . $lesson['attachment_file']);
        }
        
        // Delete quizzes
        $pdo->prepare("DELETE FROM quizzes WHERE lesson_id = ?")->execute([$lesson_id]);
        
        // Delete lesson
        $pdo->prepare("DELETE FROM lessons WHERE id = ?")->execute([$lesson_id]);
        
        header("Location: manage-lessons.php?course_id=$course_id&msg=লেসন+ডিলিট+হয়েছে&type=success");
        exit;
    }
}

// ==================== BULK ACTIONS ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['bulk_action']) && isset($_POST['selected_lessons'])) {
    $selected = $_POST['selected_lessons'];
    $bulk_action = $_POST['bulk_action'];
    
    if($bulk_action == 'delete') {
        foreach($selected as $lid) {
            $stmt = $pdo->prepare("SELECT attachment_file FROM lessons WHERE id = ?");
            $stmt->execute([$lid]);
            $l = $stmt->fetch();
            if($l && !empty($l['attachment_file']) && file_exists('../uploads/materials/' . $l['attachment_file'])) {
                unlink('../uploads/materials/' . $l['attachment_file']);
            }
            $pdo->prepare("DELETE FROM quizzes WHERE lesson_id = ?")->execute([$lid]);
            $pdo->prepare("DELETE FROM lessons WHERE id = ?")->execute([$lid]);
        }
        $message = count($selected) . ' টি লেসন ডিলিট হয়েছে';
    } elseif($bulk_action == 'free') {
        $pdo->prepare("UPDATE lessons SET is_free = 1 WHERE id IN (" . implode(',', array_fill(0, count($selected), '?')) . ")")->execute($selected);
        $message = count($selected) . ' টি লেসন ফ্রি করা হয়েছে';
    } elseif($bulk_action == 'paid') {
        $pdo->prepare("UPDATE lessons SET is_free = 0 WHERE id IN (" . implode(',', array_fill(0, count($selected), '?')) . ")")->execute($selected);
        $message = count($selected) . ' টি লেসন পেইড করা হয়েছে';
    }
    
    header("Location: manage-lessons.php?course_id=$course_id&msg=" . urlencode($message) . "&type=success");
    exit;
}

// ==================== REORDER LESSONS ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['reorder'])) {
    $orders = $_POST['order'] ?? [];
    foreach($orders as $lesson_id => $order_num) {
        $pdo->prepare("UPDATE lessons SET order_number = ? WHERE id = ? AND course_id = ?")
            ->execute([(int)$order_num, (int)$lesson_id, $course_id]);
    }
    header("Location: manage-lessons.php?course_id=$course_id&msg=ক্রম+আপডেট+হয়েছে&type=success");
    exit;
}

// Get message
$msg = $_GET['msg'] ?? '';
$msg_type = $_GET['type'] ?? 'info';

// Get modules for this course
$modules = $pdo->prepare("SELECT * FROM modules WHERE course_id = ? ORDER BY order_number");
$modules->execute([$course_id]);
$course_modules = $modules->fetchAll();

// Get all lessons with module info
$stmt = $pdo->prepare("
    SELECT l.*, m.title_bn as module_name 
    FROM lessons l 
    LEFT JOIN modules m ON l.module_id = m.id 
    WHERE l.course_id = ? 
    ORDER BY l.module_id, l.order_number
");
$stmt->execute([$course_id]);
$lessons = $stmt->fetchAll();

// Get lesson if editing
$edit_lesson = null;
if($action == 'edit' && $lesson_id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM lessons WHERE id = ? AND course_id = ?");
    $stmt->execute([$lesson_id, $course_id]);
    $edit_lesson = $stmt->fetch();
}

// Get all courses for sidebar
$all_courses = $pdo->query("SELECT id, title_bn FROM courses ORDER BY title_bn")->fetchAll();

// Get quiz count per lesson
$quiz_counts = [];
foreach($lessons as $l) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM quizzes WHERE lesson_id = ?");
    $stmt->execute([$l['id']]);
    $quiz_counts[$l['id']] = $stmt->fetchColumn();
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>লেসন ম্যানেজমেন্ট - <?= htmlspecialchars($course['title_bn'] ?? '') ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #6C5CE7; --gradient: linear-gradient(135deg, #667eea, #764ba2); --shadow: 0 3px 15px rgba(0,0,0,0.08); }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: #f0f2f8; font-family: 'Segoe UI','Hind Siliguri',Arial,sans-serif; }
        
        .navbar { background: white; box-shadow: 0 2px 10px rgba(0,0,0,0.06); padding: 12px 0; position: sticky; top: 0; z-index: 100; }
        .navbar-brand { font-weight: 700; color: var(--primary) !important; text-decoration: none; }
        
        .main-card { background: white; border-radius: 15px; padding: 25px; box-shadow: var(--shadow); margin-bottom: 20px; }
        
        .lesson-row { 
            display: flex; align-items: center; padding: 12px; 
            border: 1px solid #eee; border-radius: 10px; margin-bottom: 8px;
            transition: 0.2s; background: white;
        }
        .lesson-row:hover { border-color: var(--primary); box-shadow: var(--shadow); }
        .lesson-row.dragging { opacity: 0.5; background: #f0f0ff; }
        .drag-handle { cursor: grab; color: #ccc; margin-right: 10px; font-size: 1.2rem; }
        .drag-handle:hover { color: var(--primary); }
        
        .lesson-num { width: 32px; height: 32px; border-radius: 50%; background: #f0f0f0; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 0.85rem; margin-right: 12px; flex-shrink: 0; }
        .lesson-num.free { background: #d4f5e9; color: #11998e; }
        
        .youtube-thumb { width: 80px; height: 45px; object-fit: cover; border-radius: 6px; margin-right: 12px; }
        
        .badge-custom { padding: 3px 8px; border-radius: 15px; font-size: 0.7rem; font-weight: 600; }
        
        .form-control, .form-select, textarea { border-radius: 10px; padding: 10px 15px; border: 2px solid #e0e0e0; }
        .form-control:focus, .form-select:focus { border-color: var(--primary); outline: none; box-shadow: 0 0 0 3px rgba(108,92,231,0.08); }
        
        .btn { border-radius: 50px; padding: 8px 20px; font-weight: 600; transition: 0.3s; }
        .btn-primary { background: var(--gradient); border: none; color: white; }
        .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(108,92,231,0.3); }
        
        .modal-header { background: var(--gradient); color: white; border-radius: 15px 15px 0 0; }
        .modal-content { border-radius: 15px; border: none; }
        
        .section-card { background: #f8f9ff; border-radius: 12px; padding: 15px; margin-bottom: 15px; border: 1px solid #e8e8ff; }
        
        @media (max-width: 768px) {
            .lesson-row { flex-wrap: wrap; }
            .youtube-thumb { width: 60px; height: 34px; }
        }
    </style>
</head>
<body>

<nav class="navbar">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <a href="dashboard.php" class="navbar-brand"><i class="fas fa-graduation-cap me-2"></i>অ্যাডমিন</a>
                <?php if($course): ?>
                    <span class="text-muted ms-2">| <?= htmlspecialchars($course['title_bn']) ?></span>
                <?php endif; ?>
            </div>
            <div class="d-flex gap-2">
                <a href="courses.php" class="btn btn-outline-secondary btn-sm rounded-pill">কোর্স</a>
                <a href="../logout.php" class="btn btn-sm rounded-pill" style="background:#ff4757;color:white;">লগআউট</a>
            </div>
        </div>
    </div>
</nav>

<div class="container py-4">
    
    <!-- Message -->
    <?php if($msg): ?>
        <div class="alert alert-<?= $msg_type ?> rounded-3"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>
    
    <div class="row">
        <!-- Sidebar - Course List -->
        <div class="col-lg-3 mb-3">
            <div class="main-card">
                <h6 class="mb-3">📚 কোর্স সিলেক্ট করুন</h6>
                <?php foreach($all_courses as $c): ?>
                    <a href="?course_id=<?= $c['id'] ?>" 
                       class="d-block p-2 rounded-2 mb-1 text-decoration-none <?= $course_id == $c['id'] ? 'bg-primary text-white' : 'text-dark' ?>"
                       style="transition:0.2s;">
                        <?= htmlspecialchars(mb_substr($c['title_bn'], 0, 25)) ?>
                    </a>
                <?php endforeach; ?>
            </div>
            
            <?php if($course): ?>
                <div class="main-card mt-3">
                    <h6 class="mb-3">⚡ কুইক লিংক</h6>
                    <a href="?course_id=<?= $course_id ?>&action=add" class="btn btn-primary btn-sm w-100 mb-2">
                        <i class="fas fa-plus me-1"></i> নতুন লেসন
                    </a>
                    <a href="add-lesson.php?course_id=<?= $course_id ?>&tab=quizzes" class="btn btn-outline-primary btn-sm w-100 mb-2">
                        <i class="fas fa-question-circle me-1"></i> কুইজ ম্যানেজ
                    </a>
                    <a href="add-lesson.php?course_id=<?= $course_id ?>&tab=files" class="btn btn-outline-primary btn-sm w-100">
                        <i class="fas fa-file me-1"></i> ফাইল ম্যানেজ
                    </a>
                </div>
            <?php endif; ?>
        </div>
        
        <!-- Main Content -->
        <div class="col-lg-9">
            
            <?php if(!$course): ?>
                <div class="main-card text-center py-5">
                    <i class="fas fa-arrow-left fa-3x text-muted mb-3"></i>
                    <h5>একটি কোর্স সিলেক্ট করুন</h5>
                    <p class="text-muted">লেসন ম্যানেজ করতে বাম পাশ থেকে কোর্স সিলেক্ট করুন</p>
                </div>
            
            <?php elseif($action == 'add' || $action == 'edit'): ?>
                <!-- Add/Edit Form -->
                <div class="main-card">
                    <h4 class="mb-4">
                        <i class="fas fa-<?= $action=='edit'?'edit':'plus-circle' ?> text-primary me-2"></i>
                        <?= $action=='edit' ? 'লেসন এডিট করুন' : 'নতুন লেসন যোগ করুন' ?>
                    </h4>
                    
                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="<?= $action=='edit'?'edit_lesson':'add_lesson' ?>" value="1">
                        <?php if($action == 'edit'): ?>
                            <input type="hidden" name="lesson_id" value="<?= $edit_lesson['id'] ?>">
                            <input type="hidden" name="existing_attachment" value="<?= $edit_lesson['attachment_file'] ?>">
                            <input type="hidden" name="existing_attachment_name" value="<?= $edit_lesson['attachment_name'] ?>">
                        <?php endif; ?>
                        
                        <div class="row">
                            <div class="col-md-8">
                                <div class="section-card">
                                    <h6 class="mb-3">📝 মৌলিক তথ্য</h6>
                                    <div class="mb-2">
                                        <label class="form-label small">লেসনের নাম (বাংলা) *</label>
                                        <input type="text" name="title_bn" class="form-control" value="<?= htmlspecialchars($edit_lesson['title_bn'] ?? '') ?>" required>
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label small">Lesson Name (English)</label>
                                        <input type="text" name="title_en" class="form-control" value="<?= htmlspecialchars($edit_lesson['title_en'] ?? '') ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label small">বিবরণ</label>
                                        <textarea name="description" class="form-control" rows="3"><?= htmlspecialchars($edit_lesson['description'] ?? '') ?></textarea>
                                    </div>
                                </div>
                                
                                <div class="section-card">
                                    <h6 class="mb-3">📹 ভিডিও / কন্টেন্ট</h6>
                                    <div class="mb-2">
                                        <label class="form-label small">টাইপ</label>
                                        <select name="lesson_type" class="form-select" onchange="toggleContentType(this.value)">
                                            <option value="video" <?= ($edit_lesson['lesson_type']??'video')=='video'?'selected':'' ?>>ভিডিও (YouTube)</option>
                                            <option value="text" <?= ($edit_lesson['lesson_type']??'')=='text'?'selected':'' ?>>টেক্সট কন্টেন্ট</option>
                                            <option value="both" <?= ($edit_lesson['lesson_type']??'')=='both'?'selected':'' ?>>ভিডিও + টেক্সট</option>
                                        </select>
                                    </div>
                                    <div class="mb-2" id="youtubeField">
                                        <label class="form-label small">YouTube URL</label>
                                        <input type="url" name="youtube_url" class="form-control" value="<?= htmlspecialchars($edit_lesson['youtube_url'] ?? '') ?>" placeholder="https://youtube.com/watch?v=...">
                                    </div>
                                    <div class="mb-2" id="contentTextField" style="display:<?= ($edit_lesson['lesson_type']??'')=='text'||($edit_lesson['lesson_type']??'')=='both'?'block':'none' ?>;">
                                        <label class="form-label small">টেক্সট কন্টেন্ট</label>
                                        <textarea name="content_text" class="form-control" rows="6" placeholder="HTML কন্টেন্ট লিখুন..."><?= htmlspecialchars($edit_lesson['content_text'] ?? '') ?></textarea>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="section-card">
                                    <h6 class="mb-3">⚙️ সেটিংস</h6>
                                    <div class="mb-2">
                                        <label class="form-label small">মডিউল</label>
                                        <select name="module_id" class="form-select">
                                            <option value="">কোন মডিউল নেই</option>
                                            <?php foreach($course_modules as $mod): ?>
                                                <option value="<?= $mod['id'] ?>" <?= ($edit_lesson['module_id']??'')==$mod['id']?'selected':'' ?>><?= htmlspecialchars($mod['title_bn']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label small">ক্রমিক নং</label>
                                        <input type="number" name="order_number" class="form-control" value="<?= $edit_lesson['order_number'] ?? count($lessons)+1 ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label small">ভিডিও সময়কাল</label>
                                        <input type="text" name="video_duration" class="form-control" value="<?= htmlspecialchars($edit_lesson['video_duration'] ?? '') ?>" placeholder="যেমন: 15:30">
                                    </div>
                                    <div class="form-check mb-2">
                                        <input type="checkbox" name="is_free" class="form-check-input" id="isFree" <?= ($edit_lesson['is_free']??0)==1?'checked':'' ?>>
                                        <label class="form-check-label small" for="isFree">ফ্রি প্রিভিউ</label>
                                    </div>
                                    <div class="form-check mb-2">
                                        <input type="checkbox" name="require_quiz" class="form-check-input" id="requireQuiz" <?= ($edit_lesson['require_quiz']??0)==1?'checked':'' ?>>
                                        <label class="form-check-label small" for="requireQuiz">কুইজ বাধ্যতামূলক</label>
                                    </div>
                                </div>
                                
                                <div class="section-card">
                                    <h6 class="mb-3">📎 ফাইল সংযুক্তি</h6>
                                    <?php if($action=='edit' && !empty($edit_lesson['attachment_file'])): ?>
                                        <div class="mb-2 p-2 bg-light rounded">
                                            <small>বর্তমান ফাইল: <strong><?= $edit_lesson['attachment_name'] ?></strong></small>
                                            <br>
                                            <label class="small text-danger" style="cursor:pointer;">
                                                <input type="checkbox" name="remove_attachment" value="1"> ফাইল রিমুভ করুন
                                            </label>
                                        </div>
                                    <?php endif; ?>
                                    <input type="file" name="attachment" class="form-control form-control-sm">
                                    <small class="text-muted">PDF, DOC, PPT, ZIP (Max 50MB)</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="d-flex gap-2 mt-3">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-<?= $action=='edit'?'save':'plus' ?> me-1"></i>
                                <?= $action=='edit'?'আপডেট করুন':'লেসন যোগ করুন' ?>
                            </button>
                            <a href="?course_id=<?= $course_id ?>" class="btn btn-outline-secondary">বাতিল</a>
                        </div>
                    </form>
                </div>
            
            <?php else: ?>
                <!-- Lesson List -->
                <div class="main-card">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h4><i class="fas fa-list text-primary me-2"></i>লেসন তালিকা (<?= count($lessons) ?> টি)</h4>
                        <div class="d-flex gap-2">
                            <a href="?course_id=<?= $course_id ?>&action=add" class="btn btn-primary btn-sm">
                                <i class="fas fa-plus me-1"></i> নতুন লেসন
                            </a>
                        </div>
                    </div>
                    
                    <!-- Bulk Actions -->
                    <form method="POST" id="lessonForm">
                        <div class="d-flex gap-2 mb-3 align-items-center">
                            <select name="bulk_action" class="form-select form-select-sm" style="width:200px;">
                                <option value="">বাল্ক অ্যাকশন</option>
                                <option value="delete">🗑️ ডিলিট</option>
                                <option value="free">✅ ফ্রি করুন</option>
                                <option value="paid">🔒 পেইড করুন</option>
                            </select>
                            <button type="submit" class="btn btn-outline-danger btn-sm">প্রয়োগ করুন</button>
                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="saveOrder()">
                                <i class="fas fa-save me-1"></i> ক্রম সংরক্ষণ
                            </button>
                            <small class="text-muted" id="selectedCount">0 টি সিলেক্টেড</small>
                        </div>
                        
                        <!-- Reorder form -->
                        <input type="hidden" name="reorder" id="reorderInput" value="0">
                        
                        <?php if(count($lessons) > 0): ?>
                            <div id="sortableList">
                                <?php foreach($lessons as $index => $lesson): 
                                    $yid = getYouTubeId($lesson['youtube_url']);
                                ?>
                                    <div class="lesson-row" data-id="<?= $lesson['id'] ?>">
                                        <span class="drag-handle">⋮⋮</span>
                                        <input type="checkbox" name="selected_lessons[]" value="<?= $lesson['id'] ?>" class="form-check-input me-2" onchange="updateCount()">
                                        
                                        <div class="lesson-num <?= $lesson['is_free']?'free':'' ?>"><?= $lesson['order_number'] ?></div>
                                        
                                        <?php if($yid): ?>
                                            <img src="https://img.youtube.com/vi/<?= $yid ?>/default.jpg" class="youtube-thumb">
                                        <?php else: ?>
                                            <div class="youtube-thumb bg-secondary d-flex align-items-center justify-content-center text-white small">
                                                <?= $lesson['lesson_type']=='text'?'📝':'📹' ?>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <div class="flex-grow-1 ms-2">
                                            <strong><?= htmlspecialchars($lesson['title_bn']) ?></strong>
                                            <?php if($lesson['module_name']): ?>
                                                <br><small class="text-primary">📦 <?= $lesson['module_name'] ?></small>
                                            <?php endif; ?>
                                            <div class="mt-1">
                                                <?php if($lesson['is_free']): ?><span class="badge-custom bg-success text-white">ফ্রি</span><?php endif; ?>
                                                <?php if($lesson['lesson_type']=='text'): ?><span class="badge-custom bg-info text-white">টেক্সট</span><?php endif; ?>
                                                <?php if($lesson['video_duration']): ?><span class="badge-custom bg-secondary text-white"><?= $lesson['video_duration'] ?></span><?php endif; ?>
                                                <?php if($lesson['attachment_file']): ?><span class="badge-custom bg-warning">📎 ফাইল</span><?php endif; ?>
                                                <?php if($lesson['require_quiz']): ?><span class="badge-custom bg-danger text-white">কুইজ আবশ্যক</span><?php endif; ?>
                                                <?php if(($quiz_counts[$lesson['id']]??0) > 0): ?>
                                                    <span class="badge-custom bg-purple text-white"><?= $quiz_counts[$lesson['id']] ?> কুইজ</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        
                                        <div class="d-flex gap-1 ms-2">
                                            <a href="?course_id=<?= $course_id ?>&action=edit&id=<?= $lesson['id'] ?>" 
                                               class="btn btn-outline-primary btn-sm" title="এডিট">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="add-lesson.php?course_id=<?= $course_id ?>&tab=quizzes" 
                                               class="btn btn-outline-info btn-sm" title="কুইজ">
                                                <i class="fas fa-question-circle"></i>
                                            </a>
                                            <a href="?course_id=<?= $course_id ?>&action=delete&id=<?= $lesson['id'] ?>" 
                                               class="btn btn-outline-danger btn-sm" title="ডিলিট"
                                               onclick="return confirm('লেসন ডিলিট করবেন? কুইজ ও ফাইলও ডিলিট হবে!')">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                            <input type="hidden" name="order[<?= $lesson['id'] ?>]" value="<?= $lesson['order_number'] ?>" class="order-input">
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-5 text-muted">
                                <i class="fas fa-video-slash fa-3x mb-3" style="opacity:0.3;"></i>
                                <p>কোন লেসন নেই</p>
                                <a href="?course_id=<?= $course_id ?>&action=add" class="btn btn-primary">প্রথম লেসন যোগ করুন</a>
                            </div>
                        <?php endif; ?>
                    </form>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function toggleContentType(val) {
    document.getElementById('youtubeField').style.display = (val === 'text') ? 'none' : 'block';
    document.getElementById('contentTextField').style.display = (val === 'video') ? 'none' : 'block';
}

function updateCount() {
    const count = document.querySelectorAll('input[name="selected_lessons[]"]:checked').length;
    document.getElementById('selectedCount').textContent = count + ' টি সিলেক্টেড';
}

// Drag and drop reorder
function saveOrder() {
    document.getElementById('reorderInput').value = '1';
    document.getElementById('lessonForm').submit();
}

// Simple drag reorder
const list = document.getElementById('sortableList');
if(list) {
    let draggedItem = null;
    
    list.addEventListener('dragstart', function(e) {
        draggedItem = e.target.closest('.lesson-row');
        if(draggedItem) draggedItem.classList.add('dragging');
    });
    
    list.addEventListener('dragend', function(e) {
        if(draggedItem) draggedItem.classList.remove('dragging');
        updateOrderNumbers();
    });
    
    list.addEventListener('dragover', function(e) {
        e.preventDefault();
        const afterElement = getDragAfterElement(list, e.clientY);
        const currentItem = list.querySelector('.dragging');
        if(currentItem && afterElement) {
            list.insertBefore(currentItem, afterElement);
        } else if(currentItem) {
            list.appendChild(currentItem);
        }
    });
}

function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.lesson-row:not(.dragging)')];
    return draggableElements.reduce((closest, child) => {
        const box = child.getBoundingClientRect();
        const offset = y - box.top - box.height / 2;
        if(offset < 0 && offset > closest.offset) {
            return { offset: offset, element: child };
        } else {
            return closest;
        }
    }, { offset: Number.NEGATIVE_INFINITY }).element;
}

function updateOrderNumbers() {
    const rows = document.querySelectorAll('.lesson-row');
    rows.forEach((row, index) => {
        row.querySelector('.lesson-num').textContent = index + 1;
        const orderInput = row.querySelector('.order-input');
        if(orderInput) orderInput.value = index + 1;
    });
}

// Make rows draggable
document.querySelectorAll('.lesson-row').forEach(row => {
    row.setAttribute('draggable', 'true');
});
</script>
</body>
</html>