<?php
session_start();
include '../../includes/db_connection.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: /school_management/public/index.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Record Attendance</title>
    <link rel="stylesheet" href="/school_management/public/css/style.css">
</head>
<body>
<div class="header">
    <h1>School Management System</h1>
    <div class="nav">
        <a href="/school_management/public/dashboard.php">Dashboard</a>
        <a href="/school_management/public/students/students_list.php">Students</a>
        <a href="/school_management/public/teachers/teachers_list.php">Teachers</a>
        <a href="/school_management/public/fees/fee_collection.php">Fees</a>
        <a href="/school_management/public/fees/monthly_fee_summary.php">Monthly Report</a>
        <a href="/school_management/public/exam_results/add_exam_result.php">Exams</a>
        <a href="/school_management/public/attendance/record_attendance.php">Attendance</a>
        <a href="/school_management/public/change_password.php">Change Password</a>
        <a href="/school_management/public/logout.php">Logout</a>
    </div>
</div>

<div class="content">

<?php
if ($_SESSION['role'] !== 'Admin' && $_SESSION['role'] !== 'Teacher') {
    echo "<p style='color:red;'>You do not have permission to view this page.</p>";
    echo "</div></body></html>";
    exit();
}

$error = '';
$message = '';
$students = [];

// Fetch students for dropdown based on class
if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['class_id']) && $_GET['class_id'] != '') {
    $class_id = $_GET['class_id'];
    $sql_students = "SELECT student_id, first_name, last_name FROM students WHERE class_id = ?";
    $stmt_students = $conn->prepare($sql_students);
    if ($stmt_students) {
        $stmt_students->bind_param("i", $class_id);
        $stmt_students->execute();
        $students_result = $stmt_students->get_result();
        while($row = $students_result->fetch_assoc()) {
            $students[] = $row;
        }
        $stmt_students->close();
    }
}

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['attendance_date'])) {
    $attendance_date = $_POST['attendance_date'];
    $attendance_records = $_POST['attendance'] ?? [];

    $conn->begin_transaction();
    $success = true;

    // Check if attendance already recorded for this date and class
    $check_sql = "SELECT COUNT(*) FROM attendance 
                  WHERE attendance_date = ? 
                  AND student_id IN (SELECT student_id FROM students WHERE class_id = ?)";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("si", $attendance_date, $_POST['class_id']);
    $check_stmt->execute();
    $check_stmt->bind_result($count);
    $check_stmt->fetch();
    $check_stmt->close();

    if ($count > 0) {
        $error = "Attendance for this class on this date has already been recorded.";
        $success = false;
    } else {
        $sql = "INSERT INTO attendance (student_id, attendance_date, status) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($sql);
        if ($stmt === false) {
            $error = "Error: " . $conn->error;
            $success = false;
        } else {
            foreach ($attendance_records as $student_id => $status) {
                $stmt->bind_param("iss", $student_id, $attendance_date, $status);
                if (!$stmt->execute()) {
                    $error = "Error: " . $stmt->error;
                    $success = false;
                    break;
                }
            }
            $stmt->close();
        }
    }

    if ($success) {
        $conn->commit();
        $message = "Attendance recorded successfully!";
    } else {
        $conn->rollback();
    }
}

// Fetch all classes for the dropdown
$classes_sql = "SELECT class_id, class_name FROM classes ORDER BY class_name";
$classes_result = $conn->query($classes_sql);

?>

<div class="container">
    <h2>Record Attendance</h2>

    <?php if ($message): ?>
        <p style='color:green;'><?php echo $message; ?></p>
    <?php endif; ?>
    <?php if ($error): ?>
        <p style='color:red;'><?php echo $error; ?></p>
    <?php endif; ?>

    <form action="" method="GET">
        <label for="class_id">Select Class:</label><br>
        <select id="class_id" name="class_id" onchange="this.form.submit()" required>
            <option value="">--Select a Class--</option>
            <?php
            if ($classes_result->num_rows > 0) {
                while($row = $classes_result->fetch_assoc()) {
                    $selected = (isset($_GET['class_id']) && $_GET['class_id'] == $row['class_id']) ? 'selected' : '';
                    echo "<option value='" . htmlspecialchars($row['class_id']) . "' " . $selected . ">" . htmlspecialchars($row['class_name']) . "</option>";
                }
            }
            ?>
        </select>
    </form>
    
    <br>

    <?php if (!empty($students)): ?>
        <form action="" method="POST">
            <input type="hidden" name="class_id" value="<?php echo htmlspecialchars($_GET['class_id']); ?>">
            <label for="attendance_date">Attendance Date:</label><br>
            <input type="date" id="attendance_date" name="attendance_date" required><br><br>

            <table class="attendance-table" style="width:100%; border-collapse: collapse;">
                <thead>
                    <tr>
                        <th style="padding: 8px; border: 1px solid #ccc; text-align: left;">Student Name</th>
                        <th style="padding: 8px; border: 1px solid #ccc; text-align: center;">Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($students as $student): ?>
                        <tr>
                            <td style="padding: 8px; border: 1px solid #ccc;"><?php echo htmlspecialchars($student['first_name'] . " " . $student['last_name']); ?></td>
                            <td style="padding: 8px; border: 1px solid #ccc; text-align: center;">
                                <input type="radio" name="attendance[<?php echo htmlspecialchars($student['student_id']); ?>]" value="Present" required> Present
                                <input type="radio" name="attendance[<?php echo htmlspecialchars($student['student_id']); ?>]" value="Absent"> Absent
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <br>
            <input type="submit" value="Record Attendance">
        </form>
    <?php elseif (isset($_GET['class_id'])): ?>
        <p>No students found in this class.</p>
    <?php endif; ?>
</div>

<div class="footer">
    <p>&copy; <?php echo date("Y"); ?> School Management System. All Rights Reserved.</p>
</div>
</div>
</body>
</html>