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

// Fetch all orders
$query = "SELECT U.id, U.name, U.id_number, U.contact_no, W.prize FROM users U INNER JOIN winners W ON W.user_id = U.id WHERE W.prize != 'Try Again';";
$result = $conn->query($query);

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

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

    // Set column headers
    $fields = array('ID', 'Name', 'NIC Number', 'Contact Number', 'Prize');
    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['contact_no'], $row['prize']);
        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;

?>