<?php
// get_stn_atted.php

error_reporting(E_ALL);
ini_set('display_errors', 1); // Enable error reporting during development

// Include database connection
include("includes/db.php");

// Check if POST request contains 'classId' and 'exam_type'
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['classId']) && isset($_POST['exam_type'])) {
    $classId = $_POST['classId'];
    $examType = $_POST['exam_type'];

    // Prepare query to fetch students based on class ID
    $fetchStudentsQuery = "SELECT symbol_no, student_id, name FROM students WHERE Class_id = ? ORDER BY symbol_no";
    $stmt = $conn->prepare($fetchStudentsQuery);

    if ($stmt === false) {
        echo json_encode(["status" => "error", "message" => "Database error. Please try again."]);
        exit();
    }

    // Bind classId to the prepared statement
    $stmt->bind_param('i', $classId);
    $stmt->execute();
    $result = $stmt->get_result();

    // Check if there are students in the class
    if ($result->num_rows > 0) {
        // Display input fields for each student
        while ($row = $result->fetch_assoc()) {
            $studentId = htmlspecialchars($row['student_id']); // Escape output
            $name = htmlspecialchars($row['name']); // Escape output
            $symbolNo = htmlspecialchars($row['symbol_no']); // Escape output

            // Fetch previous attendance for the student if any
            $fetchAttendanceQuery = "SELECT atten_day FROM attendance WHERE std_id = ? AND exam_type = ?";
            $attendanceStmt = $conn->prepare($fetchAttendanceQuery);
            $attendanceStmt->bind_param('ii', $studentId, $examType);
            $attendanceStmt->execute();
            $attendanceResult = $attendanceStmt->get_result();

            $previousAttenDay = '';
            if ($attendanceResult->num_rows > 0) {
                $attendanceRow = $attendanceResult->fetch_assoc();
                $previousAttenDay = $attendanceRow['atten_day']; // Get previous attendance day value
            }

            // Display the attendance field with the previous value if it exists
            echo '<div class="form-group col-md-8">';
            echo '<label for="atten_day_' . $studentId . '">' . $name . '<span style="color:red;"> [' . $symbolNo . ']</span></label>';
            echo '<input type="number" id="atten_day_' . $studentId . '" name="attendance[' . $studentId . '][atten_day]" class="form-control" value="' . $previousAttenDay . '" required>';
            echo '</div>';

            // Close the attendance prepared statement
            $attendanceStmt->close();
        }

        // Add a reset button to clear all fields
        echo '<div class="col-md-12">';
        echo '<button type="button" class="btn btn-danger" id="resetBtn">Reset All Fields</button>';
        echo '</div>';
    } else {
        echo '<p>No students found for this class.</p>';
    }

    // Close the student query prepared statement
    $stmt->close();
} else {
    // Invalid request, return error response
    echo json_encode(["status" => "error", "message" => "Invalid request!"]);
}

// Close the database connection
$conn->close();
?>

<script>
    // Reset button functionality to clear all fields
    document.getElementById("resetBtn").addEventListener("click", function() {
        const inputs = document.querySelectorAll("input[type='number']");
        inputs.forEach(input => input.value = ''); // Clear the value of all number inputs
    });
</script>
