<?php
// admin/add-lesson.php - Lesson Management with Edit & Remove
session_start();
require_once '../includes/config.php';

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

$course_id = isset($_GET['course_id']) ? (int)$_GET['course_id'] : 0;
$action = $_GET['action'] ?? 'list';
$lesson_id = isset($_GET['id']) ? (int)$_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 && $course_id > 0 && $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 = trim($_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;
    
    // Handle file attachment
    $attachment_file = '';
    $attachment_name = '';
    if(isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0) {
        $ext = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
        $allowed = ['pdf','doc','docx','ppt','pptx','xls','xlsx','zip','rar','txt','jpg','png','mp4'];
        if(in_array($ext, $allowed)) {
            $dir = '../uploads/materials/';
            if(!is_dir($dir)) mkdir($dir, 0777, true);
            $attachment_file = time().'_'.uniqid().'.'.$ext;
            $attachment_name = $_FILES['attachment']['name'];
            move_uploaded_file($_FILES['attachment']['tmp_name'], $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) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
        $stmt->execute([$course_id, $module_id, $title_bn, $title_en, $youtube_url, $description, $order_number, $is_free, $video_duration, $attachment_file, $attachment_name]);
        header('Location: add-lesson.php?course_id='.$course_id.'&msg=লেসন+যোগ+হয়েছে&type=success');
        exit;
    }
}

// ==================== EDIT LESSON ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_lesson'])) {
    $lesson_id = (int)$_POST['lesson_id'];
    $title_bn = trim($_POST['title_bn'] ?? '');
    $title_en = trim($_POST['title_en'] ?? '');
    $youtube_url = trim($_POST['youtube_url'] ?? '');
    $description = trim($_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;
    
    // Get existing attachment
    $stmt = $pdo->prepare("SELECT attachment_file, attachment_name FROM lessons WHERE id = ?");
    $stmt->execute([$lesson_id]);
    $existing = $stmt->fetch();
    $attachment_file = $existing['attachment_file'] ?? '';
    $attachment_name = $existing['attachment_name'] ?? '';
    
    // Handle new file upload
    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);
        }
        $ext = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
        $allowed = ['pdf','doc','docx','ppt','pptx','xls','xlsx','zip','rar','txt','jpg','png','mp4'];
        if(in_array($ext, $allowed)) {
            $dir = '../uploads/materials/';
            if(!is_dir($dir)) mkdir($dir, 0777, true);
            $attachment_file = time().'_'.uniqid().'.'.$ext;
            $attachment_name = $_FILES['attachment']['name'];
            move_uploaded_file($_FILES['attachment']['tmp_name'], $dir.$attachment_file);
        }
    }
    
    // Remove attachment if requested
    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=? 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_id, $course_id]);
        header('Location: add-lesson.php?course_id='.$course_id.'&msg=লেসন+আপডেট+হয়েছে&type=success');
        exit;
    }
}

// ==================== REMOVE LESSON ====================
if($action == 'remove' && $lesson_id > 0) {
    // Get lesson info
    $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 related quizzes and progress
        $pdo->prepare("DELETE FROM quizzes WHERE lesson_id = ?")->execute([$lesson_id]);
        $pdo->prepare("DELETE FROM lesson_progress WHERE lesson_id = ?")->execute([$lesson_id]);
        
        // Delete the lesson
        $pdo->prepare("DELETE FROM lessons WHERE id = ?")->execute([$lesson_id]);
        
        header('Location: add-lesson.php?course_id='.$course_id.'&msg=লেসন+রিমুভ+হয়েছে&type=success');
        exit;
    }
}

// ==================== ADD QUIZ ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_quiz'])) {
    $quiz_lesson_id = (int)($_POST['lesson_id'] ?? 0);
    $question_bn = trim($_POST['question_bn'] ?? '');
    $option_a = trim($_POST['option_a'] ?? '');
    $option_b = trim($_POST['option_b'] ?? '');
    $option_c = trim($_POST['option_c'] ?? '');
    $option_d = trim($_POST['option_d'] ?? '');
    $correct = $_POST['correct_answer'] ?? 'a';
    
    if(empty($question_bn) || empty($option_a) || empty($option_b) || $quiz_lesson_id == 0) {
        $message = 'প্রশ্ন, অপশন এবং লেসন প্রয়োজন';
        $msg_type = 'danger';
    } else {
        $stmt = $pdo->prepare("INSERT INTO quizzes (lesson_id, question_bn, question_en, option_a, option_b, option_c, option_d, correct_answer) VALUES (?,?,?,?,?,?,?,?)");
        $stmt->execute([$quiz_lesson_id, $question_bn, $question_bn, $option_a, $option_b, $option_c, $option_d, $correct]);
        header('Location: add-lesson.php?course_id='.$course_id.'&msg=কুইজ+যোগ+হয়েছে&type=success');
        exit;
    }
}

// ==================== REMOVE QUIZ ====================
if(isset($_GET['remove_quiz'])) {
    $pdo->prepare("DELETE FROM quizzes WHERE id = ?")->execute([(int)$_GET['remove_quiz']]);
    header('Location: add-lesson.php?course_id='.$course_id.'&msg=কুইজ+রিমুভ+হয়েছে&type=success');
    exit;
}

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

// Get all lessons
$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.order_number");
$stmt->execute([$course_id]);
$lessons = $stmt->fetchAll();

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

// Get quizzes per lesson
$lesson_quizzes = [];
foreach($lessons as $l) {
    $stmt = $pdo->prepare("SELECT * FROM quizzes WHERE lesson_id = ?");
    $stmt->execute([$l['id']]);
    $lesson_quizzes[$l['id']] = $stmt->fetchAll();
}

// Edit lesson data
$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();

?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <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)}
        body{background:#f0f2f8;font-family:'Segoe UI',Arial,sans-serif}
        .navbar{background:white;padding:12px 0;box-shadow:0 2px 10px rgba(0,0,0,0.06);position:sticky;top:0;z-index:100}
        .container{max-width:1200px;margin:0 auto;padding:20px}
        .main-card{background:white;border-radius:16px;padding:25px;box-shadow:0 2px 10px rgba(0,0,0,0.04);margin-bottom:20px}
        .lesson-row{display:flex;align-items:center;padding:14px;border:1px solid #eee;border-radius:12px;margin-bottom:8px;transition:0.3s;background:white;gap:12px}
        .lesson-row:hover{box-shadow:0 3px 15px rgba(0,0,0,0.08);border-color:var(--primary)}
        .lesson-num{width:35px;height:35px;border-radius:50%;background:#e8eaef;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:0.85rem;flex-shrink:0}
        .lesson-num.free{background:#d4f5e9;color:#11998e}
        .youtube-thumb{width:100px;height:56px;object-fit:cover;border-radius:8px;flex-shrink:0}
        .badge-sm{padding:3px 8px;border-radius:20px;font-size:0.7rem;font-weight:600}
        .form-control,.form-select,textarea{border-radius:10px;padding:10px;border:2px solid #e0e0e0;width:100%;margin-bottom:8px;font-size:0.9rem}
        .form-control:focus,.form-select:focus,textarea:focus{border-color:var(--primary);outline:none}
        .btn{border-radius:50px;padding:8px 20px;font-weight:600;cursor:pointer;border:none;transition:0.3s;text-decoration:none;display:inline-flex;align-items:center;gap:5px;font-size:0.85rem}
        .btn-primary{background:var(--gradient);color:white}.btn-primary:hover{transform:translateY(-2px)}
        .btn-danger{background:#ff4757;color:white}.btn-warning{background:#ffc107;color:#333}.btn-info{background:#17a2b8;color:white}.btn-success{background:#28a745;color:white}
        .btn-outline{border:2px solid var(--primary);color:var(--primary);background:white}
        .btn-sm{padding:5px 12px;font-size:0.78rem}
        .alert{border-radius:10px;padding:12px 16px;margin-bottom:15px}
        .modal-header{background:var(--gradient);color:white;border-radius:14px 14px 0 0}
        .modal-content{border-radius:14px;border:none}
        .quiz-item{background:#f8f9ff;border-radius:10px;padding:15px;margin-bottom:8px;border-left:3px solid var(--primary)}
        @media(max-width:768px){.lesson-row{flex-wrap:wrap}}
    </style>
</head>
<body>

<nav class="navbar">
    <div class="container" style="display:flex;justify-content:space-between;align-items:center">
        <a href="dashboard.php" style="font-weight:700;color:var(--primary);text-decoration:none;font-size:1.1rem"><i class="fas fa-graduation-cap me-2"></i>অ্যাডমিন</a>
        <div class="d-flex gap-2">
            <a href="courses.php" class="btn btn-outline btn-sm">সব কোর্স</a>
            <a href="../logout.php" class="btn btn-sm" style="background:#ff4757;color:white">লগআউট</a>
        </div>
    </div>
</nav>

<div class="container">
    
    <?php if($msg): ?><div class="alert alert-<?=$msg_type?>"><?=htmlspecialchars($msg)?></div><?php endif; ?>
    
    <?php if(!$course_id): ?>
        <!-- Course Selection -->
        <div class="main-card">
            <h5 class="mb-3">📚 কোর্স সিলেক্ট করুন</h5>
            <?php foreach($all_courses as $c): ?>
                <a href="?course_id=<?=$c['id']?>" class="d-block p-3 rounded-3 mb-2 text-decoration-none" style="border:1px solid #eee;color:#333;transition:0.3s" onmouseover="this.style.background='#f8f9ff'" onmouseout="this.style.background='white'">
                    <?=htmlspecialchars($c['title_bn'])?>
                </a>
            <?php endforeach; ?>
        </div>
    <?php elseif($action == 'add' || $action == 'edit'): ?>
        <!-- Add/Edit Form -->
        <div class="main-card">
            <h4 class="mb-4"><?=$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']?>"><?php endif; ?>
                
                <div class="row">
                    <div class="col-md-8">
                        <label class="fw-bold small">লেসনের নাম (বাংলা) *</label>
                        <input type="text" name="title_bn" class="form-control" value="<?=htmlspecialchars($edit_lesson['title_bn']??'')?>" required>
                        <label class="fw-bold small">Lesson Name (English)</label>
                        <input type="text" name="title_en" class="form-control" value="<?=htmlspecialchars($edit_lesson['title_en']??'')?>">
                        <label class="fw-bold 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=...">
                        <label class="fw-bold small">বিবরণ</label>
                        <textarea name="description" class="form-control" rows="3"><?=htmlspecialchars($edit_lesson['description']??'')?></textarea>
                    </div>
                    <div class="col-md-4">
                        <label class="fw-bold 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>
                        <label class="fw-bold small">ক্রমিক নং</label>
                        <input type="number" name="order_number" class="form-control" value="<?=$edit_lesson['order_number']??count($lessons)+1?>">
                        <label class="fw-bold small">ভিডিও সময়কাল</label>
                        <input type="text" name="video_duration" class="form-control" value="<?=htmlspecialchars($edit_lesson['video_duration']??'')?>" placeholder="যেমন: 15:30">
                        <div class="form-check mt-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>
                        
                        <label class="fw-bold small mt-2">ফাইল সংযুক্তি</label>
                        <?php if($action=='edit' && !empty($edit_lesson['attachment_file'])): ?>
                            <div class="p-2 bg-light rounded mb-2 small">
                                বর্তমান: <?=htmlspecialchars($edit_lesson['attachment_name'])?>
                                <br><label style="cursor:pointer;color:red"><input type="checkbox" name="remove_attachment" value="1"> ফাইল রিমুভ করুন</label>
                            </div>
                        <?php endif; ?>
                        <input type="file" name="attachment" class="form-control">
                    </div>
                </div>
                
                <div class="d-flex gap-2 mt-3">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> <?=$action=='edit'?'আপডেট':'সংরক্ষণ'?></button>
                    <a href="?course_id=<?=$course_id?>" class="btn btn-outline">বাতিল</a>
                </div>
            </form>
        </div>
    <?php else: ?>
        <!-- Lesson List -->
        <div class="row">
            <div class="col-lg-8">
                <div class="main-card">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5>📹 লেসন তালিকা (<?=count($lessons)?> টি)</h5>
                        <a href="?course_id=<?=$course_id?>&action=add" class="btn btn-primary btn-sm"><i class="fas fa-plus"></i> নতুন লেসন</a>
                    </div>
                    
                    <?php if(count($lessons) > 0): ?>
                        <?php foreach($lessons as $l): $yid = getYouTubeId($l['youtube_url']); ?>
                            <div class="lesson-row">
                                <div class="lesson-num <?=$l['is_free']?'free':''?>"><?=$l['order_number']?></div>
                                <?php if($yid): ?><img src="https://img.youtube.com/vi/<?=$yid?>/default.jpg" class="youtube-thumb"><?php endif; ?>
                                <div class="flex-grow-1">
                                    <strong><?=htmlspecialchars($l['title_bn'])?></strong>
                                    <?php if($l['module_name']): ?><br><small class="text-primary">📦 <?=htmlspecialchars($l['module_name'])?></small><?php endif; ?>
                                    <div class="mt-1">
                                        <?php if($l['is_free']): ?><span class="badge-sm bg-success text-white">ফ্রি</span><?php endif; ?>
                                        <?php if($l['video_duration']): ?><span class="badge-sm bg-info text-white"><?=$l['video_duration']?></span><?php endif; ?>
                                        <?php if($l['attachment_file']): ?><span class="badge-sm bg-warning">📎 ফাইল</span><?php endif; ?>
                                        <?php if(count($lesson_quizzes[$l['id']]??[]) > 0): ?><span class="badge-sm bg-primary text-white"><?=count($lesson_quizzes[$l['id']])?> কুইজ</span><?php endif; ?>
                                    </div>
                                </div>
                                <div class="d-flex gap-1">
                                    <a href="?course_id=<?=$course_id?>&action=edit&id=<?=$l['id']?>" class="btn btn-warning btn-sm" title="এডিট"><i class="fas fa-edit"></i></a>
                                    <button class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#quizModal<?=$l['id']?>" title="কুইজ"><i class="fas fa-question-circle"></i></button>
                                    <a href="?course_id=<?=$course_id?>&action=remove&id=<?=$l['id']?>" class="btn btn-danger btn-sm" onclick="return confirm('লেসন রিমুভ করবেন? কুইজ ও প্রগ্রেসও ডিলিট হবে!')" title="রিমুভ"><i class="fas fa-trash"></i></a>
                                </div>
                            </div>
                            
                            <!-- Quiz Modal -->
                            <div class="modal fade" id="quizModal<?=$l['id']?>" tabindex="-1">
                                <div class="modal-dialog"><div class="modal-content">
                                    <div class="modal-header"><h6>❓ কুইজ - <?=htmlspecialchars(mb_substr($l['title_bn'],0,20))?></h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
                                    <div class="modal-body">
                                        <!-- Existing quizzes -->
                                        <?php $quizzes = $lesson_quizzes[$l['id']] ?? []; ?>
                                        <?php if(count($quizzes) > 0): ?>
                                            <?php foreach($quizzes as $q): ?>
                                                <div class="quiz-item">
                                                    <strong><?=htmlspecialchars($q['question_bn'])?></strong>
                                                    <div class="small mt-1">ক) <?=htmlspecialchars($q['option_a'])?> | খ) <?=htmlspecialchars($q['option_b'])?></div>
                                                    <div class="d-flex justify-content-between align-items-center mt-1">
                                                        <small class="text-success">উত্তর: <?=strtoupper($q['correct_answer'])?></small>
                                                        <a href="?course_id=<?=$course_id?>&remove_quiz=<?=$q['id']?>" class="btn btn-danger btn-sm" onclick="return confirm('কুইজ রিমুভ করবেন?')"><i class="fas fa-trash"></i></a>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        <?php else: ?><p class="text-muted small">কোন কুইজ নেই</p><?php endif; ?>
                                        
                                        <hr><h6 class="mb-2">➕ নতুন কুইজ যোগ করুন</h6>
                                        <form method="POST">
                                            <input type="hidden" name="add_quiz" value="1">
                                            <input type="hidden" name="lesson_id" value="<?=$l['id']?>">
                                            <input type="text" name="question_bn" class="form-control" placeholder="প্রশ্ন" required>
                                            <div class="row"><div class="col-6"><input type="text" name="option_a" class="form-control" placeholder="অপশন ক" required></div><div class="col-6"><input type="text" name="option_b" class="form-control" placeholder="অপশন খ" required></div></div>
                                            <div class="row"><div class="col-6"><input type="text" name="option_c" class="form-control" placeholder="অপশন গ"></div><div class="col-6"><input type="text" name="option_d" class="form-control" placeholder="অপশন ঘ"></div></div>
                                            <select name="correct_answer" class="form-select"><option value="a">ক</option><option value="b">খ</option><option value="c">গ</option><option value="d">ঘ</option></select>
                                            <button type="submit" class="btn btn-primary btn-sm w-100 mt-2">যোগ করুন</button>
                                        </form>
                                    </div>
                                </div></div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <p class="text-center text-muted py-4">কোন লেসন নেই</p>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Sidebar -->
            <div class="col-lg-4">
                <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':''?>" style="font-size:0.9rem">
                            <?=htmlspecialchars(mb_substr($c['title_bn'],0,30))?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>