send_to_api($detection, $request_uri, $sponsored_text_id); } private function send_to_api($detection, $request_uri, $sponsored_text_id = null) { $api_key = get_option('aimiles_api_key', ''); if (empty($api_key)) { return null; } $body = [ 'api_key' => $api_key, 'agent_name' => $detection['agent']['name'] ?? 'Unknown', 'agent_company' => $detection['agent']['company'] ?? 'Unknown', 'request_uri' => $request_uri, 'site_url' => home_url(), 'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '', ]; if ($sponsored_text_id !== null) { $body['sponsored_text_id'] = $sponsored_text_id; } wp_remote_post('https://app.aimiles.ai/api/visits', [ 'body' => wp_json_encode($body), 'headers' => ['Content-Type' => 'application/json'], 'timeout' => 0.01, 'blocking' => false, ]); return null; } public function fetch_sponsored_texts() { $api_key = get_option('aimiles_api_key', ''); if (empty($api_key)) { return null; } $response = wp_remote_get('https://app.aimiles.ai/api/sponsored_texts?key=' . urlencode($api_key), [ 'timeout' => 5, ]); if (is_wp_error($response)) { return null; } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); if (empty($data) || !is_array($data)) { return null; } // API returns a single object, not an array of objects if (isset($data['ad_text'])) { return $data; } return $data[0] ?? null; } }