isLoggedIn()) { die('Unauthorized'); } $db = Database::getInstance(); // Get selection ID from URL $selection_id = isset($_GET['id']) ? (int)$_GET['id'] : 0; if (!$selection_id) { die('Invalid selection ID'); } // Get selection details $stmt = $db->prepare(" SELECT s.*, p.project_id as project_code, p.title as project_title FROM selections s JOIN projects p ON s.project_id = p.id WHERE s.id = ? AND p.created_by = ? "); $stmt->bind_param('ii', $selection_id, $_SESSION['user_id']); $stmt->execute(); $selection = $stmt->get_result()->fetch_assoc(); if (!$selection) { die('Selection not found or access denied'); } // Get selection members $stmt = $db->prepare(" SELECT sm.panelist_id, pd.attribute_values FROM selection_members sm LEFT JOIN panel_data pd ON sm.panelist_id = pd.panelist_id WHERE sm.selection_id = ? ORDER BY sm.id ASC "); $stmt->bind_param('i', $selection_id); $stmt->execute(); $members_result = $stmt->get_result(); // Get all attributes $attributes = []; $attr_query = $db->query("SELECT id, name FROM attributes ORDER BY created_at ASC"); while ($attr = $attr_query->fetch_assoc()) { $attributes[$attr['id']] = $attr['name']; } // Set headers for CSV download header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="selection_' . $selection_id . '_' . 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']; foreach ($attributes as $attr_name) { $headers[] = $attr_name; } fputcsv($output, $headers); // Write data rows $counter = 1; while ($member = $members_result->fetch_assoc()) { $row = [$counter++, $member['panelist_id']]; $attribute_values = json_decode($member['attribute_values'], true); foreach ($attributes as $attr_id => $attr_name) { $row[] = isset($attribute_values[$attr_id]) ? $attribute_values[$attr_id] : ''; } fputcsv($output, $row); } fclose($output); exit;