<?php
// export_attendance.php — exports class attendance as a CSV download
if (isset($_POST['export_attendance_btn'])) {
    $class   = inject_checker($connection, $_POST['attendance_class']   ?? '');
    $date    = inject_checker($connection, $_POST['roll_call_date']      ?? '');
    $term    = inject_checker($connection, $_POST['current_term']        ?? '');
    $session = inject_checker($connection, $_POST['current_session']     ?? '');

    if (empty($class) || empty($date)) {
        $_SESSION['msg']  = "Class and Date are required to export attendance.";
        $_SESSION['type'] = "danger";
        header("Location: class_attendance");
        exit();
    }

    $stmt = $connection->prepare(
        "SELECT reg_number, name, class, roll_call
         FROM student_attendance
         WHERE class = ? AND date = ? AND term = ? AND session = ?
         ORDER BY name ASC"
    );
    $stmt->bind_param("ssss", $class, $date, $term, $session);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // Sanitise class/date for the filename
        $safe_class = preg_replace('/[^A-Za-z0-9_\-]/', '_', $class);
        $safe_date  = preg_replace('/[^A-Za-z0-9_\-]/', '_', $date);

        ob_clean();
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="Attendance_' . $safe_class . '_' . $safe_date . '.csv"');
        header('Pragma: no-cache');
        header('Expires: 0');

        $output = fopen("php://output", "w");
        // UTF-8 BOM so Excel opens it correctly
        fputs($output, chr(0xEF) . chr(0xBB) . chr(0xBF));
        fputcsv($output, ['Registration Number', 'Name', 'Class', 'Attendance Status (Present/Absent)']);

        while ($row = $result->fetch_assoc()) {
            fputcsv($output, $row);
        }
        fclose($output);
        exit();
    } else {
        $_SESSION['msg']  = "No attendance records found for <strong>{$class}</strong> on <strong>{$date}</strong>.";
        $_SESSION['type'] = "warning";
        header("Location: class_attendance");
        exit();
    }
}
?>
