prepare(" SELECT ps.*, p.project_id AS project_code, p.project_name FROM project_selections ps JOIN projects p ON ps.project_id = p.id WHERE ps.id = ? AND ps.client_id = ? "); $stmt->execute([$selection_id, $_SESSION['client_id']]); $selection = $stmt->fetch(); if (!$selection) { header('Location: projects-list.php'); exit; } // Build query $where = "assigned_to_selection_id = ?"; $params = [$selection_id]; $valid_statuses = ['assigned','sent','clicked','complete','partial','earlyscreenout','latescreenout','quotafull','timeout']; if ($status_filter !== 'all' && in_array($status_filter, $valid_statuses)) { $where .= " AND status = ?"; $params[] = $status_filter; } $stmt = $pdo->prepare(" SELECT unique_identifier, client_url, rr_proxy_url, status, is_sent, sent_to_user_id, sent_at, clicked_at, created_at FROM survey_urls WHERE $where ORDER BY id ASC "); $stmt->execute($params); $urls = $stmt->fetchAll(PDO::FETCH_ASSOC); // Generate filename $safe_name = preg_replace('/[^a-zA-Z0-9]/', '_', $selection['selection_name'] ?? 'selection'); $filename = $selection['project_code'] . '_' . $safe_name . '_' . $status_filter . '_' . date('Ymd') . '.csv'; // Output CSV header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Pragma: no-cache'); header('Expires: 0'); $output = fopen('php://output', 'w'); // Header row fputcsv($output, [ 'Unique ID', 'Client URL', 'Proxy URL', 'Status', 'Sent', 'Sent To User ID', 'Sent At', 'Clicked At', 'Created At' ]); foreach ($urls as $url) { fputcsv($output, [ $url['unique_identifier'], $url['client_url'], $url['rr_proxy_url'], $url['status'], $url['is_sent'] ? 'Yes' : 'No', $url['sent_to_user_id'] ?? '', $url['sent_at'] ?? '', $url['clicked_at'] ?? '', $url['created_at'] ]); } fclose($output); exit;