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

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

$staff_id = $_SESSION['staff'];

/* =======================
   SAVE ATTENDANCE
======================= */
if (isset($_POST['save_attendance_btn'])) {

    $class   = $_POST['attendance_class'];
    $date    = $_POST['roll_call_date'];
    $term    = $_POST['current_term'];
    $session = $_POST['current_session'];
    $rollType = $_POST['roll_type']; // morning | afternoon
    $total   = (int) $_POST['total_num'];

    if (!$class || !$date || !$rollType) {
        $_SESSION['msg']  = "Missing required fields";
        $_SESSION['type'] = "danger";
        header("Location: teacher_upload_attendance");
        exit;
    }

    for ($i = 0; $i < $total; $i++) {

        $reg_no = $_POST['attendance_reg_no'][$i];
        $name   = $_POST['attendance_name'][$i];

        $status = ($rollType === 'morning')
            ? $_POST['class_roll_call'][$i]
            : $_POST['class_roll_call_afternoon'][$i];

        // Check if record exists
        $check = $connection->prepare("
            SELECT id FROM student_attendance 
            WHERE reg_number=? AND date=? AND term=? AND session=? AND class=?
        ");
        $check->bind_param("sssss", $reg_no, $date, $term, $session, $class);
        $check->execute();
        $res = $check->get_result();

        if ($res->num_rows > 0) {

            $column = ($rollType === 'morning') ? 'roll_call' : 'afternoonrollcall';

            $upd = $connection->prepare("
                UPDATE student_attendance 
                SET $column=? 
                WHERE reg_number=? AND date=? AND class=?
            ");
            $upd->bind_param("ssss", $status, $reg_no, $date, $class);
            $upd->execute();

        } else {

            $morning   = ($rollType === 'morning') ? $status : 'Absent';
            $afternoon = ($rollType === 'afternoon') ? $status : 'Absent';

            $ins = $connection->prepare("
                INSERT INTO student_attendance 
                (reg_number, name, class, date, term, session, roll_call, afternoonrollcall)
                VALUES (?,?,?,?,?,?,?,?)
            ");
            $ins->bind_param(
                "ssssssss",
                $reg_no,
                $name,
                $class,
                $date,
                $term,
                $session,
                $morning,
                $afternoon
            );
            $ins->execute();
        }
    }

    $_SESSION['msg']  = ucfirst($rollType) . " roll call saved successfully";
    $_SESSION['type'] = "success";
    header("Location: teacher_upload_attendance");
    exit;
}
?>

<!-- =======================
     PAGE TITLE
======================= -->
<div class="page-title">
    <div>
        <h1><i class="fa fa-laptop"></i> Class Attendance</h1>
        <p>Save Daily Roll Call</p>
    </div>
</div>

<div class="card">
<div class="panel panel-primary">
<div class="panel-heading">
    <h4 class="text-center">Class Attendance</h4>
</div>
<div class="panel-body">

<!-- =======================
     SELECT CLASS
======================= -->
<form method="POST">
<div class="row">
<div class="col-md-4">
    <div class="input-group">
        <span class="input-group-addon">Student Class</span>
        <select class="form-control" name="attendance_class" required>
            <option value="">-- Select Class --</option>
            <?php
            $query = "SELECT DISTINCT class FROM teacher_classes WHERE teacher_id='$staff_id'";
            $run = mysqli_query($connection, $query);
            while ($row = mysqli_fetch_assoc($run)) {
                echo "<option value='{$row['class']}'>{$row['class']}</option>";
            }
            ?>
        </select>
    </div>
</div>
<div class="col-md-3">
    <input type="submit" name="view_members_btn" value="VIEW CLASS MEMBERS" class="btn btn-primary">
</div>
</div>
</form>
<br>

<?php
/* =======================
   VIEW STUDENTS
======================= */
if (isset($_POST['view_members_btn'])) {

$class = $_POST['attendance_class'];
$query = "SELECT * FROM students WHERE class='$class'";
$run = mysqli_query($connection, $query);

if (mysqli_num_rows($run) > 0) {
$i = 0; $sn = 1;
?>

<form method="POST">
<input type="hidden" name="attendance_class" value="<?= $class ?>">

<div class="row">
<div class="col-md-4">
    <div class="input-group">
        <span class="input-group-addon">Date</span>
        <input type="date" name="roll_call_date" class="form-control" required>
    </div>
</div>

<div class="col-md-4">
    <div class="input-group">
        <span class="input-group-addon">Term</span>
        <select class="form-control" name="current_term">
            <?php
            $q = mysqli_query($connection,"SELECT current_term FROM current_season");
            $r = mysqli_fetch_assoc($q);
            echo "<option>{$r['current_term']}</option>";
            ?>
        </select>
    </div>
</div>

<div class="col-md-4">
    <div class="input-group">
        <span class="input-group-addon">Session</span>
        <select class="form-control" name="current_session">
            <?php
            $q = mysqli_query($connection,"SELECT current_session FROM current_season");
            $r = mysqli_fetch_assoc($q);
            echo "<option>{$r['current_session']}</option>";
            ?>
        </select>
    </div>
</div>
</div>

<br>

<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
    <th>S/N</th>
    <th>Reg No</th>
    <th>Name</th>
    <th>AM</th>
    <th>PM</th>
</tr>
</thead>
<tbody>

<?php while ($row = mysqli_fetch_assoc($run)) { ?>
<tr>
<td><?= $sn++ ?></td>
<td>
    <input type="text" name="attendance_reg_no[]" value="<?= $row['reg_number'] ?>" class="form-control" readonly>
</td>
<td>
    <input type="text" name="attendance_name[]" value="<?= $row['firstname']." ".$row['lastname']." ".$row['othername'] ?>" class="form-control" readonly>
</td>
<td>
    <select name="class_roll_call[]" class="form-control">
        <option>Present</option>
        <option>Absent</option>
    </select>
</td>
<td>
    <select name="class_roll_call_afternoon[]" class="form-control">
        <option>Present</option>
        <option>Absent</option>
    </select>
</td>
</tr>
<?php $i++; } ?>

</tbody>
</table>
</div>

<input type="hidden" name="total_num" value="<?= $i ?>">

<button type="submit" name="save_attendance_btn"
        onclick="this.form.roll_type.value='morning'"
        class="btn btn-primary btn-sm">
Save Morning Roll Call
</button>

<button type="submit" name="save_attendance_btn"
        onclick="this.form.roll_type.value='afternoon'"
        class="btn btn-success btn-sm">
Save Afternoon Roll Call
</button>

<input type="hidden" name="roll_type">

</form>

<?php
} else {
    echo "<p class='text-danger text-center'>No students found</p>";
}
}
?>

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