prepare(" SELECT id, client_url, status, clicked_at FROM survey_urls WHERE project_id = ? AND unique_identifier = ? LIMIT 1 "); $stmt->execute([$project_id, $unique_id]); $result = $stmt->fetch(PDO::FETCH_ASSOC); if (!$result) { header('HTTP/1.0 404 Not Found'); echo "Survey URL not found or expired"; exit; } // Block access if already timed out if ($result['status'] === 'timeout') { error_log("Survey URL blocked (timed out): Project=$project_id, UniqueID=$unique_id"); $current_project_id = $project_id; include __DIR__ . '/../r/pages/timeout.php'; exit; } // Real-time timeout check: if clicked > 2 hours ago and still 'clicked', mark as timeout and block if ($result['status'] === 'clicked' && $result['clicked_at']) { $clickedTime = strtotime($result['clicked_at']); if ((time() - $clickedTime) > 7200) { // 2 hours = 7200 seconds $stmt = $pdo->prepare(" UPDATE survey_urls SET status = 'timeout', actual_loi_seconds = TIMESTAMPDIFF(SECOND, clicked_at, NOW()) WHERE id = ? "); $stmt->execute([$result['id']]); error_log("Survey URL timed out on re-access: Project=$project_id, UniqueID=$unique_id"); $current_project_id = $project_id; include __DIR__ . '/../r/pages/timeout.php'; exit; } } // Mark as clicked if still available or sent (sent = dispatched by mailer but not yet clicked) if (in_array($result['status'], ['available', 'sent'])) { $respondentIp = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? null; // Take first IP if multiple (X-Forwarded-For can have comma-separated list) if ($respondentIp && strpos($respondentIp, ',') !== false) { $respondentIp = trim(explode(',', $respondentIp)[0]); } $stmt = $pdo->prepare(" UPDATE survey_urls SET status = 'clicked', clicked_at = NOW(), respondent_ip = ? WHERE id = ? "); $stmt->execute([$respondentIp, $result['id']]); } // Log the click error_log("Survey URL clicked: Project=$project_id, UniqueID=$unique_id, PrevStatus={$result['status']}"); // Redirect to client survey URL header('Location: ' . $result['client_url']); exit; } catch (Exception $e) { error_log("Survey proxy error: " . $e->getMessage() . " | Encoded: " . $encoded); header('HTTP/1.0 500 Internal Server Error'); echo "Error loading survey. Please contact support."; exit; } ?>