<?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>Attendance Report</title>
    <link rel="stylesheet" href="/school_management/public/css/style.css">
    <style>
        .report-table {
            width: 100%;
            border-collapse: collapse;
        }
        .report-table th, .report-table td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: left;
        }
        .report-table th {
            background-color: #f2f2f2;
        }

        /* Styles for printing */
        @media print {
            body {
                margin: 0;
                padding: 0;
            }
            .header, .nav, .footer, .print-btn, form {
                display: none;
            }
            .container {
                width: 100%;
                margin: 0;
                padding: 0;
            }
            .report-table {
                font-size: 10pt;
            }
            h2 {
                text-align: center;
                margin-top: 20px;
                margin-bottom: 20px;
            }
            @page {
                size: A4 portrait;
                margin: 20mm;
            }
        }
    </style>
</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();
}

$classes_sql = "SELECT class_id, class_name FROM classes ORDER BY class_name";
$classes_result = $conn->query($classes_sql);

$sql = "SELECT 
            a.attendance_id,
            s.first_name, 
            s.last_name,
            c.class_name,
            a.attendance_date,
            a.status
        FROM attendance a
        LEFT JOIN students s ON a.student_id = s.student_id
        LEFT JOIN classes c ON s.class_id = c.class_id
        WHERE 1=1";

$params = [];
$types = "";

if (isset($_GET['class_id']) && $_GET['class_id'] != '') {
    $sql .= " AND s.class_id = ?";
    $params[] = $_GET['class_id'];
    $types .= "i";
}

if (isset($_GET['attendance_date']) && $_GET['attendance_date'] != '') {
    $sql .= " AND a.attendance_date = ?";
    $params[] = $_GET['attendance_date'];
    $types .= "s";
}

$sql .= " ORDER BY a.attendance_date DESC, s.first_name";

$stmt = $conn->prepare($sql);
if ($stmt === false) {
    die("Error preparing statement: " . $conn->error);
}

if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();

?>

<div class="container">
    <h2>Attendance Report</h2>
    <p><a href="record_attendance.php">Record New Attendance</a></p>

    <form action="" method="GET">
        <label for="class_id">Filter by Class:</label>
        <select id="class_id" name="class_id">
            <option value="">All Classes</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>
        <label for="attendance_date">Date:</label>
        <input type="date" id="attendance_date" name="attendance_date" value="<?php echo htmlspecialchars($_GET['attendance_date'] ?? ''); ?>">
        <button type="submit" class="btn">Filter</button>
        <button type="button" onclick="window.print()" class="print-btn">Print Report</button>
    </form>
    <br>

    <?php if ($result->num_rows > 0): ?>
        <table class="report-table">
            <thead>
                <tr>
                    <th>Student Name</th>
                    <th>Class</th>
                    <th>Date</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php while($row = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?></td>
                        <td><?php echo htmlspecialchars($row['class_name'] ?? 'N/A'); ?></td>
                        <td><?php echo htmlspecialchars($row['attendance_date']); ?></td>
                        <td><?php echo htmlspecialchars($row['status']); ?></td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    <?php else: ?>
        <p>No attendance records found for the selected filter.</p>
    <?php endif; ?>
</div>

<?php
$conn->close();
?>

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