<?php
// Connect to MySQL
include_once './dbconn.php';

// Fetch data from database
$sql = "SELECT * FROM `web_app_enrollee_data`";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // Set headers to force download
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export.csv"');
    header('Pragma: no-cache');
    header('Expires: 0');

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

    // Initialize serial number
    $serial = 1;

    // Output CSV column headers with Serial Number as the first column
    fputcsv($output, array('Serial Number', 'ID', 'ENROLLMENT SERIAL NO', 'COMPANY NAME', 'SURNAME','FIRST NAME','MIDDLE NAME','GENDER','PHONE NUMBER','EMAIL ADDRESS','DATE OF BIRTH','PLAN GROUP','PLAN TYPE', 'HMO ID','ADDRESS','CITY','STATE','LGA','EMPLOYEE ID','HOSPITAL','GENOTYPE','BLOOD GROUP','ALLERGIES','SURGICAL HISTORY','PASSPORT LINK','CREATED'));

    // Output each row of the data
    while ($row = mysqli_fetch_assoc($result)) {
        // Create a new array to reorder the data
        $rowData = array('Serial Number' => $serial++);
        // Merge the original row data into the new array
        $rowData = array_merge($rowData, $row);
        // Output the row data to CSV
        fputcsv($output, $rowData);
    }

    // Close the file pointer
    
    fclose($output);
    // Close connection
    mysqli_close($conn);
    
    // Redirect after export
    header("Location: index.php?exported");
    exit();
} else {
    echo "No data found";
}

// Close connection
mysqli_close($conn);
?>
