<?php
// Connect to MySQL
$conn = mysqli_connect("localhost", "vinkblgn_regportal", "Victor@007", "vinkblgn_regportal");

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Fetch data from database for the selected company
$company_name = $_POST["company_name"];
$sql = "SELECT * FROM `web_app_enrollee_data` WHERE `company_name` = '$company_name'";
$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_'.$company_name.'.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'));

    // 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);
} else {
    echo "No data found for $company_name";
}

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