<?php
/**
 * Live Classes 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 {
        // Schedule live class
        if (isset($_POST['schedule_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, 
                    status, created_by, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'scheduled', ?, NOW())
            ");
            $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'],
                intval($_POST['duration_minutes'] ?? 60),
                $_SESSION['user_id']
            ]);
            $success_message = '✅ লাইভ ক্লাস সফলভাবে নির্ধারিত হয়েছে!';
        }
        
        // Update live class
        if (isset($_POST['update_class'])) {
            $stmt = $pdo->prepare("
                UPDATE live_classes 
                SET course_id=?, teacher_id=?, class_id=?, subject_id=?, topic=?, 
                    description=?, meeting_link=?, meeting_id=?, passcode=?, 
                    scheduled_at=?, duration_minutes=?, status=?, updated_at=NOW()
                WHERE id=?
            ");
            $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'],
                intval($_POST['duration_minutes'] ?? 60),
                $_POST['status'],
                intval($_POST['class_id_edit'])
            ]);
            $success_message = '✅ লাইভ ক্লাস সফলভাবে আপডেট হয়েছে!';
        }
        
        // Delete live class
        if (isset($_POST['delete_class'])) {
            $stmt = $pdo->prepare("DELETE FROM live_classes WHERE id=?");
            $stmt->execute([intval($_POST['live_class_id'])]);
            $success_message = '✅ লাইভ ক্লাস মুছে ফেলা হয়েছে!';
        }
        
        // Update status
        if (isset($_POST['update_status'])) {
            $stmt = $pdo->prepare("UPDATE live_classes SET status=? WHERE id=?");
            $stmt->execute([$_POST['status'], intval($_POST['live_class_id'])]);
            $success_message = '✅ স্ট্যাটাস আপডেট হয়েছে!';
        }
        
    } catch(Exception $e) {
        $error_message = '❌ ত্রুটি: ' . $e->getMessage();
    }
}

// Get all live classes with related data
$filter = $_GET['filter'] ?? 'upcoming';
$where_clause = "";

switch ($filter) {
    case 'upcoming':
        $where_clause = "WHERE lc.scheduled_at >= CURDATE()";
        break;
    case 'ongoing':
        $where_clause = "WHERE lc.status = 'ongoing'";
        break;
    case 'completed':
        $where_clause = "WHERE lc.status = 'completed'";
        break;
    case 'all':
        $where_clause = "";
        break;
}

$liveClasses = $pdo->query("
    SELECT lc.*, c.course_name, c.course_code,
           CONCAT(t.first_name, ' ', t.last_name) as teacher_name,
           s.name as subject_name, cl.name as class_name,
           (SELECT COUNT(*) FROM live_class_attendance WHERE live_class_id = lc.id) as attendees
    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
    LEFT JOIN classes cl ON lc.class_id = cl.id
    $where_clause
    ORDER BY lc.scheduled_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 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();
$courses = $pdo->query("SELECT id, course_name, course_code FROM courses WHERE status='active' ORDER BY course_name")->fetchAll();

// Edit mode
$edit_class = null;
if (isset($_GET['edit']) && $_GET['edit']) {
    $edit_class = $pdo->prepare("SELECT * FROM live_classes WHERE id=?");
    $edit_class->execute([intval($_GET['edit'])]);
    $edit_class = $edit_class->fetch();
}
?>
<!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; ?>
                
                <!-- Schedule/Edit Live Class Form -->
                <div class="card mb-4">
                    <div class="card-header <?= $edit_class ? 'bg-warning' : 'bg-primary' ?> text-white">
                        <h5 class="mb-0"><?= $edit_class ? '✏️ ক্লাস সম্পাদনা' : '📅 নতুন লাইভ ক্লাস নির্ধারণ করুন' ?></h5>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <?= csrf_field() ?>
                            <input type="hidden" name="class_id_edit" value="<?= $edit_class['id'] ?? '' ?>">
                            <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
                                           value="<?= htmlspecialchars($edit_class['topic'] ?? '') ?>">
                                </div>
                                <div class="col-md-3 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'] ?>" <?= ($edit_class['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>
                                    <select name="course_id" class="form-select">
                                        <option value="">-- নির্বাচন --</option>
                                        <?php foreach ($courses as $c): ?>
                                        <option value="<?= $c['id'] ?>" <?= ($edit_class['course_id'] ?? '') == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['course_name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </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_class['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_class['subject_id'] ?? '') == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">তারিখ ও সময় <span class="text-danger">*</span></label>
                                    <input type="datetime-local" name="scheduled_at" class="form-control" required
                                           value="<?= isset($edit_class['scheduled_at']) ? date('Y-m-d\TH:i', strtotime($edit_class['scheduled_at'])) : '' ?>">
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">সময়কাল (মিনিট)</label>
                                    <input type="number" name="duration_minutes" class="form-control" value="<?= $edit_class['duration_minutes'] ?? 60 ?>" min="15">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">বিবরণ</label>
                                    <textarea name="description" class="form-control" rows="2"><?= htmlspecialchars($edit_class['description'] ?? '') ?></textarea>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">মিটিং লিংক</label>
                                    <input type="url" name="meeting_link" class="form-control" placeholder="https://zoom.us/..."
                                           value="<?= htmlspecialchars($edit_class['meeting_link'] ?? '') ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">মিটিং ID</label>
                                    <input type="text" name="meeting_id" class="form-control"
                                           value="<?= htmlspecialchars($edit_class['meeting_id'] ?? '') ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">পাসকোড</label>
                                    <input type="text" name="passcode" class="form-control"
                                           value="<?= htmlspecialchars($edit_class['passcode'] ?? '') ?>">
                                </div>
                                <?php if ($edit_class): ?>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label">স্ট্যাটাস</label>
                                    <select name="status" class="form-select">
                                        <option value="scheduled" <?= $edit_class['status'] == 'scheduled' ? 'selected' : '' ?>>নির্ধারিত</option>
                                        <option value="ongoing" <?= $edit_class['status'] == 'ongoing' ? 'selected' : '' ?>>চলমান</option>
                                        <option value="completed" <?= $edit_class['status'] == 'completed' ? 'selected' : '' ?>>সম্পন্ন</option>
                                        <option value="cancelled" <?= $edit_class['status'] == 'cancelled' ? 'selected' : '' ?>>বাতিল</option>
                                    </select>
                                </div>
                                <?php endif; ?>
                            </div>
                            <button type="submit" name="<?= $edit_class ? 'update_class' : 'schedule_class' ?>" class="btn <?= $edit_class ? 'btn-warning' : 'btn-primary' ?>">
                                <?= $edit_class ? '✏️ আপডেট করুন' : '📅 নির্ধারণ করুন' ?>
                            </button>
                            <?php if ($edit_class): ?>
                            <a href="?" class="btn btn-secondary">বাতিল করুন</a>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>
                
                <!-- Filter Buttons -->
                <div class="mb-3">
                    <a href="?filter=all" class="btn btn-sm <?= $filter == 'all' ? 'btn-dark' : 'btn-outline-dark' ?>">সব</a>
                    <a href="?filter=upcoming" class="btn btn-sm <?= $filter == 'upcoming' ? 'btn-primary' : 'btn-outline-primary' ?>">আপকামিং</a>
                    <a href="?filter=ongoing" class="btn btn-sm <?= $filter == 'ongoing' ? 'btn-success' : 'btn-outline-success' ?>">চলমান</a>
                    <a href="?filter=completed" class="btn btn-sm <?= $filter == 'completed' ? 'btn-secondary' : 'btn-outline-secondary' ?>">সম্পন্ন</a>
                </div>
                
                <!-- Live Classes 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($liveClasses) ?></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>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($liveClasses as $class): ?>
                                    <tr>
                                        <td><strong><?= htmlspecialchars($class['topic']) ?></strong></td>
                                        <td><?= htmlspecialchars($class['course_name'] ?? '-') ?></td>
                                        <td><?= htmlspecialchars($class['teacher_name']) ?></td>
                                        <td><?= date('d M Y, h:i A', strtotime($class['scheduled_at'])) ?></td>
                                        <td><?= $class['duration_minutes'] ?> মিনিট</td>
                                        <td><span class="badge bg-info"><?= $class['attendees'] ?> জন</span></td>
                                        <td>
                                            <span class="badge bg-<?= $class['status'] == 'scheduled' ? 'primary' : ($class['status'] == 'ongoing' ? 'success' : ($class['status'] == 'completed' ? 'secondary' : 'danger')) ?>">
                                                <?= $class['status'] == 'scheduled' ? 'নির্ধারিত' : ($class['status'] == 'ongoing' ? 'চলমান' : ($class['status'] == 'completed' ? 'সম্পন্ন' : 'বাতিল')) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($class['meeting_link']): ?>
                                            <a href="<?= htmlspecialchars($class['meeting_link']) ?>" target="_blank" class="btn btn-sm btn-success" title="জয়েন করুন">
                                                <i class="fas fa-video"></i>
                                            </a>
                                            <?php endif; ?>
                                            <a href="?edit=<?= $class['id'] ?>" class="btn btn-sm btn-warning" title="সম্পাদনা">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('আপনি কি নিশ্চিত যে এই ক্লাসটি মুছে ফেলতে চান?');">
                                                <?= csrf_field() ?>
                                                <input type="hidden" name="live_class_id" value="<?= $class['id'] ?>">
                                                <button type="submit" name="delete_class" class="btn btn-sm btn-danger" title="মুছুন">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    <?php if (empty($liveClasses)): ?>
                                    <tr>
                                        <td colspan="8" class="text-center text-muted py-4">
                                            <i class="fas fa-calendar-times fa-2x mb-2"></i><br>
                                            কোনো লাইভ ক্লাস পাওয়া যায়নি
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
            </main>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
