<?php
session_start();
include('db_connection.php');

if (!isset($_SESSION['teacher_id']) || $_SESSION['role'] !== 'teacher') {
    header("Location: teacher_login.php");
    exit();
}

$teacher_id = $_SESSION['teacher_id'];

/* CLASSES */
$classes = [];
$sql = "SELECT class_id, class_name FROM classes WHERE teacher_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $teacher_id);
$stmt->execute();
$classes = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$class_id = $_GET['class_id'] ?? ($classes[0]['class_id'] ?? 0);

/* STUDENTS MAP */
$student_names = [];

if ($class_id) {
    $sql = "SELECT student_id, name FROM students WHERE class_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $class_id);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    foreach ($res as $s) {
        $student_names[$s['student_id']] = $s['name'];
    }
}

/* ATTENDANCE */
$records = [];
if ($class_id) {
    $sql = "SELECT * FROM student_attendance WHERE class_id = ? ORDER BY date DESC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $class_id);
    $stmt->execute();
    $records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}

$conn->close();
?>

<!DOCTYPE html>
<html>
<head>
<title>Attendance</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
.sidebar{
    width:240px;height:100vh;position:fixed;background:#1e2a38;padding-top:20px;
}
.sidebar a{display:block;color:#fff;padding:12px;text-decoration:none}
.sidebar a:hover{background:#34495e}
.main{margin-left:240px;padding:20px}
</style>
</head>

<body>

<div class="sidebar">
    <a href="teacher_dashboard.php">Dashboard</a>
    <a href="attendance.php">Attendance</a>
    <a href="add_attendance.php">Add Attendance</a>
    <a href="feedback_grading.php">Feedback</a>
    <a href="logout.php">Logout</a>
</div>

<div class="main">

<h3>Attendance Records</h3>

<form method="GET" class="mb-3">
    <select name="class_id" class="form-select w-25" onchange="this.form.submit()">
        <?php foreach ($classes as $c): ?>
            <option value="<?= $c['class_id'] ?>" <?= $c['class_id']==$class_id?'selected':'' ?>>
                <?= htmlspecialchars($c['class_name']) ?>
            </option>
        <?php endforeach; ?>
    </select>
</form>

<a href="add_attendance.php" class="btn btn-primary mb-3">Mark Attendance</a>

<table class="table table-bordered">
    <tr>
        <th>Date</th>
        <th>Student</th>
        <th>Status</th>
    </tr>

    <?php foreach ($records as $r): ?>
    <tr>
        <td><?= $r['date'] ?></td>
        <td><?= $student_names[$r['student_id']] ?? 'Unknown' ?></td>
        <td><?= $r['status'] ?></td>
    </tr>
    <?php endforeach; ?>
</table>

</div>

</body>
</html>