<?php

include('includes/session1.php');

error_reporting();

include('includes/dbconnection.php');

require_once __DIR__ . '/includes/session_term_helper.php';

include('includes/flash.php');



if (!isset($_SESSION['sid'])) {

    header('location:logoutteacher.php');

    exit();

}



$class = $_GET['class'];

$section = $_GET['section'];

$date = $_GET['date'] ?? date('Y-m-d');



// Fetch all students in the class

$query = "SELECT id, studentName FROM students WHERE class = '$class' AND section = '$section' AND status < 3";

$students_result = mysqli_query($con, $query);

$students = mysqli_fetch_all($students_result, MYSQLI_ASSOC);



// Fetch active session and term via helper

$stResult = resolveCurrentSessionTerm($con);

$currentSessionId   = $stResult['session_id'];

$currentSessionName = $stResult['session_name'];

$currentTermId      = $stResult['term_id'];

$currentTermName    = $stResult['term_name'];



// Fetch attendance for the day

$attendance_query = "

    SELECT student_id, status

    FROM attendance

    WHERE class = '$class' AND section = '$section' AND date = '$date' AND status IS NOT NULL";

$attendance_result = mysqli_query($con, $attendance_query);



$attendance_data = [];

while ($row = mysqli_fetch_assoc($attendance_result)) {

    $attendance_data[$row['student_id']] = trim($row['status']);

}



if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $query = "

        INSERT INTO attendance (student_id, class, section, term_id, session_id, date, status)

        VALUES (?, ?, ?, ?, ?, ?, ?)

        ON DUPLICATE KEY UPDATE status = ?";

    $stmt = mysqli_prepare($con, $query);



    foreach ($_POST['attendance'] as $student_id => $status) {

        $status = trim($status); // Either "Present" or "Absent"

        mysqli_stmt_bind_param($stmt, 'issiisss', $student_id, $class, $section, $currentTermId, $currentSessionId, $date, $status, $status);

        mysqli_stmt_execute($stmt);

    }



    mysqli_stmt_close($stmt);

    flash_alert('Attendance Marked successfully!');

        header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'javascript:history.back()')); exit;

    exit();

}

?>



<!DOCTYPE html>

<html>

<?php @include("includes/head.php"); ?>



<body class="hold-transition sidebar-mini layout-fixed">

    <div class="wrapper">

        <?php @include("includes/headert.php"); ?>

        <?php @include("includes/sidebart.php"); ?>



        <div class="content-wrapper">

<section class="content-header premium-header">

    <div class="container-fluid">

        <div class="header-glass-card">

            <div class="row align-items-center">

                <div class="col-md-8">

                    <div class="title-section">

                        <div class="icon-box bg-primary-gradient shadow-sm">

                            <i class="fas fa-users"></i>

                        </div>

                        <div>

                            <h1 class="premium-title text-primary">

                                Attendance Management

                                <span class="premium-subtitle text-secondary">Monitor Attendance</span>

                            </h1>
                                        <div class="mt-1">
                                            <?php if ($currentSessionName): ?>
                                                <span class="badge badge-primary mr-1">
                                                    <i class="fas fa-calendar-alt"></i> <?= htmlspecialchars($currentSessionName) ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($currentTermName): ?>
                                                <span class="badge badge-success">
                                                    <i class="fas fa-bookmark"></i> <?= htmlspecialchars($currentTermName) ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="badge badge-warning">
                                                    <i class="fas fa-exclamation-triangle"></i> No active term
                                                </span>
                                            <?php endif; ?>
                                        </div>

                        </div>

                    </div>

                </div>

                <div class="col-md-4">

                    <nav aria-label="breadcrumb">

                        <ol class="breadcrumb premium-breadcrumb">

                            <li class="breadcrumb-item"><a href="teacher_dashboard.php" class="text-primary">Home</a></li>

                            <li class="breadcrumb-item active" aria-current="page">Mark Attendance</li>

                        </ol>

                    </nav>

                </div>

            </div>

        </div>

    </div>

</section> 

            <section class="content">

                <div class="card card-primary">

                    <div class="card-header">

                        <h5 class="card-title font-weight-bold">

                            <i class="fas fa-clipboard-list"></i> Attendance for <?php echo $class; ?> - <?php echo $section; ?> Date: <?php echo $date; ?>

                        </h5>

                    </div>

                    <div class="card-body">

                        <form method="POST">

                            <table id="example1" class="table table-bordered table-hover">

                                <thead>

                                    <tr>

                                        <th>#</th>

                                        <th>Student Name</th>

                                        <th>Present</th>

                                        <th>Absent</th>

                                    </tr>

                                </thead>

                                <tbody>

                                    <?php foreach ($students as $index => $student): ?>

                                        <tr>

                                            <td><?php echo $index + 1; ?></td>

                                            <td><?php echo $student['studentName']; ?></td>

                                            <td>

                                                <input type="checkbox"

                                                    class="attendance-checkbox"

                                                    data-student-id="<?php echo $student['id']; ?>"

                                                    data-type="Present"

                                                    name="attendance[<?php echo $student['id']; ?>]"

                                                    value="Present"

                                                    <?php echo isset($attendance_data[$student['id']]) && strtolower($attendance_data[$student['id']]) == 'present' ? 'checked' : ''; ?>>

                                                Present

                                            </td>

                                            <td>

                                                <input type="checkbox"

                                                    class="attendance-checkbox"

                                                    data-student-id="<?php echo $student['id']; ?>"

                                                    data-type="Absent"

                                                    name="attendance[<?php echo $student['id']; ?>]"

                                                    value="Absent"

                                                    <?php echo isset($attendance_data[$student['id']]) && strtolower($attendance_data[$student['id']]) == 'absent' ? 'checked' : ''; ?>>

                                                Absent

                                            </td>

                                        </tr>

                                    <?php endforeach; ?>

                                </tbody>

                            </table>

                            <div class="form-group text-center">

                                <button type="submit" class="btn btn-primary">

                                    <i class="fas fa-check-circle"></i> Submit Attendance

                                </button>

                            </div>

                            <div class="form-group text-center">

                                <small class="text-danger" style="font-size: 1rem;">

                                    <i class="fas fa-info-circle text-primary"></i>

                                    Note: Attendance marked is saved per page

                                </small>

                            </div>

                        </form>

                    </div>

                </div>

            </section>

        </div>



        <?php @include("includes/footer.php"); ?>

        <?php @include("includes/foot.php"); ?>

    </div>



    <script>

        document.querySelectorAll('.attendance-checkbox').forEach(function(checkbox) {

            checkbox.addEventListener('change', function() {

                const studentId = this.getAttribute('data-student-id');

                document.querySelectorAll('.attendance-checkbox').forEach(function(item) {

                    if (item.getAttribute('data-student-id') === studentId && item !== checkbox) {

                        item.checked = false;

                    }

                });

            });

        });

    </script>

</body>



</html>