<?php
session_start();
require_once 'config.php'; // Ensure this path is correct

// Function to check user role and redirect if unauthorized
function check_role_access($required_role_code) {
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php");
        exit;
    }

    if ($_SESSION["role"] !== $required_role_code) {
        // Redirect to a more appropriate page or show an error
        header("location: admin_dashboard.php"); // Assuming admin_dashboard is a safe fallback
        exit;
    }
}

// !! CRITICAL: Call the check for Admin role !!
check_role_access(ROLE_ADMIN);

$current_user_school_id = $_SESSION["school_id"];

// Initialize school variables
$school_name = "School Name Not Found";
$school_logo_path = "images/default_school_logo.png";

// Initialize students array
$students = [];

// Establish database connection
$conn = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Fetch School Name and Logo
$sql_school = "SELECT school_name, logo FROM schools WHERE school_id = ?";
if ($stmt_school = $conn->prepare($sql_school)) {
    $stmt_school->bind_param("i", $current_user_school_id);
    if ($stmt_school->execute()) {
        $stmt_school->bind_result($school_name_db, $school_logo_db);
        if ($stmt_school->fetch()) {
            $school_name = htmlspecialchars($school_name_db);
            $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
        }
    }
    $stmt_school->close();
}

// Fetch all students for the current school
$sql_students = "SELECT ADM, username, email, phone_number, status, class, stream, created_at FROM students WHERE school_id = ? AND role = ?";
$student_role_code = ROLE_STUDENT;

if ($stmt_students = $conn->prepare($sql_students)) {
    $stmt_students->bind_param("ii", $current_user_school_id, $student_role_code);
    if ($stmt_students->execute()) {
        $result_students = $stmt_students->get_result();
        while ($row = $result_students->fetch_assoc()) {
            $students[] = $row;
        }
    }
    $stmt_students->close();
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Print Students - <?php echo $school_name; ?></title>
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            color: #333;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .header img {
            max-height: 80px;
            margin-bottom: 10px;
        }
        .header h1 {
            font-size: 24px;
            margin: 0;
        }
        .header p {
            font-size: 14px;
            margin: 5px 0;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
            font-size: 12px;
        }
        th {
            background-color: #f2f2f2;
        }
        .footer {
            text-align: center;
            margin-top: 40px;
            font-size: 10px;
            color: #777;
        }
        @media print {
            body {
                margin: 0;
                padding: 0;
            }
            .header {
                margin-bottom: 20px;
            }
            table {
                margin-top: 15px;
            }
            /* Hide elements not needed for print */
            .no-print {
                display: none;
            }
        }
    </style>
</head>
<body onload="window.print()">
    <div class="header">
        <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo">
        <h1><?php echo $school_name; ?></h1>
        <p>All Students List</p>
        <p>Date: <?php echo date('Y-m-d'); ?></p>
    </div>

    <?php if (empty($students)): ?>
        <p style="text-align: center;">No students found to print.</p>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>ADM</th>
                    <th>Username</th>
                    <th>Email</th>
                    <th>Phone Number</th>
                    <th>Class</th>
                    <th>Stream</th>
                    <th>Status</th>
                    <th>Registered On</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($students as $student): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($student['ADM']); ?></td>
                        <td><?php echo htmlspecialchars($student['username']); ?></td>
                        <td><?php echo htmlspecialchars($student['email'] ?? 'N/A'); ?></td>
                        <td><?php echo htmlspecialchars($student['phone_number'] ?? 'N/A'); ?></td>
                        <td><?php echo htmlspecialchars($student['class'] ?? 'N/A'); ?></td>
                        <td><?php echo htmlspecialchars($student['stream'] ?? 'N/A'); ?></td>
                        <td><?php echo htmlspecialchars($student['status']); ?></td>
                        <td><?php echo date('Y-m-d', strtotime($student['created_at'])); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>

    <div class="footer">
        <p>&copy; <?php echo date('Y'); ?> Divine Reports. All rights reserved.</p>
    </div>
</body>
</html>
