<?php
/**
 * Online Courses Management
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/SecurityHelper.php';

// Check authentication - redirect to login if not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

// Check admin role
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    die('❌ অ্যাক্সেস denied। আপনার এই পেজ দেখার অনুমতি নেই।<br><br>
    <a href="../login.php" class="btn btn-primary">লগইন পেজে যান</a>');
}

$success_message = '';
$error_message = '';

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    SecurityHelper::validatePost();
    
    try {
        // Add new course
        if (isset($_POST['add_course'])) {
            $stmt = $pdo->prepare("
                INSERT INTO courses (course_code, course_name, description, class_id, subject_id, 
                    teacher_id, start_date, end_date, status, created_by, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'draft', ?, NOW())
            ");
            $stmt->execute([
                sanitize($_POST['course_code']),
                sanitize($_POST['course_name']),
                sanitize($_POST['description'] ?? ''),
                $_POST['class_id'] ?: null,
                $_POST['subject_id'] ?: null,
                $_POST['teacher_id'] ?: null,
                $_POST['start_date'] ?: null,
                $_POST['end_date'] ?: null,
                $_SESSION['user_id']
            ]);
            $success_message = '✅ কোর্স সফলভাবে তৈরি হয়েছে!';
        }
        
        // Update course
        if (isset($_POST['update_course'])) {
            $stmt = $pdo->prepare("
                UPDATE courses 
                SET course_code=?, course_name=?, description=?, class_id=?, subject_id=?, 
                    teacher_id=?, start_date=?, end_date=?, status=?, updated_at=NOW()
                WHERE id=?
            ");
            $stmt->execute([
                sanitize($_POST['course_code']),
                sanitize($_POST['course_name']),
                sanitize($_POST['description'] ?? ''),
                $_POST['class_id'] ?: null,
                $_POST['subject_id'] ?: null,
                $_POST['teacher_id'] ?: null,
                $_POST['start_date'] ?: null,
                $_POST['end_date'] ?: null,
                $_POST['status'],
                intval($_POST['course_id'])
            ]);
            $success_message = '✅ কোর্স সফলভাবে আপডেট হয়েছে!';
        }
        
        // Delete course
        if (isset($_POST['delete_course'])) {
            $stmt = $pdo->prepare("DELETE FROM courses WHERE id=?");
            $stmt->execute([intval($_POST['course_id'])]);
            $success_message = '✅ কোর্স মুছে ফেলা হয়েছে!';
        }
        
        // Add module
        if (isset($_POST['add_module'])) {
            $stmt = $pdo->prepare("
                INSERT INTO course_modules (course_id, module_name, description, sort_order, created_at)
                VALUES (?, ?, ?, ?, NOW())
            ");
            $max_order = $pdo->query("SELECT MAX(sort_order) as max_order FROM course_modules WHERE course_id=" . intval($_POST['course_id']))->fetch()['max_order'] ?? 0;
            $stmt->execute([
                intval($_POST['course_id']),
                sanitize($_POST['module_name']),
                sanitize($_POST['description'] ?? ''),
                $max_order + 1
            ]);
            $success_message = '✅ মডিউল সফলভাবে যোগ করা হয়েছে!';
        }
        
        // Add lesson
        if (isset($_POST['add_lesson'])) {
            $stmt = $pdo->prepare("
                INSERT INTO course_lessons (module_id, course_id, lesson_title, content, video_url, 
                    duration_minutes, sort_order, is_free, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");
            $max_order = $pdo->query("SELECT MAX(sort_order) as max_order FROM course_lessons WHERE module_id=" . intval($_POST['module_id']))->fetch()['max_order'] ?? 0;
            $stmt->execute([
                intval($_POST['module_id']),
                intval($_POST['course_id']),
                sanitize($_POST['lesson_title']),
                sanitize($_POST['content'] ?? ''),
                sanitize($_POST['video_url'] ?? ''),
                intval($_POST['duration_minutes'] ?? 0),
                $max_order + 1,
                isset($_POST['is_free']) ? 1 : 0
            ]);
            $success_message = '✅ পাঠ সফলভাবে যোগ করা হয়েছে!';
        }
        
    } catch(Exception $e) {
        $error_message = '❌ ত্রুটি: ' . $e->getMessage();
    }
}

// Get all courses with related data
$courses = $pdo->query("
    SELECT c.*, cl.name as class_name, s.name as subject_name,
           CONCAT(t.first_name, ' ', t.last_name) as teacher_name,
           (SELECT COUNT(*) FROM course_modules WHERE course_id = c.id) as total_modules,
           (SELECT COUNT(*) FROM course_lessons WHERE course_id = c.id) as total_lessons,
           (SELECT COUNT(*) FROM student_enrollments WHERE course_id = c.id) as enrolled_students
    FROM courses c
    LEFT JOIN classes cl ON c.class_id = cl.id
    LEFT JOIN subjects s ON c.subject_id = s.id
    LEFT JOIN teachers t ON c.teacher_id = t.id
    ORDER BY c.created_at DESC
")->fetchAll();

// Get data for dropdowns
$classes = $pdo->query("SELECT id, name FROM classes WHERE status='active' ORDER BY name")->fetchAll();
$subjects = $pdo->query("SELECT id, name, code FROM subjects WHERE status='active' ORDER BY name")->fetchAll();
$teachers = $pdo->query("SELECT id, first_name, last_name FROM teachers WHERE status='active' ORDER BY first_name")->fetchAll();

// Get modules for selected course
$selected_course_id = $_GET['course_id'] ?? null;
$modules = [];
if ($selected_course_id) {
    $modules = $pdo->prepare("SELECT * FROM course_modules WHERE course_id=? ORDER BY sort_order");
    $modules->execute([$selected_course_id]);
    $modules = $modules->fetchAll();
}

// Edit mode
$edit_course = null;
if (isset($_GET['edit']) && $_GET['edit']) {
    $edit_course = $pdo->prepare("SELECT * FROM courses WHERE id=?");
    $edit_course->execute([intval($_GET['edit'])]);
    $edit_course = $edit_course->fetch();
}

// View course details
$view_course = null;
if (isset($_GET['view']) && $_GET['view']) {
    $view_course = $pdo->prepare("
        SELECT c.*, cl.name as class_name, s.name as subject_name,
               CONCAT(t.first_name, ' ', t.last_name) as teacher_name
        FROM courses c
        LEFT JOIN classes cl ON c.class_id = cl.id
        LEFT JOIN subjects s ON c.subject_id = s.id
        LEFT JOIN teachers t ON c.teacher_id = t.id
        WHERE c.id=?
    ");
    $view_course->execute([intval($_GET['view'])]);
    $view_course = $view_course->fetch();
    
    if ($view_course) {
        $view_modules = $pdo->prepare("SELECT * FROM course_modules WHERE course_id=? ORDER BY sort_order");
        $view_modules->execute([$view_course['id']]);
        $view_modules = $view_modules->fetchAll();
        
        $view_lessons = $pdo->prepare("SELECT * FROM course_lessons WHERE course_id=? ORDER BY sort_order");
        $view_lessons->execute([$view_course['id']]);
        $view_lessons = $view_lessons->fetchAll();
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>কোর্স ব্যবস্থাপনা - <?= APP_NAME ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <main class="col-md-12 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">📚 কোর্স ব্যবস্থাপনা</h1>
                    <div>
                        <a href="index.php" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left"></i> ফিরে যান
                        </a>
                    </div>
                </div>
                
                <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <?= $success_message ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                <?php if ($error_message): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <?= $error_message ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                
                <!-- View Course Details -->
                <?php if ($view_course): ?>
                <div class="card mb-4">
                    <div class="card-header bg-info text-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">📖 <?= htmlspecialchars($view_course['course_name']) ?></h5>
                        <a href="?" class="btn btn-light btn-sm">বন্ধ করুন</a>
                    </div>
                    <div class="card-body">
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <p><strong>কোর্স কোড:</strong> <?= htmlspecialchars($view_course['course_code']) ?></p>
                                <p><strong>ক্লাস:</strong> <?= htmlspecialchars($view_course['class_name'] ?? 'N/A') ?></p>
                                <p><strong>বিষয়:</strong> <?= htmlspecialchars($view_course['subject_name'] ?? 'N/A') ?></p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>শিক্ষক:</strong> <?= htmlspecialchars($view_course['teacher_name'] ?? 'N/A') ?></p>
                                <p><strong>স্ট্যাটাস:</strong> <span class="badge bg-<?= $view_course['status'] == 'active' ? 'success' : ($view_course['status'] == 'draft' ? 'warning' : 'secondary') ?>"><?= $view_course['status'] == 'active' ? 'অ্যাক্টিভ' : ($view_course['status'] == 'draft' ? 'ড্রাফট' : 'আর্কাইভ') ?></span></p>
                                <p><strong>মোট মডিউল:</strong> <?= count($view_modules ?? []) ?> | <strong>মোট পাঠ:</strong> <?= count($view_lessons ?? []) ?></p>
                            </div>
                        </div>
                        
                        <h6 class="mb-3">📁 মডিউল ও পাঠসমূহ</h6>
                        <?php foreach ($view_modules as $module): ?>
                            <div class="card mb-3">
                                <div class="card-header bg-light">
                                    <strong><?= htmlspecialchars($module['module_name']) ?></strong>
                                </div>
                                <div class="card-body">
                                    <ul class="list-group list-group-flush">
                                        <?php 
                                        $module_lessons = array_filter($view_lessons ?? [], fn($l) => $l['module_id'] == $module['id']);
                                        foreach ($module_lessons as $lesson):
                                        ?>
                                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                                <span><i class="fas fa-play-circle text-primary"></i> <?= htmlspecialchars($lesson['lesson_title']) ?></span>
                                                <span class="badge bg-light text-dark"><?= $lesson['duration_minutes'] ?> মিনিট</span>
                                            </li>
                                        <?php endforeach; ?>
                                        <?php if (empty($module_lessons)): ?>
                                            <li class="list-group-item text-muted">কোনো পাঠ যোগ করা হয়নি</li>
                                        <?php endif; ?>
                                    </ul>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Add/Edit Course Form -->
                <div class="card mb-4">
                    <div class="card-header <?= $edit_course ? 'bg-warning' : 'bg-primary' ?> text-white">
                        <h5 class="mb-0"><?= $edit_course ? '✏️ কোর্স সম্পাদনা' : '➕ নতুন কোর্স যোগ করুন' ?></h5>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <?= csrf_field() ?>
                            <input type="hidden" name="course_id" value="<?= $edit_course['id'] ?? '' ?>">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">কোর্স কোড <span class="text-danger">*</span></label>
                                    <input type="text" name="course_code" class="form-control" required 
                                           value="<?= htmlspecialchars($edit_course['course_code'] ?? '') ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">কোর্স নাম <span class="text-danger">*</span></label>
                                    <input type="text" name="course_name" class="form-control" required
                                           value="<?= htmlspecialchars($edit_course['course_name'] ?? '') ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">স্ট্যাটাস</label>
                                    <select name="status" class="form-select">
                                        <option value="draft" <?= ($edit_course['status'] ?? '') == 'draft' ? 'selected' : '' ?>>ড্রাফট</option>
                                        <option value="active" <?= ($edit_course['status'] ?? '') == 'active' ? 'selected' : '' ?>>অ্যাক্টিভ</option>
                                        <option value="archived" <?= ($edit_course['status'] ?? '') == 'archived' ? 'selected' : '' ?>>আর্কাইভ</option>
                                    </select>
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">বিবরণ</label>
                                    <textarea name="description" class="form-control" rows="2"><?= htmlspecialchars($edit_course['description'] ?? '') ?></textarea>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">ক্লাস</label>
                                    <select name="class_id" class="form-select">
                                        <option value="">-- নির্বাচন --</option>
                                        <?php foreach ($classes as $c): ?>
                                        <option value="<?= $c['id'] ?>" <?= ($edit_course['class_id'] ?? '') == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">বিষয়</label>
                                    <select name="subject_id" class="form-select">
                                        <option value="">-- নির্বাচন --</option>
                                        <?php foreach ($subjects as $s): ?>
                                        <option value="<?= $s['id'] ?>" <?= ($edit_course['subject_id'] ?? '') == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">শিক্ষক</label>
                                    <select name="teacher_id" class="form-select">
                                        <option value="">-- নির্বাচন --</option>
                                        <?php foreach ($teachers as $t): ?>
                                        <option value="<?= $t['id'] ?>" <?= ($edit_course['teacher_id'] ?? '') == $t['id'] ? 'selected' : '' ?>><?= htmlspecialchars($t['first_name'] . ' ' . $t['last_name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">শুরুর তারিখ</label>
                                    <input type="date" name="start_date" class="form-control" value="<?= $edit_course['start_date'] ?? '' ?>">
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">শেষ তারিখ</label>
                                    <input type="date" name="end_date" class="form-control" value="<?= $edit_course['end_date'] ?? '' ?>">
                                </div>
                            </div>
                            <button type="submit" name="<?= $edit_course ? 'update_course' : 'add_course' ?>" class="btn <?= $edit_course ? 'btn-warning' : 'btn-primary' ?>">
                                <?= $edit_course ? '✏️ আপডেট করুন' : '➕ যোগ করুন' ?>
                            </button>
                            <?php if ($edit_course): ?>
                            <a href="?" class="btn btn-secondary">বাতিল করুন</a>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>
                
                <!-- Courses List -->
                <div class="card">
                    <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">📋 সকল কোর্স</h5>
                        <span class="badge bg-light text-dark">মোট: <?= count($courses) ?></span>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th>কোর্স কোড</th>
                                        <th>কোর্স নাম</th>
                                        <th>ক্লাস</th>
                                        <th>শিক্ষক</th>
                                        <th>মডিউল</th>
                                        <th>পাঠ</th>
                                        <th>ছাত্র</th>
                                        <th>স্ট্যাটাস</th>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($courses as $course): ?>
                                    <tr>
                                        <td><strong><?= htmlspecialchars($course['course_code']) ?></strong></td>
                                        <td><?= htmlspecialchars($course['course_name']) ?></td>
                                        <td><?= htmlspecialchars($course['class_name'] ?? '-') ?></td>
                                        <td><?= htmlspecialchars($course['teacher_name'] ?? '-') ?></td>
                                        <td><?= $course['total_modules'] ?></td>
                                        <td><?= $course['total_lessons'] ?></td>
                                        <td><?= $course['enrolled_students'] ?></td>
                                        <td>
                                            <span class="badge bg-<?= $course['status'] == 'active' ? 'success' : ($course['status'] == 'draft' ? 'warning' : 'secondary') ?>">
                                                <?= $course['status'] == 'active' ? 'অ্যাক্টিভ' : ($course['status'] == 'draft' ? 'ড্রাফট' : 'আর্কাইভ') ?>
                                            </span>
                                        </td>
                                        <td>
                                            <a href="?view=<?= $course['id'] ?>" class="btn btn-sm btn-info" title="দেখুন">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="?edit=<?= $course['id'] ?>" class="btn btn-sm btn-warning" title="সম্পাদনা">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#addModuleModal<?= $course['id'] ?>" title="মডিউল যোগ">
                                                <i class="fas fa-folder-plus"></i>
                                            </button>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('আপনি কি নিশ্চিত যে এই কোর্সটি মুছে ফেলতে চান?');">
                                                <?= csrf_field() ?>
                                                <input type="hidden" name="course_id" value="<?= $course['id'] ?>">
                                                <button type="submit" name="delete_course" class="btn btn-sm btn-danger" title="মুছুন">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php if (empty($courses)): ?>
                                    <tr>
                                        <td colspan="9" class="text-center text-muted py-4">
                                            <i class="fas fa-inbox fa-2x mb-2"></i><br>
                                            কোনো কোর্স পাওয়া যায়নি
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- Add Module Modals -->
                <?php foreach ($courses as $course): ?>
                <div class="modal fade" id="addModuleModal<?= $course['id'] ?>" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">📁 <?= htmlspecialchars($course['course_name']) ?> - মডিউল যোগ করুন</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <form method="POST">
                                <?= csrf_field() ?>
                                <input type="hidden" name="course_id" value="<?= $course['id'] ?>">
                                <div class="modal-body">
                                    <div class="mb-3">
                                        <label class="form-label">মডিউলের নাম <span class="text-danger">*</span></label>
                                        <input type="text" name="module_name" class="form-control" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label">বিবরণ</label>
                                        <textarea name="description" class="form-control" rows="2"></textarea>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
                                    <button type="submit" name="add_module" class="btn btn-primary">মডিউল যোগ করুন</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
