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

if (!isset($_SESSION['staff'])) {
    $_SESSION['msg'] = "Please login to view student attendance history.";
    $_SESSION['type'] = "danger";
    header("Location: login.php");
    exit;
}

$staff_id = $_SESSION['staff'];

/* ===========================
   CURRENT TERM & SESSION
=========================== */
$term_default = '';
$session_default = '';

$cs = $connection->query("SELECT current_term, current_session FROM current_season LIMIT 1");
if ($cs && $cs->num_rows > 0) {
    $current_season = $cs->fetch_assoc();
    $term_default = $current_season['current_term'] ?? '';
    $session_default = $current_season['current_session'] ?? '';
}

/* ===========================
   FILTER VALUES
=========================== */
$date_filter    = $_POST['filter_date'] ?? '';
$term_filter    = $_POST['filter_term'] ?? $term_default;
$session_filter = $_POST['filter_session'] ?? $session_default;
$class_filter   = $_POST['filter_class'] ?? '';

/* ===========================
   FETCH STAFF ASSIGNED CLASSES
=========================== */
$classes = [];
$class_stmt = $connection->prepare(
    "SELECT DISTINCT class FROM teacher_classes WHERE teacher_id = ? ORDER BY class ASC"
);
$class_stmt->bind_param("s", $staff_id);
$class_stmt->execute();
$class_res = $class_stmt->get_result();

while ($c = $class_res->fetch_assoc()) {
    if (!empty($c['class'])) {
        $classes[] = $c['class'];
    }
}

/* ===========================
   ATTENDANCE QUERY
=========================== */
$sql = "
SELECT 
    sa.*,
    s.firstname,
    s.lastname,
    s.othername
FROM student_attendance sa
LEFT JOIN students s 
    ON sa.reg_number = s.reg_number 
    AND sa.class = s.class
WHERE sa.term = ?
AND sa.session = ?
AND sa.class IN (" . implode(',', array_fill(0, count($classes), '?')) . ")
";

$params = array_merge([$term_filter, $session_filter], $classes);
$types  = "ss" . str_repeat("s", count($classes));

if ($date_filter) {
    $sql .= " AND sa.date = ?";
    $params[] = $date_filter;
    $types .= "s";
}

if ($class_filter && in_array($class_filter, $classes)) {
    $sql .= " AND sa.class = ?";
    $params[] = $class_filter;
    $types .= "s";
}

$sql .= " ORDER BY sa.date DESC, sa.class ASC, s.firstname ASC";

$stmt = $connection->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
?>

<div class="page-title">
    <div>
        <h1><i class="fa fa-users"></i> Student Attendance History</h1>
        <p>View recorded attendance for your assigned classes</p>
    </div>
</div>

<div class="card">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h4 class="text-center">Filter Attendance</h4>
        </div>
        <div class="panel-body">
            <form method="POST" class="row g-3">

                <div class="col-md-3">
                    <input type="date" name="filter_date" class="form-control"
                        value="<?= htmlspecialchars($date_filter ?? '', ENT_QUOTES, 'UTF-8') ?>">
                </div>

                <div class="col-md-3">
                    <select name="filter_term" class="form-control">
                        <?php
                        foreach (["First Term", "Second Term", "Third Term"] as $t) {
                            $sel = ($t === $term_filter) ? "selected" : "";
                            echo "<option $sel>$t</option>";
                        }
                        ?>
                    </select>
                </div>

                <div class="col-md-3">
                    <select name="filter_session" class="form-control">
                        <option selected><?= htmlspecialchars($session_filter ?? '', ENT_QUOTES, 'UTF-8') ?></option>
                    </select>
                </div>

                <div class="col-md-3">
                    <select name="filter_class" class="form-control">
                        <option value="">All Assigned Classes</option>
                        <?php
                        foreach ($classes as $c) {
                            $sel = ($c === $class_filter) ? "selected" : "";
                            echo "<option value='".htmlspecialchars($c, ENT_QUOTES, 'UTF-8')."' $sel>"
                                .htmlspecialchars($c, ENT_QUOTES, 'UTF-8')."</option>";
                        }
                        ?>
                    </select>
                </div>

                <div class="col-md-12 mt-2">
                    <button type="submit" class="btn btn-primary btn-sm w-100">Filter</button>
                </div>
            </form>
        </div>
    </div>

    <div class="panel panel-primary mt-3">
        <div class="panel-heading">
            <h4 class="text-center">Student Attendance Records</h4>
        </div>
        <div class="panel-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover">
                    <thead class="table-primary">
                        <tr>
                            <th>#</th>
                            <th>Reg Number</th>
                            <th>Name</th>
                            <th>Class</th>
                            <th>Date</th>
                            <th>Morning Roll</th>
                            <th>AM Time</th>
                            <th>Afternoon Roll</th>
                            <th>PM Time</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php
                    if ($result->num_rows > 0) {
                        $i = 1;
                        while ($row = $result->fetch_assoc()) {

                            $fullname = trim(
                                ($row['firstname'] ?? '') . ' ' .
                                ($row['lastname'] ?? '') . ' ' .
                                ($row['othername'] ?? '')
                            );

                            $am  = $row['roll_call'] ?? '-';
                            $pm  = $row['afternoonrollcall'] ?? '-';
                            $tam = $row['time_morning'] ?? '-';
                            $tpm = $row['time_afternoon'] ?? '-';

                            echo "<tr>
                                <td>{$i}</td>
                                <td>".htmlspecialchars($row['reg_number'] ?? '', ENT_QUOTES, 'UTF-8')."</td>
                                <td>".htmlspecialchars($fullname, ENT_QUOTES, 'UTF-8')."</td>
                                <td>".htmlspecialchars($row['class'] ?? '', ENT_QUOTES, 'UTF-8')."</td>
                                <td>".htmlspecialchars($row['date'] ?? '', ENT_QUOTES, 'UTF-8')."</td>
                                <td>".($am === 'Present'
                                    ? "<span class='badge bg-success'>Present</span>"
                                    : "<span class='badge bg-danger'>Absent</span>")."</td>
                                <td>".htmlspecialchars($tam, ENT_QUOTES, 'UTF-8')."</td>
                                <td>".($pm === 'Present'
                                    ? "<span class='badge bg-success'>Present</span>"
                                    : "<span class='badge bg-danger'>Absent</span>")."</td>
                                <td>".htmlspecialchars($tpm, ENT_QUOTES, 'UTF-8')."</td>
                            </tr>";
                            $i++;
                        }
                    } else {
                        echo "<tr>
                            <td colspan='9' class='text-center text-danger'>
                                No attendance records found.
                            </td>
                        </tr>";
                    }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
