<?php
require_once(__DIR__ . "/../header.php");
require_once(__DIR__ . "/../../public/connection.php");

if (!isset($_SESSION['student'])) {
    header("Location: ../../login.php");
    exit;
}

$student_id = $_SESSION['student'];

// Fetch student's class
$stmt = $connection->prepare("SELECT class FROM students WHERE id = ?");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$res = $stmt->get_result();
$student_class = $res->fetch_assoc()['class'] ?? null;

if (!$student_class) {
    die("Your class is not set in your profile.");
}

// Fetch all virtual classes for this student's class
$stmt = $connection->prepare("
    SELECT *
    FROM virtual_classes
    WHERE class = ?
    ORDER BY start_datetime DESC
");
$stmt->bind_param("s", $student_class);
$stmt->execute();
$classes = $stmt->get_result();
?>

<div class="container mt-4">
<div class="card shadow-lg border-0">
    <div class="card-header bg-primary text-white fw-bold">
        Your Scheduled Classes
    </div>
    <div class="card-body">

    <?php if ($classes->num_rows > 0): ?>
        <div class="row g-3">
            <?php while ($c = $classes->fetch_assoc()): ?>
            <div class="col-md-6">
                <div class="card shadow-sm h-100 border-0">
                    <div class="card-body">

                        <h5 class="fw-bold mb-2"><?= htmlspecialchars($c['title']) ?></h5>
                        <p class="mb-1"><b>Subject:</b> <?= htmlspecialchars($c['subjects']) ?></p>
                        <p class="mb-1"><b>Class:</b> <?= htmlspecialchars($c['class']) ?></p>

                        <p class="mb-2 text-muted">
                            <i class="bi bi-clock"></i>
                            <?= date("d M Y h:i A", strtotime($c['start_datetime'])) ?> –
                            <?= date("h:i A", strtotime($c['end_datetime'])) ?>
                        </p>

                        <div class="d-flex flex-column gap-2 mt-3">
                            <?php if (!empty($c['join_url'])): ?>
                                <a href="<?= htmlspecialchars($c['join_url']) ?>" target="_blank" class="btn btn-primary w-100">
                                    <i class="bi bi-camera-video"></i> Join Class
                                </a>
                            <?php else: ?>
                                <span class="badge bg-danger align-self-start">Zoom not generated</span>
                            <?php endif; ?>
                        </div>

                    </div>
                </div>
            </div>
            <?php endwhile; ?>
        </div>
    <?php else: ?>
        <div class="alert alert-info shadow-sm mt-2">
            <i class="bi bi-info-circle"></i> No classes scheduled yet.
        </div>
    <?php endif; ?>

    </div>
</div>
</div>
