<?php
/**
 * Online Class / LMS Module
 */

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 - support both new and legacy session variables
$user_role = $_SESSION['user_role'] ?? $_SESSION['role'] ?? '';
if (!isset($_SESSION['user_id']) || ($user_role !== 'admin' && $user_role !== 'teacher')) {
    http_response_code(403);
    die('❌ অ্যাক্সেস denied। আপনার এই পেজ দেখার অনুমতি নেই।<br><br>
    <a href="../../login.php" class="btn btn-primary">লগইন পেজে যান</a>');
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    SecurityHelper::validatePost();
    
    try {
        if (isset($_POST['create_course'])) {
            $stmt = $pdo->prepare("
                INSERT INTO courses (course_code, course_name, description, class_id, subject_id, 
                    teacher_id, start_date, end_date, created_by) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $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 = '✅ কোর্স সফলভাবে তৈরি হয়েছে!';
        }
        
        if (isset($_POST['schedule_live_class'])) {
            $stmt = $pdo->prepare("
                INSERT INTO live_classes (course_id, teacher_id, class_id, subject_id, topic, 
                    description, meeting_link, meeting_id, passcode, scheduled_at, duration_minutes) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $_POST['course_id'] ?: null,
                $_POST['teacher_id'],
                $_POST['class_id'] ?: null,
                $_POST['subject_id'] ?: null,
                sanitize($_POST['topic']),
                sanitize($_POST['description']),
                sanitize($_POST['meeting_link']),
                sanitize($_POST['meeting_id']),
                sanitize($_POST['passcode']),
                $_POST['scheduled_at'],
                $_POST['duration_minutes']
            ]);
            $success_message = '✅ লাইভ ক্লাস নির্ধারিত হয়েছে!';
        }
        
        if (isset($_POST['update_course_status'])) {
            $stmt = $pdo->prepare("UPDATE courses SET status=? WHERE id=?");
            $stmt->execute([$_POST['status'], intval($_POST['course_id'])]);
            $success_message = '✅ কোর্স স্ট্যাটাস আপডেট হয়েছে!';
        }
    } catch(Exception $e) {
        $error_message = '❌ ত্রুটি: ' . $e->getMessage();
    }
}

// Get statistics
$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 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();

$liveClasses = $pdo->query("
    SELECT lc.*, c.course_name, CONCAT(t.first_name, ' ', t.last_name) as teacher_name,
           s.name as subject_name
    FROM live_classes lc
    LEFT JOIN courses c ON lc.course_id = c.id
    LEFT JOIN teachers t ON lc.teacher_id = t.id
    LEFT JOIN subjects s ON lc.subject_id = s.id
    WHERE lc.scheduled_at >= CURDATE()
    ORDER BY lc.scheduled_at ASC
    LIMIT 10
")->fetchAll();

$totalCourses = count($courses);
$activeCourses = count(array_filter($courses, fn($c) => $c['status'] == 'active'));
$upcomingClasses = count($liveClasses);

// Get classes and subjects 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();
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>অনলাইন ক্লাস / LMS - <?= 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-9 ms-sm-auto col-lg-10 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">📚 অনলাইন ক্লাস / LMS</h1>
                    <div>
                        <a href="../../index.php" class="btn btn-outline-secondary">
                            <i class="fas fa-home"></i> হোম পেজ
                        </a>
                        <button class="btn btn-primary ms-2" data-bs-toggle="modal" data-bs-target="#createCourseModal">
                            <i class="fas fa-plus"></i> নতুন কোর্স
                        </button>
                        <button class="btn btn-success ms-2" data-bs-toggle="modal" data-bs-target="#scheduleClassModal">
                            <i class="fas fa-video"></i> লাইভ ক্লাস
                        </button>
                    </div>
                </div>
                
                <?php if ($success_message): ?>
                    <div class="alert alert-success"><?= $success_message ?></div>
                <?php endif; ?>
                <?php if ($error_message): ?>
                    <div class="alert alert-danger"><?= $error_message ?></div>
                <?php endif; ?>
                
                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-3">
                        <div class="card bg-primary text-white">
                            <div class="card-body text-center">
                                <h5>মোট কোর্স</h5>
                                <h2><?= $totalCourses ?></h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-success text-white">
                            <div class="card-body text-center">
                                <h5>অ্যাক্টিভ কোর্স</h5>
                                <h2><?= $activeCourses ?></h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-info text-white">
                            <div class="card-body text-center">
                                <h5>আপকামিং ক্লাস</h5>
                                <h2><?= $upcomingClasses ?></h2>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-dark">
                            <div class="card-body text-center">
                                <h5>মোট ছাত্র</h5>
                                <h2><?= array_sum(array_column($courses, 'enrolled_students')) ?></h2>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <!-- Courses Section -->
                    <div class="col-md-8">
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">🎓 কোর্সসমূহ</h5>
                                <a href="all_courses.php" class="btn btn-sm btn-outline-primary">সব দেখুন</a>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped table-hover">
                                        <thead>
                                            <tr>
                                                <th>কোর্স কোড</th>
                                                <th>কোর্স নাম</th>
                                                <th>ক্লাস</th>
                                                <th>শিক্ষক</th>
                                                <th>ছাত্র</th>
                                                <th>স্ট্যাটাস</th>
                                                <th>অ্যাকশন</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach (array_slice($courses, 0, 10) 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['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="course_details.php?id=<?= $course['id'] ?>" class="btn btn-sm btn-info">
                                                        <i class="fas fa-eye"></i>
                                                    </a>
                                                    <a href="course_modules.php?course_id=<?= $course['id'] ?>" class="btn btn-sm btn-primary">
                                                        <i class="fas fa-list"></i> মডিউল
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Live Classes Section -->
                    <div class="col-md-4">
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="mb-0">📹 আপকামিং লাইভ ক্লাস</h5>
                            </div>
                            <div class="card-body">
                                <?php if (count($liveClasses) > 0): ?>
                                <div class="list-group">
                                    <?php foreach ($liveClasses as $class): ?>
                                    <div class="list-group-item">
                                        <h6 class="mb-1"><?= htmlspecialchars($class['topic']) ?></h6>
                                        <p class="mb-1">
                                            <small>
                                                <i class="fas fa-chalkboard-teacher"></i> <?= htmlspecialchars($class['teacher_name']) ?><br>
                                                <i class="fas fa-clock"></i> <?= date('d M Y, h:i A', strtotime($class['scheduled_at'])) ?><br>
                                                <i class="fas fa-book"></i> <?= htmlspecialchars($class['subject_name'] ?? 'N/A') ?>
                                            </small>
                                        </p>
                                        <span class="badge bg-<?= $class['status'] == 'scheduled' ? 'primary' : ($class['status'] == 'ongoing' ? 'success' : 'secondary') ?>">
                                            <?= $class['status'] == 'scheduled' ? 'নির্ধারিত' : ($class['status'] == 'ongoing' ? 'চলমান' : 'শেষ') ?>
                                        </span>
                                        <?php if ($class['meeting_link']): ?>
                                        <a href="<?= htmlspecialchars($class['meeting_link']) ?>" target="_blank" class="btn btn-sm btn-success float-end">
                                            <i class="fas fa-video"></i> জয়েন
                                        </a>
                                        <?php endif; ?>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <?php else: ?>
                                <div class="text-center py-4 text-muted">
                                    <i class="fas fa-calendar-times fa-3x mb-3"></i>
                                    <p>কোনো আপকামিং ক্লাস নেই</p>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Navigation Links -->
                <div class="mt-3">
                    <a href="assignments.php" class="btn btn-outline-primary">
                        <i class="fas fa-tasks"></i> অ্যাসাইনমেন্ট ব্যবস্থাপনা
                    </a>
                    <a href="student_progress.php" class="btn btn-outline-success">
                        <i class="fas fa-chart-line"></i> ছাত্রের অগ্রগতি
                    </a>
                </div>
            </main>
        </div>
    </div>
    
    <!-- Create Course Modal -->
    <div class="modal fade" id="createCourseModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">নতুন কোর্স তৈরি করুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <?= csrf_field() ?>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">কোর্স কোড <span class="text-danger">*</span></label>
                                <input type="text" name="course_code" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">কোর্স নাম <span class="text-danger">*</span></label>
                                <input type="text" name="course_name" class="form-control" required>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">বিবরণ</label>
                                <textarea name="description" class="form-control" rows="3"></textarea>
                            </div>
                            <div class="col-md-4 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'] ?>"><?= htmlspecialchars($c['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4 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'] ?>"><?= htmlspecialchars($s['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4 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'] ?>"><?= htmlspecialchars($t['first_name'] . ' ' . $t['last_name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">শুরুর তারিখ</label>
                                <input type="date" name="start_date" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">শেষ তারিখ</label>
                                <input type="date" name="end_date" class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
                        <button type="submit" name="create_course" class="btn btn-primary">কোর্স তৈরি করুন</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Schedule Live Class Modal -->
    <div class="modal fade" id="scheduleClassModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">লাইভ ক্লাস নির্ধারণ করুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <?= csrf_field() ?>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">টপিক / বিষয় <span class="text-danger">*</span></label>
                                <input type="text" name="topic" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">শিক্ষক <span class="text-danger">*</span></label>
                                <select name="teacher_id" class="form-select" required>
                                    <option value="">-- নির্বাচন --</option>
                                    <?php foreach ($teachers as $t): ?>
                                    <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['first_name'] . ' ' . $t['last_name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-12 mb-3">
                                <label class="form-label">বিবরণ</label>
                                <textarea name="description" class="form-control" rows="2"></textarea>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">কোর্স (ঐচ্ছিক)</label>
                                <select name="course_id" class="form-select">
                                    <option value="">-- নির্বাচন --</option>
                                    <?php foreach ($courses as $c): ?>
                                    <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['course_name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">তারিখ ও সময় <span class="text-danger">*</span></label>
                                <input type="datetime-local" name="scheduled_at" class="form-control" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">সময়কাল (মিনিট)</label>
                                <input type="number" name="duration_minutes" class="form-control" value="60" min="15">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">মিটিং লিংক</label>
                                <input type="url" name="meeting_link" class="form-control" placeholder="https://zoom.us/...">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">মিটিং ID</label>
                                <input type="text" name="meeting_id" class="form-control">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">পাসকোড</label>
                                <input type="text" name="passcode" class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ</button>
                        <button type="submit" name="schedule_live_class" class="btn btn-success">ক্লাস নির্ধারণ করুন</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
