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

// Define role constants (ensure these match your config.php or are globally defined)
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 2);

// Only allow access if logged in as an Admin
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || $_SESSION["role"] !== ROLE_ADMIN || !isset($_SESSION["school_id"])) {
    // Redirect to login or show an unauthorized message
    header("location: login.php");
    exit;
}

$current_user_school_id = $_SESSION["school_id"];

if (isset($conn) && $conn instanceof mysqli) {
    // Fetch all staff members for the current school
    $staff_members = [];
    $sql_staff = "SELECT staff_id, username, email, phone_number, photo, work, department, status, created_at FROM staff WHERE school_id = ?";
    if ($stmt = $conn->prepare($sql_staff)) {
        $stmt->bind_param("i", $current_user_school_id);
        if ($stmt->execute()) {
            $result = $stmt->get_result();
            while ($row = $result->fetch_assoc()) {
                $staff_members[] = $row;
            }
        } else {
            error_log("Execute failed for staff export query: " . $stmt->error);
            // In a real application, you might want to redirect with an error message
            die("Error fetching staff data for export.");
        }
        $stmt->close();
    } else {
        error_log("Prepare failed for staff export query: " . $conn->error);
        die("Database error preparing for export.");
    }
    $conn->close();

    // Set headers for CSV download
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="staff_list_' . date('Y-m-d') . '.csv"');
    header('Pragma: no-cache');
    header('Expires: 0');

    // Create a file pointer connected to the output stream
    $output = fopen('php://output', 'w');

    // Output the CSV headers (column names)
    if (!empty($staff_members)) {
        fputcsv($output, array_keys($staff_members[0]));
    } else {
        // If no staff members, just put headers
        fputcsv($output, ['staff_id', 'username', 'email', 'phone_number', 'photo', 'work', 'department', 'status', 'created_at']);
    }

    // Output all staff members
    foreach ($staff_members as $row) {
        fputcsv($output, $row);
    }

    fclose($output);
    exit;

} else {
    error_log("Database connection \$conn not available in export_staff_csv.php");
    die("Database connection error. Cannot export data.");
}
?>
