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

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

$select = "--- Select Class ---";

// Fetch all classes
$classes = [];
$class_query = $connection->query("SELECT * FROM classes ORDER BY classes ASC");
if ($class_query && $class_query->num_rows > 0) {
    while ($c = $class_query->fetch_assoc()) {
        $classes[] = $c['classes'];
    }
}

// Fetch all sessions
$sessions = [];
$session_query = $connection->query("SELECT * FROM sessions ORDER BY sessions ASC");
if ($session_query && $session_query->num_rows > 0) {
    while ($s = $session_query->fetch_assoc()) {
        $sessions[] = $s['sessions'];
    }
}

/* =========================
   HANDLE PRESETS AND DATES
========================= */
$preset = $_POST['preset'] ?? '';
$date_from = $_POST['date_from'] ?? '';
$date_to   = $_POST['date_to'] ?? '';

if ($preset === 'today') {
    $date_from = $date_to = date('Y-m-d');
} elseif ($preset === 'week') {
    $date_from = date('Y-m-d', strtotime('monday this week'));
    $date_to   = date('Y-m-d', strtotime('sunday this week'));
} elseif ($preset === 'month') {
    $date_from = date('Y-m-01');
    $date_to   = date('Y-m-t');
}
?>

<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Student Attendance</h1>
    <p>View Student Attendance History</p>
  </div>
</div>

<div class='card'>
   <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>View Student Attendance Record</h4>
        </div>
        <div class='panel-body'>
            <form method='POST' action=''>
                <div class='row mb-2'>
                    <!-- PRESET DROPDOWN -->
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Quick Preset</span>
                            <select name='preset' class='form-control' onchange="this.form.submit()">
                                <option value=''>-- Select Preset --</option>
                                <option value='today' <?= $preset=='today'?'selected':'' ?>>Today</option>
                                <option value='week' <?= $preset=='week'?'selected':'' ?>>This Week</option>
                                <option value='month' <?= $preset=='month'?'selected':'' ?>>This Month</option>
                            </select>
                        </div>
                    </div>
                    <!-- DATE RANGE -->
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>From</span>
                            <input type='date' name='date_from' class='form-control' value='<?= htmlspecialchars($date_from) ?>' required />
                        </div>
                    </div>
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>To</span>
                            <input type='date' name='date_to' class='form-control' value='<?= htmlspecialchars($date_to) ?>' required />
                        </div>
                    </div>
                    <!-- CLASS -->
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Class</span>
                            <select class='form-control' name='view_attendance_class'>
                                <option selected><?= $select ?></option>
                                <?php foreach($classes as $cls): ?>
                                    <option value="<?= htmlspecialchars($cls) ?>" <?= (($_POST['view_attendance_class'] ?? '')==$cls)?'selected':'' ?>><?= htmlspecialchars($cls) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
                <br />
                <div class='row'>
                    <!-- TERM -->
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Term</span>
                            <select class='form-control' name='view_attendance_term'>
                                <?php
                                $terms = ['First Term','Second Term','Third Term'];
                                foreach($terms as $t):
                                    $selected = (($_POST['view_attendance_term'] ?? '')==$t)?'selected':'';
                                    echo "<option value='$t' $selected>$t</option>";
                                endforeach;
                                ?>
                            </select>
                        </div>
                    </div>
                    <!-- SESSION -->
                    <div class='col-md-3'>
                        <div class='input-group'>
                            <span class='input-group-addon'>Session</span>
                            <select class='form-control' name='view_attendance_session'>
                                <?php foreach($sessions as $sess): ?>
                                    <option value="<?= htmlspecialchars($sess) ?>" <?= (($_POST['view_attendance_session'] ?? '')==$sess)?'selected':'' ?>><?= htmlspecialchars($sess) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class='col-md-3'>
                        <input type='submit' name='view_attendance_btn' value='VIEW RECORDS' class='btn btn-primary' />
                    </div>
                </div>
            </form>
            <br />
        </div>
    </div>

<?php
if(isset($_POST['view_attendance_btn'])){
    $date_from = $_POST['date_from'];
    $date_to   = $_POST['date_to'];
    $view_class = $_POST['view_attendance_class'];
    $view_term = $_POST['view_attendance_term'];
    $view_session = $_POST['view_attendance_session'];

    if($view_class == $select){
        echo "<p class='text-danger'><b>Please select a class to view attendance</b></p>";
    } else {
        $query = "SELECT * FROM student_attendance 
                  WHERE date BETWEEN ? AND ? AND class=? AND term=? AND session=? 
                  ORDER BY reg_number ASC";
        $stmt = $connection->prepare($query);
        $stmt->bind_param("sssss", $date_from, $date_to, $view_class, $view_term, $view_session);
        $stmt->execute();
        $res = $stmt->get_result();

        if($res->num_rows > 0){
            echo "
                <div class='table-responsive'>
                    <table class='table table-bordered table-hover'>
                        <thead>
                            <tr>
                                <th>S/N</th>
                                <th>NAME</th>
                                <th>REG NO</th>
                                <th>DATE</th>
                                <th>CLASS</th>
                                <th>TERM</th>
                                <th>SESSION</th>
                                <th>Morning Roll Call</th>
                                <th>AM Time</th>
                                <th>Afternoon Roll Call</th>
                                <th>PM Time</th>
                            </tr>
                        </thead>
                        <tbody>
            ";
            $i=1;
            while($row = $res->fetch_assoc()){
                $am = $row['roll_call'] ?? '-';
                $pm = $row['afternoonrollcall'] ?? '-';
                $am_time = $row['time_morning'] ?? '-';
                $pm_time = $row['time_afternoon'] ?? '-';
                echo "
                    <tr>
                        <td>{$i}</td>
                        <td>".htmlspecialchars($row['name'])."</td>
                        <td>".htmlspecialchars($row['reg_number'])."</td>
                        <td>".htmlspecialchars($row['date'])."</td>
                        <td>".htmlspecialchars($row['class'])."</td>
                        <td>".htmlspecialchars($row['term'])."</td>
                        <td>".htmlspecialchars($row['session'])."</td>
                        <td>{$am}</td>
                        <td>{$am_time}</td>
                        <td>{$pm}</td>
                        <td>{$pm_time}</td>
                    </tr>
                ";
                $i++;
            }
            echo "
                        </tbody>
                    </table>
                </div>
            ";
        } else {
            echo "<p class='text-danger'><b>No attendance records found for the selected date/class range</b></p>";
        }
    }
}
?>
</div>
