300, // 5 minutes 'display' => __('Every 5 Minutes (AIappOnsite)') ); return $schedules; } /** * Process a single webhook job */ function aiapp_process_webhook_job($args): void { $response_id = $args['response_id'] ?? ''; if (!$response_id) { error_log('[AIappOnsite] Invalid response_id in webhook job: ' . print_r($args, true)); return; } $job = aiapp_jobs_get($response_id); if (!$job || $job['status'] !== 'queued') { // Job already processed or doesn't exist return; } try { // Build the standardized webhook payload using the new format $payload_data = array( 'app_id' => $job['app_id'], 'response_id' => $response_id, 'form_data' => $job['payload']['data'] ?? array(), 'ai_response' => $job['payload']['ai_response'] ?? '', ); // Build the new standardized payload $payload = ai_app_onsite_build_webhook_payload($payload_data); // Dispatch to all active webhooks for this app $webhook_handler = new AI_App_Onsite_Webhook_Handler(); $webhook_handler->dispatch_sends((int)$job['app_id'], $payload); // Mark as sent aiapp_jobs_mark_sent($response_id); error_log("[AIappOnsite] Webhook successfully sent for response_id: {$response_id}"); } catch (Exception $e) { error_log("[AIappOnsite] Webhook job failed for response_id {$response_id}: " . $e->getMessage()); aiapp_jobs_mark_failed($response_id, $e->getMessage()); } } /** * Process overdue webhook jobs (fallback for low-traffic sites) */ function aiapp_drain_overdue_webhooks(): void { $current_time = time(); $overdue_jobs = aiapp_jobs_list_overdue($current_time); if (empty($overdue_jobs)) { return; } foreach ($overdue_jobs as $job) { do_action('aiapp_send_webhook', array('response_id' => $job['response_id'])); // Rate limit: process max 10 jobs per run to avoid timeouts static $processed = 0; if (++$processed >= 10) { break; } } } /** * Clean up cron jobs on plugin deactivation */ function aiapp_cleanup_webhook_cron(): void { wp_clear_scheduled_hook('aiapp_drain_webhook_queue'); // Clear any pending webhook jobs $pending_hooks = _get_cron_array(); foreach ($pending_hooks as $timestamp => $hooks) { if (isset($hooks['aiapp_send_webhook'])) { foreach ($hooks['aiapp_send_webhook'] as $hook) { wp_unschedule_event($timestamp, 'aiapp_send_webhook', $hook['args']); } } } } // Initialize when this file is loaded aiapp_init_webhook_cron();