<?php
// Database connection details
require('../dbconfig/dbconfig.php'); 

// Fetch all orders
$query = "SELECT id, name, id_number, CAST(dob AS DATE) AS dob, contact_no, province, district FROM users";
$result = $conn->query($query);

if ($result->num_rows > 0) {
    $delimiter = ",";
    $filename = "UserDetails_" . date('Y-m-d') . ".csv";

    // Create a file pointer
    $f = fopen('php://memory', 'w');

    // Set column headers
    $fields = array('ID', 'Name', 'NIC Number', 'DOB', 'Contact Number', 'Province', 'District');
    fputcsv($f, $fields, $delimiter);

    // Output each row of the data, format line as CSV and write to file pointer
    while ($row = $result->fetch_assoc()) {
        $lineData = array($row['id'], $row['name'], $row['id_number'], $row['dob'], $row['contact_no'], $row['province'], $row['district']);
        fputcsv($f, $lineData, $delimiter);
    }

    // Move back to beginning of file
    fseek($f, 0);

    // Set headers to download file rather than displayed
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');

    // Output all remaining data on a file pointer
    fpassthru($f);
}
exit;

?>