<?php
// Ensure form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Include database connection
    include('db_connection.php');

    // Initialize variables from the form
    $teacher_id = $_POST['teacher_id'];
    $attendance_date = $_POST['attendance_date'];
    $status = $_POST['status'];
    $notes = isset($_POST['notes']) ? $_POST['notes'] : '';

    // Prepare SQL statement to insert attendance record
    $query = "INSERT INTO attendance (teacher_id, attendance_date, status, notes) VALUES (?, ?, ?, ?)";
    $stmt = $conn->prepare($query);

    // Check for prepared statement errors
    if ($stmt === false) {
        die('Error in preparing statement: ' . $conn->error);
    }

    // Bind parameters and execute statement
    $stmt->bind_param("isss", $teacher_id, $attendance_date, $status, $notes);
    $stmt->execute();

    // Check for execution success
    if ($stmt->affected_rows > 0) {
        // Successful insertion
        header("Location: manage_attendance.php");
        exit();
    } else {
        // Error in execution
        echo "Error: " . $stmt->error;
    }

    // Close statement and connection
    $stmt->close();
    $conn->close();
} else {
    // Redirect back if accessed directly
    header("Location: manage_attendance.php");
    exit();
}
?>
