isLoggedIn()) { die('Unauthorized access'); } $db = Database::getInstance(); // Get all attributes for headers $attributes = $db->query(" SELECT id, name FROM attributes ORDER BY created_at ASC "); // Set headers for CSV download header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="panel_data_' . date('Y-m-d') . '.csv"'); // Create output stream $output = fopen('php://output', 'w'); // Add BOM for Excel UTF-8 compatibility fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); // Write headers $headers = ['Panelist ID']; while ($attr = $attributes->fetch_assoc()) { $headers[] = $attr['name']; } fputcsv($output, $headers); // Get all panel data $panel_query = $db->query(" SELECT * FROM panel_data ORDER BY created_at ASC "); // Write data rows while ($panel = $panel_query->fetch_assoc()) { $row = [str_pad($panel['panelist_id'], 6, '0', STR_PAD_LEFT)]; $attributes->data_seek(0); // Reset attributes pointer $values = json_decode($panel['attribute_values'], true); while ($attr = $attributes->fetch_assoc()) { $value = $values[$attr['id']] ?? '-'; // Handle array values for multiple-choice attributes if (is_array($value)) { $value = implode(', ', $value); } $row[] = $value; } fputcsv($output, $row); } fclose($output); exit;