register_site_if_needed(); if (!wp_next_scheduled('airf_nightly_analysis_event')) { wp_schedule_event(time() + HOUR_IN_SECONDS, 'daily', 'airf_nightly_analysis_event'); } if (!wp_next_scheduled('airf_weekly_digest_event')) { wp_schedule_event(time() + DAY_IN_SECONDS, 'weekly', 'airf_weekly_digest_event'); } $self->ensure_auto_analysis_schedule(); } public static function deactivate(): void { wp_clear_scheduled_hook('airf_nightly_analysis_event'); wp_clear_scheduled_hook('airf_weekly_digest_event'); wp_clear_scheduled_hook('airf_run_queued_analysis'); wp_clear_scheduled_hook('airf_timeout_reconcile_event'); wp_clear_scheduled_hook('airf_auto_analysis_check'); wp_clear_scheduled_hook('airf_retry_analysis_event'); delete_transient('airf_timeout_reconcile_lock'); delete_transient('airf_loopback_token'); delete_transient('airf_loopback_kick_lock'); delete_transient('airf_rotation_hint'); } private function __construct() { $this->api_client = new AIRF_Api_Client(AIRF_API_BASE_URL); add_action('init', [$this, 'ensure_auto_analysis_schedule']); add_action('admin_init', [$this, 'ensure_registered']); add_action('admin_menu', [$this, 'register_admin_page']); add_action('admin_notices', [$this, 'render_admin_notice']); add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']); add_filter('cron_schedules', [$this, 'register_cron_schedules']); add_action('admin_post_airf_force_plan_sync', [$this, 'handle_force_plan_sync']); add_action('admin_post_airf_run_analysis_now', [$this, 'handle_run_analysis_now']); add_action('admin_post_airf_update_settings', [$this, 'handle_update_settings']); add_action('admin_post_airf_update_countries', [$this, 'handle_update_countries']); add_action('wp_ajax_airf_dispatch_analysis', [$this, 'ajax_dispatch_analysis']); add_action('wp_ajax_airf_poll_job_status', [$this, 'ajax_poll_job_status']); add_action('wp_ajax_airf_send_verification_code', [$this, 'ajax_send_verification_code']); add_action('wp_ajax_airf_verify_code', [$this, 'ajax_verify_code']); // Loopback worker endpoint — reachable without a logged-in cookie because the // dispatcher fires a non-blocking HTTP request from PHP itself. Authenticated // by a single-use random token kept in a 120 s transient. add_action('wp_ajax_airf_run_worker_loopback', [$this, 'ajax_run_worker_loopback']); add_action('wp_ajax_nopriv_airf_run_worker_loopback', [$this, 'ajax_run_worker_loopback']); add_action('airf_run_queued_analysis', [$this, 'run_queued_analysis']); add_action('airf_timeout_reconcile_event', [$this, 'run_timeout_reconcile']); add_action('woocommerce_product_options_inventory_product_data', [$this, 'render_supplier_lead_days_field']); add_action('woocommerce_admin_process_product_object', [$this, 'save_supplier_lead_days_field']); add_action('airf_nightly_analysis_event', [$this, 'run_nightly_analysis']); add_action('airf_weekly_digest_event', [$this, 'send_weekly_digest']); add_action('airf_auto_analysis_check', [$this, 'run_auto_analysis_check']); add_action('airf_retry_analysis_event', [$this, 'run_retry_analysis']); } public function ensure_registered(): void { $this->maybe_run_timeout_reconcile_fallback(); $this->maybe_recover_stuck_running_job(); $this->register_site_if_needed(); $this->maybe_redirect_after_job(); } private function maybe_redirect_after_job(): void { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading current admin page slug only; no state change. $page = filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS); if (!is_string($page) || $page !== 'airf-restock-forecast') { return; } // Already showing a notice — avoid redirect loop // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Checking for an existing notice flag only; no state change. if (filter_has_var(INPUT_GET, 'airf_notice')) { return; } if (!current_user_can('manage_woocommerce')) { return; } $job_status = get_option(AIRF_OPTION_JOB_STATUS, []); if (!is_array($job_status) || !in_array($job_status['state'] ?? '', ['done', 'failed'], true)) { return; } $notice = (string) ($job_status['notice'] ?? 'analysis_failed'); delete_option(AIRF_OPTION_JOB_STATUS); wp_safe_redirect(add_query_arg('airf_notice', $notice, admin_url('admin.php?page=airf-restock-forecast'))); exit; } public function enqueue_admin_assets(string $hook): void { if ($hook !== 'woocommerce_page_airf-restock-forecast') { return; } wp_enqueue_style( 'airf-admin', plugin_dir_url(dirname(__FILE__)) . 'assets/css/admin.css', [], filemtime(plugin_dir_path(dirname(__FILE__)) . 'assets/css/admin.css') ); wp_enqueue_script( 'chart-js', plugin_dir_url(dirname(__FILE__)) . 'assets/vendor/chart.umd.min.js', [], '4.5.1', true ); wp_enqueue_script( 'hammerjs', plugin_dir_url(dirname(__FILE__)) . 'assets/vendor/hammer.min.js', [], '2.0.8', true ); wp_enqueue_script( 'chartjs-plugin-zoom', plugin_dir_url(dirname(__FILE__)) . 'assets/vendor/chartjs-plugin-zoom.min.js', ['chart-js', 'hammerjs'], '2.2.0', true ); wp_enqueue_script( 'airf-admin', plugin_dir_url(dirname(__FILE__)) . 'assets/js/admin.js', ['chart-js', 'chartjs-plugin-zoom'], filemtime(plugin_dir_path(dirname(__FILE__)) . 'assets/js/admin.js'), true ); $job_status = get_option(AIRF_OPTION_JOB_STATUS, []); $job_state = is_array($job_status) ? (string) ($job_status['state'] ?? '') : ''; wp_localize_script('airf-admin', 'airfAdmin', [ 'ajaxUrl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('airf_dispatch_analysis'), 'pollNonce' => wp_create_nonce('airf_poll_status'), 'verificationNonce' => wp_create_nonce('airf_verification'), 'redirectBase' => admin_url('admin.php?page=airf-restock-forecast'), 'jobState' => $job_state, ]); $last_result = get_option(AIRF_OPTION_LAST_RESULT, []); $insights_data = is_array($last_result) ? ($last_result['insights'] ?? []) : []; $plan_gates_data = is_array($last_result) ? ($last_result['plan_gates'] ?? []) : []; $recs_data = is_array($last_result) ? ($last_result['recommendations'] ?? []) : []; $billing_cta = $this->get_billing_cta('starter'); // Build product meta lookup (SKU → edit URL + live stock) for JS info panel $product_meta_map = []; foreach ($recs_data as $rec) { if (!is_array($rec)) continue; $sku = (string) ($rec['sku'] ?? ''); if ($sku !== '' && !isset($product_meta_map[$sku])) { $product_meta_map[$sku] = $this->resolve_product_meta($sku); } } wp_localize_script('airf-admin', 'airfInsights', [ 'forecastSeries' => is_array($insights_data) ? ($insights_data['forecast_series'] ?? []) : [], 'stockoutRevenue' => is_array($insights_data) ? ($insights_data['stockout_revenue_loss'] ?? null) : null, 'seasonalPatterns' => is_array($insights_data) ? ($insights_data['seasonal_patterns'] ?? null) : null, 'demandAnomalies' => is_array($insights_data) ? ($insights_data['demand_anomalies'] ?? []) : [], 'reorderCalendar' => is_array($insights_data) ? ($insights_data['reorder_calendar'] ?? []) : [], 'abcSummary' => is_array($insights_data) ? ($insights_data['abc_summary'] ?? null) : null, 'abcClassification' => is_array($insights_data) ? ($insights_data['abc_classification'] ?? null) : null, 'planGates' => $plan_gates_data, 'recommendations' => $recs_data, 'productMeta' => $product_meta_map, 'upgradeUrls' => [ 'starter' => $billing_cta['url'], 'growth' => $billing_cta['url'], ], 'billingEnabled' => AIRF_BILLING_ENABLED, ]); } public function ajax_dispatch_analysis(): void { check_ajax_referer('airf_dispatch_analysis', 'nonce'); if (!current_user_can('manage_woocommerce')) { wp_send_json_error(['message' => 'permission_denied'], 403); } // If a job is already in flight, return its current state — don't double-dispatch $current = get_option(AIRF_OPTION_JOB_STATUS, []); if (is_array($current) && in_array($current['state'] ?? '', ['queued', 'running', 'retrying'], true)) { wp_send_json_success(['state' => $current['state']]); } wp_clear_scheduled_hook('airf_timeout_reconcile_event'); $now = time(); update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'queued', 'dispatched_at' => $now, 'last_heartbeat_at' => $now, ], false); wp_schedule_single_event($now, 'airf_run_queued_analysis'); // Kick WP-Cron immediately so the job starts without waiting for the next page load. $this->kick_wp_cron(); $this->airf_log('dispatch_queued', ['ts' => $now]); wp_send_json_success(['state' => 'queued']); } public function ajax_poll_job_status(): void { check_ajax_referer('airf_poll_status', 'nonce'); if (!current_user_can('manage_woocommerce')) { wp_send_json_error(['message' => 'permission_denied'], 403); } $this->maybe_run_timeout_reconcile_fallback(); $this->maybe_recover_stuck_running_job(); $this->maybe_run_sync_fallback_dispatch(); $status = get_option(AIRF_OPTION_JOB_STATUS, []); $state = is_array($status) ? (string) ($status['state'] ?? 'unknown') : 'unknown'; $notice = is_array($status) ? (string) ($status['notice'] ?? '') : ''; wp_send_json_success(['state' => $state, 'notice' => $notice]); } public function run_queued_analysis(): void { $status = get_option(AIRF_OPTION_JOB_STATUS, []); // Only process if job is in a runnable state if (!is_array($status) || !in_array($status['state'] ?? '', ['queued', 'running'], true)) { return; } $dispatched_at = (int) ($status['dispatched_at'] ?? time()); // Raise limits for large stores. Best-effort: FPM may ignore set_time_limit. if (function_exists('wp_raise_memory_limit')) { wp_raise_memory_limit('admin'); } @set_time_limit(0); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- set_time_limit may be disabled by host. if (function_exists('ignore_user_abort')) { @ignore_user_abort(true); // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged } // Shutdown handler: if PHP fatals (OOM, FPM kill) before we update status, // record a failed state so the UI can recover. Best-effort — the DB may also // be gone after a hard OOM, so the running-job watchdog is still the primary // safety net. We capture a baseline of error_get_last() right now so we only // react to errors that occur AFTER this point (avoids misattributing pre-worker // warnings/errors from other plugins). $shutdown_marker = ['active' => true, 'dispatched_at' => $dispatched_at]; $shutdown_marker_ref = &$shutdown_marker; $baseline_err = error_get_last(); register_shutdown_function(function () use (&$shutdown_marker_ref, $baseline_err) { if (empty($shutdown_marker_ref['active'])) { return; } $err = error_get_last(); if (!is_array($err)) { return; } // Skip if error_get_last() is unchanged from baseline (no new fatal here). if (is_array($baseline_err) && $err == $baseline_err) { return; } $fatal_mask = E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR; if (!((int) ($err['type'] ?? 0) & $fatal_mask)) { return; } $reason = 'fatal_error'; $msg = strtolower((string) ($err['message'] ?? '')); if (strpos($msg, 'allowed memory size') !== false || strpos($msg, 'out of memory') !== false) { $reason = 'oom_suspected'; } elseif (strpos($msg, 'maximum execution time') !== false) { $reason = 'fpm_timeout'; } update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'failed', 'notice' => 'analysis_failed', 'dispatched_at' => (int) $shutdown_marker_ref['dispatched_at'], 'last_heartbeat_at' => time(), 'failure_reason' => $reason, ], false); $existing_status = get_option(AIRF_OPTION_LAST_STATUS, []); if (!is_array($existing_status)) { $existing_status = []; } $existing_status['failure_reason'] = $reason; update_option(AIRF_OPTION_LAST_STATUS, $existing_status, false); }); try { $now = time(); update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'running', 'dispatched_at' => $dispatched_at, 'last_heartbeat_at' => $now, ], false); $this->airf_log('worker_enter', ['dispatched_at' => $dispatched_at]); $result = $this->run_analysis_with_lock(); if ($result === null) { update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'queued', 'dispatched_at' => $dispatched_at, 'last_heartbeat_at' => time(), ], false); if (!wp_next_scheduled('airf_run_queued_analysis')) { wp_schedule_single_event(time() + 30, 'airf_run_queued_analysis'); } $shutdown_marker['active'] = false; return; } $notice = (string) ($result['notice'] ?? 'analysis_failed'); if ($notice === 'analysis_retrying') { $this->start_timeout_reconcile( $dispatched_at, (int) ($result['analysis_started_at'] ?? time()), (string) ($result['baseline_generated_at'] ?? '') ); $shutdown_marker['active'] = false; return; } update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => $notice === 'analysis_failed' ? 'failed' : 'done', 'notice' => $notice, 'dispatched_at' => $dispatched_at, 'last_heartbeat_at' => time(), ], false); $this->airf_log('worker_done', ['notice' => $notice]); $shutdown_marker['active'] = false; } catch (\Throwable $e) { wp_clear_scheduled_hook('airf_timeout_reconcile_event'); update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'failed', 'notice' => 'analysis_failed', 'dispatched_at' => $dispatched_at, 'last_heartbeat_at' => time(), 'failure_reason' => 'exception', ], false); $this->airf_log('worker_exception', ['msg' => $e->getMessage()]); $shutdown_marker['active'] = false; } } private function get_timeout_reconcile_delays(): array { $default_delays = [10, 25, 45]; $raw_delays = apply_filters('airf_timeout_reconcile_delays', $default_delays); if (!is_array($raw_delays) || empty($raw_delays)) { return $default_delays; } $delays = []; foreach ($raw_delays as $delay) { $seconds = max(1, (int) $delay); $delays[] = $seconds; } if (empty($delays)) { return $default_delays; } return array_values($delays); } private function kick_wp_cron(): void { if (function_exists('spawn_cron')) { spawn_cron(microtime(true)); } } /** * Site-scoped advisory lock name. Multisite-safe: each subsite gets its own * lock so site A's analysis cannot block site B's. The 64-char MySQL lock-name * limit (since 5.7) is comfortably respected. */ private function get_analysis_lock_name(): string { $blog_id = function_exists('get_current_blog_id') ? (int) get_current_blog_id() : 0; return 'airf_analysis_job_' . $blog_id; } /** * Lightweight gated logger used at dispatch / worker / watchdog boundaries. * Off by default; enable via WP_DEBUG or `airf_debug_logging` filter. */ private function airf_log(string $event, array $context = []): void { $enabled = (defined('WP_DEBUG') && WP_DEBUG) || apply_filters('airf_debug_logging', false); if (!$enabled) { return; } $line = '[airf] ' . $event; if (!empty($context)) { $line .= ' ' . wp_json_encode($context); } error_log($line); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Gated debug log. } private function get_running_watchdog_ttl(): int { return max(60, (int) apply_filters('airf_running_watchdog_ttl', 240)); } /** * Recover stuck `running` / `queued` jobs whose worker died (OOM / FPM kill / * lost cron). Three independent gates protect against false-positive kills: * 1. Heartbeat must be older than `airf_running_watchdog_ttl` (default 240 s). * 2. No `airf_run_queued_analysis` cron event is pending. * 3. The MySQL advisory lock `airf_analysis_job` is NOT currently held by any * connection (i.e. no live worker exists). This is the strongest signal * because the lock is auto-released only when the worker's DB connection * closes — a true dead-man switch. */ private function maybe_recover_stuck_running_job(): void { $status = get_option(AIRF_OPTION_JOB_STATUS, []); if (!is_array($status)) { return; } $state = (string) ($status['state'] ?? ''); if (!in_array($state, ['queued', 'running'], true)) { return; } $now = time(); $dispatched_at = (int) ($status['dispatched_at'] ?? 0); $last_heartbeat_at = (int) ($status['last_heartbeat_at'] ?? $dispatched_at); $progress_at = max($dispatched_at, $last_heartbeat_at); $ttl = $this->get_running_watchdog_ttl(); if ($progress_at <= 0 || ($now - $progress_at) < $ttl) { return; } // Gate 2: a worker run is still legitimately scheduled — give it a chance. if (wp_next_scheduled('airf_run_queued_analysis') !== false) { return; } // Gate 3: a real worker is actively holding the advisory lock. Refresh the // heartbeat (so we don't re-probe every poll) and let it finish. if ($this->is_analysis_lock_held()) { $status['last_heartbeat_at'] = $now; update_option(AIRF_OPTION_JOB_STATUS, $status, false); $this->airf_log('watchdog_skipped_lock_held'); return; } // Anti-flicker: a worker that JUST returned successfully will write // `state=done` within a few ms of releasing the lock. Require lock-not-held // to be observed for `airf_watchdog_grace` seconds (default 10) before // killing, so we don't race-redirect the user to "failed" right before the // worker stamps "done". $not_held_since = (int) ($status['watchdog_not_held_since'] ?? 0); $grace = max(2, (int) apply_filters('airf_watchdog_grace', 10)); if ($not_held_since <= 0) { $status['watchdog_not_held_since'] = $now; update_option(AIRF_OPTION_JOB_STATUS, $status, false); return; } if (($now - $not_held_since) < $grace) { return; } wp_clear_scheduled_hook('airf_timeout_reconcile_event'); update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'failed', 'notice' => 'analysis_failed', 'dispatched_at' => $dispatched_at ?: $now, 'last_heartbeat_at' => $now, 'failure_reason' => 'worker_stalled', ], false); $existing_status = get_option(AIRF_OPTION_LAST_STATUS, []); if (!is_array($existing_status)) { $existing_status = []; } $existing_status['failure_reason'] = 'worker_stalled'; update_option(AIRF_OPTION_LAST_STATUS, $existing_status, false); // The API may have processed the request before our worker died (counted // 1 quota call). Schedule a deferred reconcile so the customer doesn't // burn quota on a manual retry that produces the same result. Done via // cron — NOT inline — so a shopper hitting init never pays the cost. if (!wp_next_scheduled('airf_timeout_reconcile_event')) { $started_at = (int) ($status['dispatched_at'] ?? $now); update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'retrying', 'notice' => 'analysis_retrying', 'dispatched_at' => $dispatched_at ?: $now, 'last_heartbeat_at' => $now, 'retry_attempt' => 0, 'retry_delays' => $this->get_timeout_reconcile_delays(), 'retry_analysis_started_at' => $started_at, 'retry_baseline_generated_at' => '', 'retry_started_at' => $now, 'retry_last_checked_at' => 0, 'retry_next_check_at' => $now + 5, 'failure_reason' => 'worker_stalled', ], false); wp_schedule_single_event($now + 5, 'airf_timeout_reconcile_event'); } $this->airf_log('watchdog_stuck_running', ['age' => $now - $progress_at]); } /** * MySQL `IS_USED_LOCK` returns the connection id holding the named lock, or * NULL if not held. We use it to detect an active worker without taking the * lock ourselves (which would race with the real worker). */ private function is_analysis_lock_held(): bool { global $wpdb; $lock_name = $this->get_analysis_lock_name(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Liveness probe; no caching is meaningful. $holder = $wpdb->get_var($wpdb->prepare("SELECT IS_USED_LOCK(%s)", $lock_name)); return $holder !== null && $holder !== ''; } /** * Non-blocking fallback dispatch: if a `queued` job has not been picked up by * WP-Cron within the threshold (host blocks self-loopback, DISABLE_WP_CRON * without system cron, etc.), fire a fire-and-forget loopback POST to a * dedicated worker endpoint. We do NOT run the worker inline from the poll * handler — that would block the AJAX response for the full analysis duration. * * Idempotency: * - Throttled to one kick per `airf_loopback_kick_throttle` seconds (default 30). * - The endpoint validates a single-use random token. * - The MySQL advisory lock inside `run_analysis_with_lock()` makes concurrent * execution impossible even if cron also fires. */ private function maybe_run_sync_fallback_dispatch(): void { if (!apply_filters('airf_enable_sync_fallback_dispatch', true)) { return; } $status = get_option(AIRF_OPTION_JOB_STATUS, []); if (!is_array($status) || ($status['state'] ?? '') !== 'queued') { return; } $dispatched_at = (int) ($status['dispatched_at'] ?? 0); $threshold = max(15, (int) apply_filters('airf_sync_fallback_threshold', 60)); if ($dispatched_at <= 0 || (time() - $dispatched_at) < $threshold) { return; } // Throttle so a chatty front-end (3 s polling) doesn't cause a kick storm. $throttle = max(5, (int) apply_filters('airf_loopback_kick_throttle', 30)); if (get_transient('airf_loopback_kick_lock')) { return; } set_transient('airf_loopback_kick_lock', 1, $throttle); // Re-arm the cron event in case it was lost. if (!wp_next_scheduled('airf_run_queued_analysis')) { wp_schedule_single_event(time(), 'airf_run_queued_analysis'); } $this->kick_wp_cron(); // Fire-and-forget loopback POST. Authenticated by a single-use token in a // short-lived transient — the endpoint is wp_ajax_nopriv-registered because // the loopback request carries no logged-in cookie. if (function_exists('wp_generate_password')) { $token = wp_generate_password(40, false, false); } else { $token = bin2hex(random_bytes(20)); } set_transient('airf_loopback_token', $token, 120); wp_remote_post(admin_url('admin-ajax.php'), [ 'timeout' => 0.01, 'blocking' => false, 'sslverify' => apply_filters('https_local_ssl_verify', false), 'cookies' => [], 'body' => [ 'action' => 'airf_run_worker_loopback', 'token' => $token, ], ]); $this->airf_log('loopback_kicked', ['age' => time() - $dispatched_at]); } /** * Loopback worker endpoint. Reachable without auth so the non-blocking POST * (which doesn't carry browser cookies) succeeds. Defence in depth: * 1. Per-IP throttle: 1 request / 5 s (transient-backed). * 2. REMOTE_ADDR allowlist: 127.0.0.1 / ::1 / SERVER_ADDR (same host). * Hosts behind a proxy can extend via `airf_loopback_allowed_ips` filter. * 3. User-Agent must contain "WordPress/" — our dispatcher uses WP's HTTP API * which always sets this UA; arbitrary attackers do not. * 4. Single-use random token in a 120 s transient, consumed atomically. * All four must pass before any work happens. */ public function ajax_run_worker_loopback(): void { // Gate 1: per-IP throttle (drops bulk-flood attempts before any heavier work). $ip = isset($_SERVER['REMOTE_ADDR']) ? (string) $_SERVER['REMOTE_ADDR'] : ''; $ip = preg_replace('/[^0-9a-fA-F:.]/', '', $ip); if ($ip !== '') { $throttle_key = 'airf_lb_ip_' . md5($ip); if (get_transient($throttle_key)) { wp_send_json_error(['message' => 'throttled'], 429); } set_transient($throttle_key, 1, 5); } // Gate 2: REMOTE_ADDR allowlist — loopback dispatch always originates locally. $allowed = ['127.0.0.1', '::1']; if (!empty($_SERVER['SERVER_ADDR'])) { $allowed[] = (string) $_SERVER['SERVER_ADDR']; } $allowed = array_values(array_unique(array_filter( (array) apply_filters('airf_loopback_allowed_ips', $allowed), 'is_string' ))); if ($ip === '' || !in_array($ip, $allowed, true)) { wp_send_json_error(['message' => 'forbidden'], 403); } // Gate 3: User-Agent fingerprint — WP's HTTP API always sends "WordPress/". $ua = isset($_SERVER['HTTP_USER_AGENT']) ? (string) $_SERVER['HTTP_USER_AGENT'] : ''; if (stripos($ua, 'WordPress/') === false) { wp_send_json_error(['message' => 'forbidden'], 403); } // Gate 4: single-use token. // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Token-authenticated; nonce isn't usable across PHP loopback. $token = isset($_POST['token']) ? sanitize_text_field(wp_unslash($_POST['token'])) : ''; $expected = get_transient('airf_loopback_token'); if (!is_string($expected) || $expected === '' || $token === '' || !hash_equals($expected, $token)) { wp_send_json_error(['message' => 'invalid_token'], 403); } // Single-use: consume the token before doing any work. delete_transient('airf_loopback_token'); $this->run_queued_analysis(); wp_send_json_success(['ran' => true]); } private function start_timeout_reconcile(int $dispatched_at, int $analysis_started_at, string $baseline_generated_at): void { $delays = $this->get_timeout_reconcile_delays(); $next_check_at = time() + (int) $delays[0]; wp_clear_scheduled_hook('airf_timeout_reconcile_event'); update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'retrying', 'notice' => 'analysis_retrying', 'dispatched_at' => $dispatched_at, 'retry_attempt' => 0, 'retry_delays' => $delays, 'retry_analysis_started_at' => $analysis_started_at, 'retry_baseline_generated_at' => $baseline_generated_at, 'retry_started_at' => time(), 'retry_last_checked_at' => 0, 'retry_next_check_at' => $next_check_at, ], false); wp_schedule_single_event($next_check_at, 'airf_timeout_reconcile_event'); $this->kick_wp_cron(); } private function get_timeout_reconcile_lock_ttl(): int { return max(5, (int) apply_filters('airf_timeout_reconcile_lock_ttl', 20)); } private function get_timeout_reconcile_watchdog_ttl(): int { return max(60, (int) apply_filters('airf_timeout_reconcile_watchdog_ttl', 600)); } private function maybe_run_timeout_reconcile_fallback(): void { $status = get_option(AIRF_OPTION_JOB_STATUS, []); if (!is_array($status) || ($status['state'] ?? '') !== 'retrying') { return; } $now = time(); $attempt = max(0, (int) ($status['retry_attempt'] ?? 0)); $delays = isset($status['retry_delays']) && is_array($status['retry_delays']) ? array_values(array_map('intval', $status['retry_delays'])) : $this->get_timeout_reconcile_delays(); $next_check_at = (int) ($status['retry_next_check_at'] ?? 0); if ($next_check_at <= 0) { $delay_index = min($attempt, max(0, count($delays) - 1)); $next_check_at = $now + (int) ($delays[$delay_index] ?? 10); $status['retry_next_check_at'] = $next_check_at; update_option(AIRF_OPTION_JOB_STATUS, $status, false); } if (wp_next_scheduled('airf_timeout_reconcile_event') === false) { $schedule_at = max($now + 1, $next_check_at); wp_schedule_single_event($schedule_at, 'airf_timeout_reconcile_event'); $this->kick_wp_cron(); } $retry_started_at = (int) ($status['retry_started_at'] ?? $status['dispatched_at'] ?? $now); $watchdog_due = $retry_started_at > 0 && (($now - $retry_started_at) >= $this->get_timeout_reconcile_watchdog_ttl()); if (!$watchdog_due && $next_check_at > 0 && $now < $next_check_at) { return; } if (get_transient('airf_timeout_reconcile_lock')) { return; } set_transient('airf_timeout_reconcile_lock', 1, $this->get_timeout_reconcile_lock_ttl()); try { $this->run_timeout_reconcile($watchdog_due); } finally { delete_transient('airf_timeout_reconcile_lock'); } } public function run_timeout_reconcile(bool $force_terminal = false): void { $status = get_option(AIRF_OPTION_JOB_STATUS, []); if (!is_array($status) || ($status['state'] ?? '') !== 'retrying') { return; } $dispatched_at = (int) ($status['dispatched_at'] ?? time()); $analysis_started_at = (int) ($status['retry_analysis_started_at'] ?? $dispatched_at); $baseline_generated_at = (string) ($status['retry_baseline_generated_at'] ?? ''); $attempt = max(0, (int) ($status['retry_attempt'] ?? 0)); $delays = isset($status['retry_delays']) && is_array($status['retry_delays']) ? array_values(array_map('intval', $status['retry_delays'])) : $this->get_timeout_reconcile_delays(); $site_token = get_option(AIRF_OPTION_SITE_TOKEN, ''); if (!is_string($site_token) || $site_token === '') { wp_clear_scheduled_hook('airf_timeout_reconcile_event'); update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'failed', 'notice' => 'site_not_registered', 'dispatched_at' => $dispatched_at, ], false); return; } if ($this->reconcile_after_timeout($site_token, $baseline_generated_at, $analysis_started_at)) { wp_clear_scheduled_hook('airf_timeout_reconcile_event'); update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'done', 'notice' => 'analysis_success', 'dispatched_at' => $dispatched_at, ], false); return; } if ($force_terminal) { wp_clear_scheduled_hook('airf_timeout_reconcile_event'); update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'failed', 'notice' => 'analysis_failed', 'dispatched_at' => $dispatched_at, ], false); return; } $next_attempt = $attempt + 1; if (isset($delays[$next_attempt])) { $next_check_at = time() + (int) $delays[$next_attempt]; wp_clear_scheduled_hook('airf_timeout_reconcile_event'); update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'retrying', 'notice' => 'analysis_retrying', 'dispatched_at' => $dispatched_at, 'retry_attempt' => $next_attempt, 'retry_delays' => $delays, 'retry_analysis_started_at' => $analysis_started_at, 'retry_baseline_generated_at' => $baseline_generated_at, 'retry_started_at' => (int) ($status['retry_started_at'] ?? time()), 'retry_last_checked_at' => time(), 'retry_next_check_at' => $next_check_at, ], false); wp_schedule_single_event($next_check_at, 'airf_timeout_reconcile_event'); $this->kick_wp_cron(); return; } wp_clear_scheduled_hook('airf_timeout_reconcile_event'); update_option(AIRF_OPTION_JOB_STATUS, [ 'state' => 'failed', 'notice' => 'analysis_failed', 'dispatched_at' => $dispatched_at, ], false); } private function run_analysis_with_lock(): ?array { global $wpdb; $lock_name = $this->get_analysis_lock_name(); // MySQL advisory lock — atomic, works on every WordPress install. // Auto-released when the DB connection closes (dead-man switch). // Returns '1' = acquired, '0' = held by another process, NULL = error. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Advisory lock requires direct SQL and is intentionally uncached. $lock = $wpdb->get_var($wpdb->prepare("SELECT GET_LOCK(%s, 0)", $lock_name)); if ($lock !== '1') { return null; } try { return $this->run_analysis_internal(); } finally { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Release advisory lock acquired above. $wpdb->query($wpdb->prepare("SELECT RELEASE_LOCK(%s)", $lock_name)); } } private function run_scheduled_analysis(): void { $result = $this->run_analysis_with_lock(); if ($result === null) { return; } if (($result['notice'] ?? '') === 'analysis_failed' && !wp_next_scheduled('airf_retry_analysis_event')) { wp_schedule_single_event(time() + HOUR_IN_SECONDS, 'airf_retry_analysis_event'); } } /** * Sync plan from API (at most once per 60 s to avoid hammering). * Updates AIRF_OPTION_PLAN_META with fresh plan/quota/calls_used. */ private function sync_plan(bool $force = false): void { // Rate-limit: skip if we synced within the last 60 seconds if (!$force && get_transient('airf_plan_synced')) { return; } $site_token = get_option(AIRF_OPTION_SITE_TOKEN, ''); if (!is_string($site_token) || $site_token === '') { return; } $result = $this->api_client->get_plan_status($site_token); if ($result['ok'] && is_array($result['data'])) { update_option(AIRF_OPTION_PLAN_META, $result['data'], false); // Keep airf_plan in sync for quick lookups $plan = $result['data']['plan'] ?? 'free'; update_option('airf_plan', $plan, false); // Only rate-limit on success — a failed sync (stale token, blip) must // not block the next attempt for up to 60 s. set_transient('airf_plan_synced', 1, 60); } elseif (in_array((int) ($result['status'] ?? 0), [401, 403, 404], true)) { // Site not found or token invalid — fully deregister so the verification // form is shown immediately on the next page load. delete_option(AIRF_OPTION_SITE_TOKEN); delete_option(AIRF_OPTION_SIGNING_SECRET); delete_option(AIRF_OPTION_PLAN_META); delete_option('airf_plan'); delete_transient('airf_plan_synced'); } } private function is_timeout_result(array $result): bool { $status = (int) ($result['status'] ?? 0); if ($status !== 0) { return false; } $message = strtolower((string) ($result['message'] ?? '')); return $message !== '' && (strpos($message, 'timeout') !== false || strpos($message, 'curl error 28') !== false); } private function is_generated_at_newer(string $candidate, string $baseline, int $analysis_started_at): bool { if ($candidate === '') { return false; } $candidate_ts = strtotime($candidate); if ($candidate_ts === false) { return false; } $analysis_floor = max(0, $analysis_started_at - 5); if ($candidate_ts < $analysis_floor) { return false; } $baseline_ts = $baseline !== '' ? strtotime($baseline) : false; if ($baseline_ts !== false) { return $candidate_ts > $baseline_ts; } return true; } private function reconcile_after_timeout(string $site_token, string $baseline_generated_at = '', int $analysis_started_at = 0): bool { // Bypass transient rate-limit so local counters stay aligned after network blips. $this->sync_plan(true); $cached = $this->api_client->get_cached_analysis($site_token); if (!$cached['ok'] || !is_array($cached['data']) || !empty($cached['data']['empty'])) { return false; } $latest = $cached['data']; $existing = get_option(AIRF_OPTION_LAST_RESULT, []); $latest_generated_at = (string) ($latest['generated_at'] ?? ''); $existing_generated_at = is_array($existing) ? (string) ($existing['generated_at'] ?? '') : ''; if ($baseline_generated_at === '') { $baseline_generated_at = $existing_generated_at; } if ($analysis_started_at <= 0) { $analysis_started_at = time(); } if (!$this->is_generated_at_newer($latest_generated_at, $baseline_generated_at, $analysis_started_at)) { return false; } if ($latest_generated_at !== '' && $latest_generated_at === $existing_generated_at) { return true; } update_option(AIRF_OPTION_LAST_RESULT, $latest, false); update_option('airf_last_analysis_date', gmdate('Y-m-d'), false); update_option( AIRF_OPTION_LAST_STATUS, [ 'stale' => !empty($latest['stale']), 'stale_generated_at' => (string) ($latest['stale_generated_at'] ?? ''), 'low_confidence' => false, ], false ); $this->advance_rotation_offset(); return true; } private function register_site_if_needed(): void { if (get_option(AIRF_OPTION_SITE_TOKEN)) { return; } // If we have a signing_secret, try HMAC re-registration first (fast path) $signing_secret = get_option(AIRF_OPTION_SIGNING_SECRET, ''); if ($signing_secret) { $result = $this->api_client->register_site(); if ($result['ok'] && is_array($result['data'])) { $this->save_registration_response($result['data']); return; } } // No signing_secret or HMAC failed — email verification required. // The admin page will show the verification form. } private function save_registration_response(array $data): void { if (!empty($data['site_token'])) { update_option(AIRF_OPTION_SITE_TOKEN, sanitize_text_field($data['site_token']), false); } if (!empty($data['signing_secret'])) { update_option(AIRF_OPTION_SIGNING_SECRET, sanitize_text_field($data['signing_secret']), false); } update_option(AIRF_OPTION_PLAN_META, $data, false); } public function ajax_send_verification_code(): void { check_ajax_referer('airf_verification', 'nonce'); if (!current_user_can('manage_woocommerce')) { wp_send_json_error(['message' => 'permission_denied'], 403); } $consent = isset($_POST['consent']) ? sanitize_text_field(wp_unslash($_POST['consent'])) : '0'; if ($consent !== '1') { wp_send_json_error(['message' => __('You must consent to the Terms and Privacy Policy before continuing.', 'airf-restock-forecast')]); } $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : ''; if (!is_email($email)) { wp_send_json_error(['message' => __('Please enter a valid email address.', 'airf-restock-forecast')]); } $result = $this->api_client->register_init($email); if (!$result['ok']) { wp_send_json_error([ 'message' => $result['message'] ?? __('Unable to send verification code.', 'airf-restock-forecast'), 'code' => $result['code'] ?? '', ]); } // Store original email for display in Settings > Site Info update_option(AIRF_OPTION_VERIFICATION_EMAIL, sanitize_email($email), false); // Show masked email in verification UI response $masked_email = $result['data']['email'] ?? ''; $response = [ 'email' => $masked_email, 'recovery' => !empty($result['data']['recovery']), ]; if (isset($result['data']['dev_code']) && is_string($result['data']['dev_code'])) { $response['dev_code'] = sanitize_text_field($result['data']['dev_code']); } wp_send_json_success($response); } public function ajax_verify_code(): void { check_ajax_referer('airf_verification', 'nonce'); if (!current_user_can('manage_woocommerce')) { wp_send_json_error(['message' => 'permission_denied'], 403); } $code = isset($_POST['code']) ? sanitize_text_field(wp_unslash($_POST['code'])) : ''; if (!preg_match('/^\d{6}$/', $code)) { wp_send_json_error(['message' => __('Please enter a valid 6-digit code.', 'airf-restock-forecast')]); } $result = $this->api_client->register_verify($code); if (!$result['ok'] || !is_array($result['data'])) { wp_send_json_error([ 'message' => $result['message'] ?? __('Verification failed.', 'airf-restock-forecast'), ]); } $this->save_registration_response($result['data']); // Keep AIRF_OPTION_VERIFICATION_EMAIL stored — it is displayed in Settings > Site Info // and acts as the recovery email identifier for the admin. // Discard any analysis job that may have been queued under the old token. wp_clear_scheduled_hook('airf_run_queued_analysis'); wp_clear_scheduled_hook('airf_timeout_reconcile_event'); $stale_job = get_option(AIRF_OPTION_JOB_STATUS, []); if (is_array($stale_job) && in_array($stale_job['state'] ?? '', ['queued', 'running', 'retrying'], true)) { delete_option(AIRF_OPTION_JOB_STATUS); } wp_send_json_success(['registered' => true]); } public function register_admin_page(): void { add_submenu_page( 'woocommerce', __('AIRF Restock Forecast', 'airf-restock-forecast'), __('AIRF Restock Forecast', 'airf-restock-forecast'), 'manage_woocommerce', 'airf-restock-forecast', [$this, 'render_admin_page'] ); } public function render_admin_notice(): void { if (!current_user_can('manage_woocommerce')) { return; } $screen = get_current_screen(); if (!$screen || $screen->id !== 'woocommerce_page_airf-restock-forecast') { return; } $notice_key_raw = filter_input(INPUT_GET, 'airf_notice', FILTER_SANITIZE_FULL_SPECIAL_CHARS); if (is_string($notice_key_raw) && $notice_key_raw !== '') { $notice_key = sanitize_key($notice_key_raw); $notice_map = [ 'analysis_success' => ['success', __('Analysis completed successfully.', 'airf-restock-forecast')], 'countries_saved' => ['success', __('Customer countries were saved.', 'airf-restock-forecast')], 'countries_load_failed' => ['warning', __('Could not load latest countries from API. Showing cached values.', 'airf-restock-forecast')], 'countries_save_timeout' => ['warning', __('Saving countries is taking longer than expected. Please try again in a moment if the selection does not appear.', 'airf-restock-forecast')], 'countries_save_failed' => ['error', __('Could not save countries because the API is unreachable. Please try again after connectivity is restored.', 'airf-restock-forecast')], 'quota_exceeded' => [ 'warning', AIRF_BILLING_ENABLED ? __('Monthly credits exhausted for your current AIRF service plan. Choose another plan or wait for next month.', 'airf-restock-forecast') : __('Monthly credits exhausted. Please wait for the next month reset.', 'airf-restock-forecast'), ], 'low_confidence' => ['warning', __('Not enough order history yet. Forecast requires at least 60 days of data.', 'airf-restock-forecast')], 'missing_products' => ['warning', __('No products with sales history were found for analysis.', 'airf-restock-forecast')], 'analysis_failed' => ['error', __('Analysis request failed. The previous cached result is still available if present.', 'airf-restock-forecast')], 'site_not_registered' => ['error', __('Site token is missing. Please deactivate and reactivate the plugin.', 'airf-restock-forecast')], 'token_invalid' => ['error', __('Your site credentials have changed — likely because another server recovered the same account. Please re-register using the verification form.', 'airf-restock-forecast')], ]; if (isset($notice_map[$notice_key])) { echo '

'; echo esc_html($notice_map[$notice_key][1]); echo '

'; } } } public function render_admin_page(): void { if (!current_user_can('manage_woocommerce')) { wp_die(esc_html__('You do not have permission to access this page.', 'airf-restock-forecast')); } // Gate: if no site_token, show the email verification form if (!get_option(AIRF_OPTION_SITE_TOKEN)) { $this->render_verification_page(); return; } $this->sync_plan(); // phpcs:ignore WordPress.Security.NonceVerification.Recommended $active_tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : 'dashboard'; if (!in_array($active_tab, ['dashboard', 'insights', 'history', 'settings'], true)) { $active_tab = 'dashboard'; } $base = admin_url('admin.php?page=airf-restock-forecast'); echo '
'; echo '

' . esc_html__('AIRF Restock Forecast', 'airf-restock-forecast') . '

'; // Tab navigation echo ''; switch ($active_tab) { case 'insights': $this->render_insights_tab(); break; case 'history': $this->render_history_tab(); break; case 'settings': $this->render_settings_tab(); break; default: $this->render_dashboard_tab(); break; } echo '
'; } private function render_verification_page(): void { $masked_email = get_option(AIRF_OPTION_VERIFICATION_EMAIL, ''); $current_domain = wp_parse_url(home_url(), PHP_URL_HOST); // Render a non-blocking registration card so admin navigation remains usable. echo '
'; echo '

' . esc_html__('AIRF Restock Forecast', 'airf-restock-forecast') . '

'; echo '

' . esc_html__('This site is not yet registered. Complete verification to activate the plugin.', 'airf-restock-forecast') . '

'; echo '
'; echo '
'; // ── Step 1: email input ──────────────────────────────────────────────── echo ''; // ── Step 2: OTP input ───────────────────────────────────────────────── echo ''; echo '
'; // inner card echo '
'; // register container echo '

' . wp_kses( __('Plugin documentation & support', 'airf-restock-forecast'), ['a' => ['href' => [], 'target' => [], 'rel' => []]] ) . '

'; echo '
'; // wrap } private function render_dashboard_tab(): void { $plan_meta = get_option(AIRF_OPTION_PLAN_META, []); $last_result = get_option(AIRF_OPTION_LAST_RESULT, []); $last_status = get_option(AIRF_OPTION_LAST_STATUS, []); $plan = is_array($plan_meta) ? ($plan_meta['plan'] ?? 'unknown') : 'unknown'; $quota = is_array($plan_meta) ? (int) ($plan_meta['monthly_quota'] ?? 0) : 0; $credits_used = is_array($plan_meta) ? (int) ($plan_meta['calls_used'] ?? 0) : 0; $credits_remaining = max(0, $quota - $credits_used); $last_updated = is_array($last_result) ? ($last_result['generated_at'] ?? '') : ''; $analysis_source = is_array($last_result) ? (string) ($last_result['analysis_source'] ?? '') : ''; $summary = is_array($last_result) ? (string) ($last_result['summary'] ?? '') : ''; $pct = $quota > 0 ? min(100, round(($credits_used / $quota) * 100)) : 0; $bar_class = $pct >= 90 ? 'airf-progress__fill--danger' : ($pct >= 60 ? 'airf-progress__fill--warn' : 'airf-progress__fill--ok'); // ── Status alerts ── if ($analysis_source === 'mock') { echo '

' . esc_html__('Mock mode is active — these are test recommendations, not live analysis.', 'airf-restock-forecast') . '

'; } if (is_array($last_status) && !empty($last_status['stale'])) { echo '

' . sprintf( /* translators: %s: date of cached results */ esc_html__('Showing cached results from %s due to an upstream issue.', 'airf-restock-forecast'), esc_html((string) ($last_status['stale_generated_at'] ?? $last_updated)) ) . '

'; } if (is_array($last_status) && !empty($last_status['low_confidence'])) { echo '

' . sprintf( /* translators: %s: date to check back */ esc_html__('Low confidence — check back on %s.', 'airf-restock-forecast'), esc_html((string) ($last_status['check_back_date'] ?? __('a later date', 'airf-restock-forecast'))) ) . '

'; } // ── Top cards ── echo '
'; // Credits card echo '
'; echo '

' . esc_html__('Credits', 'airf-restock-forecast') . ' ' . esc_html(ucfirst($plan)) . '

'; echo '
' . esc_html((string) $credits_remaining) . '
'; echo '
' . sprintf( /* translators: %s: total quota */ esc_html__('of %s remaining this month', 'airf-restock-forecast'), esc_html((string) $quota) ) . '
'; echo '
'; echo '

' . sprintf( /* translators: 1: credits used, 2: total quota */ esc_html__('%1$s / %2$s credits used', 'airf-restock-forecast'), esc_html((string) $credits_used), esc_html((string) $quota) ) . '

'; if (AIRF_BILLING_ENABLED) { $billing_url = $this->is_paid_plan($plan) ? AIRF_POLAR_PORTAL_URL : $this->get_checkout_url('starter'); $billing_label = $this->is_paid_plan($plan) ? __('Open billing portal', 'airf-restock-forecast') : __('View plan options', 'airf-restock-forecast'); echo ''; } echo '
'; // Last analysis card echo '
'; echo '

' . esc_html__('Last Analysis', 'airf-restock-forecast') . '

'; if ($last_updated !== '') { echo '
' . esc_html($this->human_time_diff($last_updated)) . '
'; $ts = strtotime($last_updated); echo '
' . esc_html($ts ? wp_date('M j, Y \a\t g:i A', $ts) : $last_updated) . '
'; } else { echo '
' . esc_html__('No analysis yet', 'airf-restock-forecast') . '
'; echo '
' . esc_html__('Click below to run your first analysis', 'airf-restock-forecast') . '
'; } echo '
'; echo ''; echo ''; echo '
'; echo '
'; echo '
'; // .airf-cards // ── Summary ── if ($summary !== '') { echo '

' . esc_html($summary) . '

'; } $insights = is_array($last_result) ? ($last_result['insights'] ?? []) : []; $plan_gates = is_array($last_result) ? ($last_result['plan_gates'] ?? []) : []; // ── ABC Summary ── if (is_array($insights) && is_array($plan_gates)) { $this->render_abc_summary_card($insights, $plan_gates); } // ── Recommendations table ── $this->render_recommendations_table($last_result); // ── Analysis Overview ── $forecast = is_array($insights) ? ($insights['forecast_series'] ?? []) : []; $recommendations = is_array($last_result['recommendations'] ?? null) ? $last_result['recommendations'] : []; if (!empty($recommendations) || (is_array($forecast) && !empty($forecast))) { $insights_url = admin_url('admin.php?page=airf-restock-forecast&tab=insights'); echo '
'; echo '

' . esc_html__('Analysis Overview', 'airf-restock-forecast') . '

'; echo '' . esc_html__('View all insights', 'airf-restock-forecast') . ' →'; echo '
'; echo '
'; echo '

' . esc_html__('Urgency distribution across analyzed products', 'airf-restock-forecast') . '

'; echo ''; echo '

' . esc_html__('This chart summarizes the latest analysis run. AIRF analyzes products with sales history, keeps about 75% of the run focused on top lifetime sellers, and rotates the remaining 25% across the rest of the catalog over time.', 'airf-restock-forecast') . '

'; echo '

' . esc_html__('Use Insights for product-by-product demand forecasts and deeper trend details.', 'airf-restock-forecast') . '

'; echo '
'; } // ── Revenue Loss Alert ── $revenue = is_array($insights) ? ($insights['stockout_revenue_loss'] ?? null) : null; if (is_array($revenue) && !empty($revenue)) { $total_monthly = 0.0; $currency = ''; $out_count = 0; foreach ($revenue as $rd) { if (!is_array($rd)) continue; $total_monthly += (float) ($rd['monthly_loss'] ?? 0); if ($currency === '') $currency = (string) ($rd['currency'] ?? ''); if (!empty($rd['currently_out'])) $out_count++; } if ($total_monthly > 0) { echo '
'; echo '
▼
'; echo '
'; echo '
' . esc_html($currency . ' ' . number_format($total_monthly, 0)) . '/mo
'; echo '
'; echo esc_html(sprintf( /* translators: %d: number of out-of-stock products */ _n( 'Estimated revenue lost from %d out-of-stock product', 'Estimated revenue lost from %d out-of-stock products', $out_count, 'airf-restock-forecast' ), $out_count )); echo '
'; echo '
'; echo '
'; } } elseif (is_array($plan_gates) && in_array('stockout_revenue', $plan_gates['locked_features'] ?? [], true) && AIRF_BILLING_ENABLED) { $billing_cta = $this->get_billing_cta('starter'); echo '
'; echo ' '; echo '' . esc_html__('Revenue impact analysis', 'airf-restock-forecast') . ' — ' . esc_html__('see how much stockouts cost you.', 'airf-restock-forecast') . ' '; echo '' . sprintf( /* translators: %s: billing CTA label (e.g. "View plan options") */ esc_html__('%s for plan details', 'airf-restock-forecast'), esc_html($billing_cta['label']) ) . ''; echo '
'; } } private function render_history_tab(): void { $site_token = get_option(AIRF_OPTION_SITE_TOKEN, ''); if (!is_string($site_token) || $site_token === '') { echo '

' . esc_html__('Site not registered. Please deactivate and reactivate the plugin.', 'airf-restock-forecast') . '

'; return; } $hist_page_raw = filter_input(INPUT_GET, 'hist_page', FILTER_SANITIZE_NUMBER_INT); $page = max(1, (int) ($hist_page_raw ?: '1')); $result = $this->api_client->get_analysis_history($site_token, $page); if (!$result['ok'] && (int) ($result['status'] ?? 0) === 401) { // Token rotated externally (e.g. another instance recovered the account). // Clearing it here causes ensure_registered() to re-register or show the form. delete_option(AIRF_OPTION_SITE_TOKEN); echo '

' . esc_html__('Your site credentials have expired. Please re-register the plugin to restore analysis history.', 'airf-restock-forecast') . '

'; return; } if (!$result['ok'] || !is_array($result['data']) || empty($result['data']['history'])) { echo '

' . esc_html__('No analysis history yet.', 'airf-restock-forecast') . '

' . wp_kses( sprintf( /* translators: %s: URL to Dashboard tab */ __('Run your first analysis from the Dashboard.', 'airf-restock-forecast'), esc_url(admin_url('admin.php?page=airf-restock-forecast&tab=dashboard')) ), ['a' => ['href' => []]] ) . '

'; return; } $history = $result['data']['history']; $pagination = $result['data']['pagination'] ?? null; // Build per-product sparkline data from history (most recent first) $product_stockout_history = []; foreach (array_reverse($history) as $entry) { if (!is_array($entry) || !is_array($entry['recommendations'] ?? null)) { continue; } foreach ($entry['recommendations'] as $rec) { if (!is_array($rec)) continue; $name = (string) ($rec['name'] ?? ''); $days = $rec['days_until_stockout'] ?? null; if ($name !== '' && $days !== null) { $product_stockout_history[$name][] = (int) $days; } } } echo '
'; foreach ($history as $i => $entry) { if (!is_array($entry)) continue; $date = (string) ($entry['generated_at'] ?? $entry['created_at'] ?? ''); $entry_summary = (string) ($entry['summary'] ?? ''); $recs = is_array($entry['recommendations'] ?? null) ? $entry['recommendations'] : []; echo '
'; echo '
'; echo '▶'; echo '' . esc_html($this->human_time_diff($date)) . ''; if ($entry_summary !== '') { echo '' . esc_html($entry_summary) . ''; } echo '
'; // Expandable body echo '
'; if (!empty($recs)) { echo ''; echo ''; foreach ($recs as $rec) { if (!is_array($rec)) continue; $name = (string) ($rec['name'] ?? 'Unknown'); $urgency = (string) ($rec['urgency'] ?? 'ok'); $qty = (string) ($rec['suggested_reorder_qty'] ?? 'n/a'); $hist_sku = (string) ($rec['sku'] ?? ''); $stockout = $this->format_stockout_display( $rec['days_until_stockout'] ?? null, $urgency, $rec['suggested_reorder_qty'] ?? null ); $trend = (string) ($rec['trend'] ?? 'stable'); // Sparkline for this product if we have 2+ data points $sparkline_html = ''; if (isset($product_stockout_history[$name]) && count($product_stockout_history[$name]) >= 2) { $sparkline_html = $this->render_sparkline($product_stockout_history[$name]); } $hist_meta = $this->resolve_product_meta($hist_sku); $allowed_sparkline_tags = [ 'svg' => [ 'class' => true, 'width' => true, 'height' => true, 'viewbox' => true, 'viewBox' => true, ], 'polyline' => [ 'points' => true, 'stroke' => true, ], ]; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; } echo '
' . esc_html__('Product', 'airf-restock-forecast') . '' . esc_html__('SKU', 'airf-restock-forecast') . '' . esc_html__('Urgency', 'airf-restock-forecast') . '' . esc_html__('Stockout', 'airf-restock-forecast') . '' . esc_html__('Qty', 'airf-restock-forecast') . '' . esc_html__('Trend', 'airf-restock-forecast') . '
' . esc_html($name) . ($sparkline_html !== '' ? ' ' . wp_kses($sparkline_html, $allowed_sparkline_tags) : '') . '' . wp_kses_post($this->render_sku_link($hist_sku, $hist_meta['edit_url'])) . '' . esc_html($urgency) . '' . esc_html((string) $stockout) . '' . esc_html($qty) . '' . wp_kses_post($this->render_trend($trend)) . '
'; } else { echo '

' . esc_html__('No product recommendations in this analysis.', 'airf-restock-forecast') . '

'; } echo '
'; // .airf-timeline-body echo '
'; // .airf-timeline-item } echo '
'; // .airf-timeline // Pagination controls if (is_array($pagination) && ($pagination['total_pages'] ?? 1) > 1) { $base_url = admin_url('admin.php?page=airf-restock-forecast&tab=history'); $total_pages = (int) $pagination['total_pages']; $current = (int) ($pagination['page'] ?? 1); echo '
'; if ($current > 1) { echo '« ' . esc_html__('Prev', 'airf-restock-forecast') . ' '; } echo '' . sprintf( /* translators: 1: current page, 2: total pages, 3: total analyses */ esc_html__('Page %1$s of %2$s (%3$s analyses)', 'airf-restock-forecast'), esc_html($current), esc_html($total_pages), esc_html($pagination['total'] ?? 0) ) . ''; if ($current < $total_pages) { echo ' ' . esc_html__('Next', 'airf-restock-forecast') . ' »'; } echo '
'; } } private function render_insights_tab(): void { $last_result = get_option(AIRF_OPTION_LAST_RESULT, []); if (!is_array($last_result)) $last_result = []; $insights = isset($last_result['insights']) && is_array($last_result['insights']) ? $last_result['insights'] : []; $plan_gates = isset($last_result['plan_gates']) && is_array($last_result['plan_gates']) ? $last_result['plan_gates'] : []; $locked = is_array($plan_gates['locked_features'] ?? null) ? $plan_gates['locked_features'] : []; $plan = (string) ($plan_gates['plan'] ?? 'free'); $total = (int) ($plan_gates['total_products'] ?? 0); $visible = (int) ($plan_gates['visible_insight_products'] ?? 1); if (empty($insights) || empty($insights['forecast_series'])) { echo '
'; echo ''; echo '

' . esc_html__( 'No insights data yet.', 'airf-restock-forecast' ) . '

'; echo '

' . esc_html__( 'Run an analysis from the Dashboard to generate prediction graphs and insights.', 'airf-restock-forecast' ) . '

'; echo '' . esc_html__( 'Go to Dashboard', 'airf-restock-forecast' ) . ''; echo '
'; return; } // ── Prediction Graphs — Single chart with product selector ── $forecast = $insights['forecast_series']; if (is_array($forecast) && !empty($forecast)) { echo '

' . esc_html__( 'Product Forecasts', 'airf-restock-forecast' ) . '

'; echo '

' . esc_html__( 'Detailed historical and predicted demand for one product at a time.', 'airf-restock-forecast' ) . '

'; // Product selector bar echo '
'; echo ''; echo ''; echo ''; echo ''; echo '
'; // Main chart + info panel layout echo '
'; echo '
'; echo ''; echo '
' . esc_html__( 'Scroll to zoom · Drag to pan ·', 'airf-restock-forecast' ) . '
'; echo '

' . esc_html__( 'Showing currently selected product. Use Export CSV for all products.', 'airf-restock-forecast' ) . '

'; echo '
'; echo '
'; echo '
'; echo '
' . esc_html__( 'SKU', 'airf-restock-forecast' ) . '
'; echo '
' . esc_html__( 'Stock', 'airf-restock-forecast' ) . '
'; echo '
' . esc_html__( 'Stockout in', 'airf-restock-forecast' ) . '
'; echo '
' . esc_html__( 'Reorder Qty', 'airf-restock-forecast' ) . '
'; echo '
' . esc_html__( 'Trend', 'airf-restock-forecast' ) . '
'; echo '
'; echo '
'; echo '
'; // Upgrade CTA for gated products if ($visible < $total && AIRF_BILLING_ENABLED) { $billing_cta = $this->get_billing_cta('starter'); echo '
'; echo ' '; echo wp_kses( sprintf( /* translators: 1: visible product count wrapped in , 2: total product count wrapped in */ __( 'Showing %1$s of %2$s products.', 'airf-restock-forecast' ), '' . esc_html((string) $visible) . '', '' . esc_html((string) $total) . '' ), ['strong' => []] ) . ' '; echo '' . esc_html($billing_cta['label']) . ' ' . esc_html__( 'for full plan coverage', 'airf-restock-forecast' ) . ' →'; echo '
'; } } // ── Stockout Revenue Loss ── echo '

' . esc_html__( 'Revenue Impact', 'airf-restock-forecast' ) . '

'; if (in_array('stockout_revenue', $locked, true)) { $this->render_locked_card( __( 'See How Much Stockouts Cost You', 'airf-restock-forecast' ), __( 'Understand the revenue impact of out-of-stock products and prioritize restocking by dollar value.', 'airf-restock-forecast' ), 'starter' ); } else { $revenue = $insights['stockout_revenue_loss'] ?? []; if (is_array($revenue) && !empty($revenue)) { $total_monthly = 0.0; $currency = ''; foreach ($revenue as $rd) { if (!is_array($rd)) continue; $total_monthly += (float) ($rd['monthly_loss'] ?? 0); if ($currency === '') $currency = (string) ($rd['currency'] ?? ''); } echo '
'; echo '
▼
'; echo '
'; echo '
' . esc_html($currency . ' ' . number_format($total_monthly, 0)) . '/mo
'; echo '
' . esc_html__( 'Total estimated revenue lost from stockouts', 'airf-restock-forecast' ) . '
'; echo '
'; echo '
'; echo ''; foreach ($revenue as $sku => $rd) { if (!is_array($rd)) continue; $out = !empty($rd['currently_out']); echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; } echo '
' . esc_html__( 'Product', 'airf-restock-forecast' ) . '' . esc_html__( 'Status', 'airf-restock-forecast' ) . '' . esc_html__( 'Daily Loss', 'airf-restock-forecast' ) . '' . esc_html__( 'Monthly Loss', 'airf-restock-forecast' ) . '
' . esc_html((string) ($rd['name'] ?? $sku)) . '' . ($out ? '' . esc_html__( 'Out of Stock', 'airf-restock-forecast' ) . '' : '' . esc_html__( 'In Stock', 'airf-restock-forecast' ) . '') . '' . esc_html($currency . ' ' . number_format((float) ($rd['daily_loss'] ?? 0), 2)) . '' . esc_html($currency . ' ' . number_format((float) ($rd['monthly_loss'] ?? 0), 0)) . '
'; } else { echo '
'; echo ''; echo '

' . esc_html__( 'No revenue loss data available. Ensure products have prices set.', 'airf-restock-forecast' ) . '

'; echo '
'; } } // ── Reorder Calendar (table) ── echo '

' . esc_html__( 'Reorder Calendar', 'airf-restock-forecast' ) . '

'; if (in_array('reorder_calendar', $locked, true)) { $this->render_locked_card( __( 'Optimal Reorder Calendar', 'airf-restock-forecast' ), __( 'See exactly when to place each supplier order, factoring in lead times and predicted demand.', 'airf-restock-forecast' ), 'starter' ); } else { $calendar = $insights['reorder_calendar'] ?? []; if (is_array($calendar) && !empty($calendar)) { echo ''; foreach ($calendar as $entry) { if (!is_array($entry)) continue; $urgency = (string) ($entry['urgency'] ?? 'ok'); $reorder_date = (string) ($entry['reorder_date'] ?? ''); $delivery_date = (string) ($entry['delivery_date'] ?? ''); $ts = strtotime($reorder_date); $dt = strtotime($delivery_date); echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; } echo '
' . esc_html__( 'Product', 'airf-restock-forecast' ) . '' . esc_html__( 'Order By', 'airf-restock-forecast' ) . '' . esc_html__( 'Delivery', 'airf-restock-forecast' ) . '' . esc_html__( 'Qty', 'airf-restock-forecast' ) . '' . esc_html__( 'Urgency', 'airf-restock-forecast' ) . '
' . esc_html((string) ($entry['name'] ?? '')) . '' . esc_html($ts ? wp_date('M j, Y', $ts) : $reorder_date) . '' . esc_html($dt ? wp_date('M j, Y', $dt) : $delivery_date) . '' . esc_html((string) ($entry['qty'] ?? 0)) . '' . esc_html($urgency) . '
'; } else { echo '
'; echo ''; echo '

' . esc_html__( 'No upcoming reorders needed based on current stock levels.', 'airf-restock-forecast' ) . '

'; echo '
'; } } // ── Demand Anomalies ── echo '

' . esc_html__( 'Demand Anomaly Alerts', 'airf-restock-forecast' ) . '

'; if (in_array('anomaly_alerts', $locked, true)) { $this->render_locked_card( __( 'Demand Anomaly Detection', 'airf-restock-forecast' ), __( 'Get alerted when product demand spikes or drops unexpectedly so you can react fast.', 'airf-restock-forecast' ), 'starter' ); } else { $anomalies = $insights['demand_anomalies'] ?? []; if (is_array($anomalies) && !empty($anomalies)) { echo ''; echo ''; foreach ($anomalies as $anomaly) { if (!is_array($anomaly)) continue; $type = (string) ($anomaly['type'] ?? 'spike'); $type = $type === 'drop' ? 'drop' : 'spike'; $message = (string) ($anomaly['message'] ?? ''); $type_icon = $type === 'spike' ? '▲' : '▼'; $type_label = $type === 'spike' ? __('Spike', 'airf-restock-forecast') : __('Drop', 'airf-restock-forecast'); echo ''; echo ''; echo ''; echo ''; } echo '
' . esc_html__( 'Type', 'airf-restock-forecast' ) . '' . esc_html__( 'Alert', 'airf-restock-forecast' ) . '
' . esc_html($type_label) . '' . esc_html($message) . '
'; } else { echo '
'; echo ''; echo '

' . esc_html__( 'No demand anomalies detected. All products are within normal ranges.', 'airf-restock-forecast' ) . '

'; echo '
'; } } // ── Seasonal Patterns ── echo '

' . esc_html__( 'Seasonal Patterns', 'airf-restock-forecast' ) . '

'; if (in_array('seasonal_patterns', $locked, true)) { $this->render_locked_card( __( 'Seasonal Demand Patterns', 'airf-restock-forecast' ), __( 'Identify recurring demand cycles and prepare inventory ahead of peak seasons.', 'airf-restock-forecast' ), 'growth' ); } else { $seasonal = $insights['seasonal_patterns'] ?? []; if (is_array($seasonal) && !empty($seasonal)) { // Product selector bar (carousel nav) echo '
'; echo ''; echo ''; echo ''; echo ''; echo '
'; // Render all panels; only first visible $si = 0; foreach ($seasonal as $sku => $pattern) { if (!is_array($pattern)) continue; echo '
0 ? ' style="display:none;"' : '') . '>'; echo '

' . esc_html((string) ($pattern['name'] ?? $sku)) . '

'; $s_meta = $this->resolve_product_meta((string) $sku); echo '

' . esc_html__( 'SKU:', 'airf-restock-forecast' ) . ' ' . wp_kses_post($this->render_sku_link((string) $sku, $s_meta['edit_url'])) . '

'; if (!empty($pattern['has_seasonality'])) { if (!empty($pattern['peak_months'])) { echo '

' . esc_html__( 'Peak months:', 'airf-restock-forecast' ) . ' ' . esc_html(implode(', ', array_map('ucfirst', $pattern['peak_months']))) . '

'; } if (!empty($pattern['low_months'])) { echo '

' . esc_html__( 'Low months:', 'airf-restock-forecast' ) . ' ' . esc_html(implode(', ', array_map('ucfirst', $pattern['low_months']))) . '

'; } if (!empty($pattern['monthly_index']) && is_array($pattern['monthly_index'])) { echo '
'; $month_abbr = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; $mi = 0; foreach ($pattern['monthly_index'] as $month => $idx) { $pct = min(100, max(10, (int) round((float) $idx * 50))); $idx_display = number_format((float) $idx, 2); echo '
'; echo '
' . esc_html($idx_display) . '
'; echo '
'; echo '
' . esc_html($month_abbr[$mi] ?? '') . '
'; echo '
'; $mi++; } echo '
'; echo '

' . esc_html__( '1.00 = average demand. Values above 1.00 indicate higher-than-average months; below 1.00 indicate lower-than-average months.', 'airf-restock-forecast' ) . '

'; } } else { echo '

' . esc_html__( 'No significant seasonal pattern detected.', 'airf-restock-forecast' ) . '

'; } echo '
'; $si++; } } else { echo '
'; echo ''; echo '

' . esc_html__( 'Seasonal patterns require 12+ months of data to detect.', 'airf-restock-forecast' ) . '

'; echo '
'; } } // ── Market Events ── echo '

' . esc_html__( 'Upcoming Market Events', 'airf-restock-forecast' ) . '

'; if (in_array('market_events', $locked, true)) { $this->render_locked_card( __( 'Market Events & Holidays', 'airf-restock-forecast' ), __( 'See upcoming holidays, seasonal sales, and cultural events from your customer countries that impact demand forecasts.', 'airf-restock-forecast' ), 'starter' ); } else { $market_events = $insights['market_events'] ?? []; if (is_array($market_events) && !empty($market_events)) { echo '
'; foreach ($market_events as $evt) { if (!is_array($evt)) continue; $cat = (string) ($evt['category'] ?? 'holiday'); $factor = (float) ($evt['demandFactor'] ?? 1); $pct = round(($factor - 1) * 100); $cat_icons = ['holiday' => '🎄', 'sale' => '🛒', 'cultural' => '🌍', 'seasonal' => '☀️']; $icon = $cat_icons[$cat] ?? '📅'; echo '
'; echo '' . wp_kses_post($icon) . ''; echo '
'; echo '' . esc_html((string) ($evt['name'] ?? '')) . ''; echo ''; echo esc_html((string) ($evt['date'] ?? '')) . ' · ' . esc_html((string) ($evt['country'] ?? '')); echo ''; echo '
'; if ($pct > 0) { /* translators: %s: percentage number */ echo '+' . esc_html((string) $pct) . '% ' . esc_html__( 'demand', 'airf-restock-forecast' ) . ''; } echo '
'; } echo '
'; } else { echo '
'; echo ''; echo '

' . esc_html__( 'No upcoming market events. Add customer countries in Settings to see holidays and sales events that affect demand.', 'airf-restock-forecast' ) . '

'; echo '
'; } } // ── Export ── echo '
'; echo '

' . esc_html__( 'Export & Reports', 'airf-restock-forecast' ) . '

'; if (in_array('export', $locked, true)) { $this->render_locked_card( __( 'Export Your Forecast Data', 'airf-restock-forecast' ), __( 'Download CSV reports and generate supplier-ready order forms.', 'airf-restock-forecast' ), 'starter' ); } else { echo '
'; echo ''; echo ''; if (!in_array('supplier_report', $locked, true)) { echo ''; } elseif (AIRF_BILLING_ENABLED) { $billing_cta = $this->get_billing_cta('growth'); echo ' ' . esc_html__( 'Supplier Report', 'airf-restock-forecast' ) . ' — ' . esc_html($billing_cta['label']) . ''; } echo '
'; } echo '
'; // .airf-export-section } private function render_locked_card(string $title, string $description, string $min_plan): void { $billing_cta = $this->get_billing_cta($min_plan); echo '
'; echo ''; echo '
'; echo '

' . esc_html($title) . '

'; echo '

' . esc_html($description) . '

'; if (AIRF_BILLING_ENABLED) { echo '' . esc_html($billing_cta['label']) . ''; } echo '
'; echo '
'; } private function render_settings_tab(): void { $plan_meta = get_option(AIRF_OPTION_PLAN_META, []); $settings = $this->get_settings(); $plan = is_array($plan_meta) ? ($plan_meta['plan'] ?? 'unknown') : 'unknown'; $quota = is_array($plan_meta) ? (int) ($plan_meta['monthly_quota'] ?? 0) : 0; $credits_used = is_array($plan_meta) ? (int) ($plan_meta['calls_used'] ?? 0) : 0; $site_token = get_option(AIRF_OPTION_SITE_TOKEN, ''); $domain = wp_parse_url(home_url(), PHP_URL_HOST); // Plan & Account echo '
'; echo '

' . esc_html__( 'Plan & Account', 'airf-restock-forecast' ) . '

'; echo '
'; echo '

' . esc_html__( 'Plan:', 'airf-restock-forecast' ) . ' ' . esc_html(ucfirst($plan)) . '

'; echo '
'; wp_nonce_field('airf_force_plan_sync'); echo ''; echo ''; echo '
'; echo '
'; /* translators: 1: credits used, 2: total quota */ echo '

' . sprintf( esc_html__( 'Credits: %1$s / %2$s used this month', 'airf-restock-forecast' ), esc_html((string) $credits_used), esc_html((string) $quota) ) . '

'; if (AIRF_BILLING_ENABLED) { $billing_url = $this->is_paid_plan($plan) ? AIRF_POLAR_PORTAL_URL : $this->get_checkout_url('starter'); $billing_label = $this->is_paid_plan($plan) ? __( 'Open billing portal', 'airf-restock-forecast' ) : __( 'View plan options', 'airf-restock-forecast' ); echo ''; } echo '
'; // Shared form: auto-analysis + digest echo '
'; wp_nonce_field('airf_update_settings'); echo ''; // ── Auto Analysis Schedule ── $days_labels = [ 'monday' => 'Mo', 'tuesday' => 'Tu', 'wednesday' => 'We', 'thursday' => 'Th', 'friday' => 'Fr', 'saturday' => 'Sa', 'sunday' => 'Su', ]; $enabled = $settings['auto_analysis_enabled']; $sel_days = $settings['auto_analysis_days']; $sel_time = esc_attr($settings['auto_analysis_time']); // Compute next run label $next_run_label = ''; if ($enabled) { $parts = explode(':', $settings['auto_analysis_time']); $hour = max(0, min(23, (int) ($parts[0] ?? 8))); $minute = max(0, min(59, (int) ($parts[1] ?? 0))); $tz = wp_timezone(); $now = new \DateTimeImmutable('now', $tz); foreach (range(0, 13) as $offset) { $candidate = $now->modify("+{$offset} day")->setTime($hour, $minute, 0); if ($candidate > $now) { $day_name = strtolower((string) $candidate->format('l')); if (in_array($day_name, $sel_days, true)) { $next_run_label = $candidate->format('D, M j') . ' at ' . $candidate->format('g:i A'); break; } } } } echo '
'; echo '

' . esc_html__( 'Auto Analysis', 'airf-restock-forecast' ) . '

'; echo ''; echo '
'; echo '

' . esc_html__( 'Run on', 'airf-restock-forecast' ) . '

'; echo '
'; foreach ($days_labels as $val => $label) { $is_checked = in_array($val, $sel_days, true); echo ''; } echo '
'; echo '
'; echo ''; echo ''; echo '
'; if ($next_run_label !== '') { echo '

⏰ ' . esc_html__( 'Next run:', 'airf-restock-forecast' ) . ' ' . esc_html($next_run_label) . '

'; } echo '
'; echo '
'; // ── Email Digest ── echo '

' . esc_html__( 'Email Digest', 'airf-restock-forecast' ) . '

'; echo ''; echo '
'; echo '
'; echo '
'; // ── Customer Base Countries ── $this->render_country_picker_card(); // Site Info echo '
'; echo '

' . esc_html__( 'Site Info', 'airf-restock-forecast' ) . '

'; echo '
'; $is_registered = is_string($site_token) && strlen($site_token) > 6; $recovery_email = get_option(AIRF_OPTION_VERIFICATION_EMAIL, ''); if (!$recovery_email) { // Fallback for sites registered before the email-verification flow $recovery_email = get_bloginfo('admin_email'); } $status_color = $is_registered ? '#46b450' : '#d63638'; $status_label = $is_registered ? __( 'Registered', 'airf-restock-forecast' ) : __( 'Not registered', 'airf-restock-forecast' ); echo '

' . esc_html__( 'Status:', 'airf-restock-forecast' ) . ' ' . esc_html($status_label) . '

'; echo '

' . esc_html__( 'Recovery email:', 'airf-restock-forecast' ) . ' ' . esc_html((string) $recovery_email) . '

'; if ($is_registered) { echo '

' . esc_html__( 'Token:', 'airf-restock-forecast' ) . ' …' . esc_html(substr($site_token, -6)) . '

'; } echo '

' . esc_html__( 'Domain:', 'airf-restock-forecast' ) . ' ' . esc_html((string) $domain) . '

'; echo '

' . esc_html__( 'Plugin version:', 'airf-restock-forecast' ) . ' ' . esc_html(AIRF_VERSION) . '

'; echo '
'; echo '

' . wp_kses( __('Plugin documentation & support', 'airf-restock-forecast'), ['a' => ['href' => [], 'target' => [], 'rel' => []]] ) . '

'; echo '
'; } private function render_country_picker_card(): void { $plan_meta = get_option(AIRF_OPTION_PLAN_META, []); $plan = is_array($plan_meta) ? ($plan_meta['plan'] ?? 'free') : 'free'; $site_token = get_option(AIRF_OPTION_SITE_TOKEN, ''); $show_cached_notice = false; // Plan limits for countries $max_countries = ['free' => 0, 'starter' => 6, 'growth' => 15]; $limit = $max_countries[$plan] ?? 0; if ($limit === 0) { echo '
'; echo '

' . esc_html__( 'Customer Base Countries', 'airf-restock-forecast' ) . '

'; echo '

' . esc_html__( 'Select the countries where your customers are based. Upcoming holidays, seasonal sales, and cultural events from those markets are used to refine demand forecasts.', 'airf-restock-forecast' ) . '

'; $url = $this->get_checkout_url('starter'); $label = __( 'View plan options', 'airf-restock-forecast' ); echo '
'; echo ' '; if (AIRF_BILLING_ENABLED) { echo '' . esc_html($label) . ''; } else { echo '' . esc_html__( 'Available on Starter plan and above.', 'airf-restock-forecast' ) . ''; } echo '
'; echo '
'; return; } // Fetch saved countries from API $saved_countries = []; if (is_string($site_token) && $site_token !== '') { $resp = $this->api_client->get_customer_countries($site_token); if ($resp['ok'] && is_array($resp['data']) && is_array($resp['data']['countries'] ?? null)) { $saved_countries = $resp['data']['countries'] ?? []; update_option(AIRF_OPTION_CACHED_COUNTRIES, $saved_countries, false); } else { $cached = get_option(AIRF_OPTION_CACHED_COUNTRIES, []); $saved_countries = is_array($cached) ? $cached : []; $show_cached_notice = true; } } else { $cached = get_option(AIRF_OPTION_CACHED_COUNTRIES, []); $saved_countries = is_array($cached) ? $cached : []; } if (!is_array($saved_countries)) { $saved_countries = []; } // Get the full WooCommerce country list $all_countries = function_exists('WC') && WC()->countries ? WC()->countries->get_countries() : []; echo '
'; echo '

' . esc_html__( 'Customer Base Countries', 'airf-restock-forecast' ) . '

'; echo '

' . wp_kses( sprintf( /* translators: %s: maximum number of countries wrapped in */ __( 'Select up to %s countries. Events, holidays, and sales seasons from those markets refine your demand forecast.', 'airf-restock-forecast' ), esc_html((string) $limit) ), ['strong' => []] ) . '

'; if ($show_cached_notice) { echo '
'; echo '

' . esc_html__( 'Could not load the latest countries from API. Showing cached values.', 'airf-restock-forecast' ) . '

'; echo '
'; } echo '
'; wp_nonce_field('airf_update_countries'); echo ''; // Selected tags echo '
'; foreach ($saved_countries as $cc) { $cc = strtoupper(sanitize_text_field($cc)); $name = isset($all_countries[$cc]) ? $all_countries[$cc] : $cc; echo ''; echo esc_html($name); echo ''; echo ''; echo ''; } echo '
'; // Dropdown to add echo '
'; echo ''; echo '' . esc_html(count($saved_countries) . ' / ' . $limit) . ''; echo '
'; if ($plan === 'starter' && AIRF_BILLING_ENABLED) { $growth_cta = $this->get_billing_cta('growth'); echo '

' . esc_html__( 'Need more than 6 countries?', 'airf-restock-forecast' ) . ' ' . esc_html($growth_cta['label']) . '

'; } echo '
'; echo '
'; echo '
'; } public function handle_update_countries(): void { if (!current_user_can('manage_woocommerce')) { wp_die( esc_html__( 'Permission denied.', 'airf-restock-forecast' ) ); } check_admin_referer('airf_update_countries'); $site_token = get_option(AIRF_OPTION_SITE_TOKEN, ''); if (!is_string($site_token) || $site_token === '') { wp_safe_redirect(admin_url('admin.php?page=airf-restock-forecast&tab=settings')); exit; } $raw = []; if (isset($_POST['airf_countries']) && is_array($_POST['airf_countries'])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- check_admin_referer('airf_update_countries') verified above. $raw = map_deep(wp_unslash($_POST['airf_countries']), 'sanitize_text_field'); } $countries = []; foreach ($raw as $cc) { $clean = strtoupper(sanitize_text_field($cc)); if (preg_match('/^[A-Z]{2}$/', $clean) && !in_array($clean, $countries, true)) { $countries[] = $clean; } } // Server-side will enforce plan limit $result = $this->api_client->update_customer_countries($site_token, $countries); if ($result['ok']) { update_option(AIRF_OPTION_CACHED_COUNTRIES, $countries, false); $notice = 'countries_saved'; } elseif ($this->is_timeout_result($result)) { $notice = 'countries_save_timeout'; } else { $notice = 'countries_save_failed'; } wp_safe_redirect(add_query_arg('airf_notice', $notice, admin_url('admin.php?page=airf-restock-forecast&tab=settings'))); exit; } public function handle_force_plan_sync(): void { if (!current_user_can('manage_woocommerce')) { wp_die( esc_html__( 'Permission denied.', 'airf-restock-forecast' ) ); } check_admin_referer('airf_force_plan_sync'); $site_token = get_option(AIRF_OPTION_SITE_TOKEN, ''); if (!is_string($site_token) || $site_token === '') { wp_safe_redirect(admin_url('admin.php?page=airf-restock-forecast&tab=settings')); exit; } $result = $this->api_client->get_plan_status($site_token); if ($result['ok'] && is_array($result['data'])) { update_option(AIRF_OPTION_PLAN_META, $result['data'], false); // Re-fetch cached analysis with new plan gating so insights reflect instantly $cached = $this->api_client->get_cached_analysis($site_token); if ($cached['ok'] && is_array($cached['data']) && empty($cached['data']['empty'])) { update_option(AIRF_OPTION_LAST_RESULT, $cached['data'], false); } } wp_safe_redirect(admin_url('admin.php?page=airf-restock-forecast&tab=settings')); exit; } public function handle_run_analysis_now(): void { if (!current_user_can('manage_woocommerce')) { wp_die( esc_html__( 'Permission denied.', 'airf-restock-forecast' ) ); } check_admin_referer('airf_run_analysis_now'); $status = $this->run_analysis_with_lock(); if ($status === null) { $status = ['ok' => false, 'notice' => 'analysis_failed']; } $notice = isset($status['notice']) ? $status['notice'] : 'analysis_failed'; wp_safe_redirect(add_query_arg('airf_notice', $notice, admin_url('admin.php?page=airf-restock-forecast'))); exit; } public function handle_update_settings(): void { if (!current_user_can('manage_woocommerce')) { wp_die( esc_html__( 'Permission denied.', 'airf-restock-forecast' ) ); } check_admin_referer('airf_update_settings'); $settings = $this->get_settings(); $weekly_digest_raw = isset($_POST['airf_weekly_digest_enabled']) ? sanitize_text_field(wp_unslash($_POST['airf_weekly_digest_enabled'])) : ''; $settings['weekly_digest_enabled'] = $weekly_digest_raw === '1'; // Auto-analysis schedule $settings['auto_analysis_enabled'] = !empty($_POST['airf_auto_analysis_enabled']); $valid_days = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday']; $days_raw = []; if (isset($_POST['airf_auto_analysis_days']) && is_array($_POST['airf_auto_analysis_days'])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- check_admin_referer('airf_update_settings') verified above. $days_raw = map_deep(wp_unslash($_POST['airf_auto_analysis_days']), 'sanitize_text_field'); } $days_clean = array_values(array_intersect(array_map(static function ($day): string { return sanitize_text_field((string) $day); }, $days_raw), $valid_days)); $settings['auto_analysis_days'] = !empty($days_clean) ? $days_clean : ['monday']; $time_raw = isset($_POST['airf_auto_analysis_time']) ? sanitize_text_field(wp_unslash($_POST['airf_auto_analysis_time'])) : '08:00'; $settings['auto_analysis_time'] = preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $time_raw) ? $time_raw : '08:00'; update_option(AIRF_OPTION_SETTINGS, $settings, false); $this->reschedule_auto_analysis($settings); wp_safe_redirect(admin_url('admin.php?page=airf-restock-forecast&tab=settings')); exit; } private function reschedule_auto_analysis(array $settings): void { wp_clear_scheduled_hook('airf_auto_analysis_check'); if (empty($settings['auto_analysis_enabled'])) { return; } $parts = explode(':', $settings['auto_analysis_time']); $hour = max(0, min(23, (int) ($parts[0] ?? 8))); $minute = max(0, min(59, (int) ($parts[1] ?? 0))); $tz = wp_timezone(); $now = new \DateTimeImmutable('now', $tz); $target = $now->setTime($hour, $minute, 0); if ($target <= $now) { $target = $target->modify('+1 day'); } wp_schedule_event($target->getTimestamp(), 'daily', 'airf_auto_analysis_check'); } public function ensure_auto_analysis_schedule(): void { // Frontend/admin traffic fallback for timeout reconciliation when cron is delayed. $this->maybe_run_timeout_reconcile_fallback(); $this->maybe_recover_stuck_running_job(); $settings = $this->get_settings(); $next = wp_next_scheduled('airf_auto_analysis_check'); if (empty($settings['auto_analysis_enabled'])) { if ($next !== false) { wp_clear_scheduled_hook('airf_auto_analysis_check'); } return; } if ($next === false) { $this->reschedule_auto_analysis($settings); } } public function run_auto_analysis_check(): void { $settings = $this->get_settings(); if (empty($settings['auto_analysis_enabled'])) { return; } $today = strtolower((string) wp_date('l')); if (!in_array($today, $settings['auto_analysis_days'], true)) { return; } $this->run_scheduled_analysis(); } public function run_nightly_analysis(): void { $settings = $this->get_settings(); if (!empty($settings['auto_analysis_enabled'])) { return; } $this->run_scheduled_analysis(); } public function run_retry_analysis(): void { $this->run_scheduled_analysis(); } private function run_analysis_internal(): array { if (!class_exists('WooCommerce')) { return ['ok' => false, 'notice' => 'analysis_failed']; } $site_token = get_option(AIRF_OPTION_SITE_TOKEN, ''); if (!is_string($site_token) || $site_token === '') { return ['ok' => false, 'notice' => 'site_not_registered']; } $this->sync_plan(); $payload = $this->build_analysis_payload(); if (empty($payload['products'])) { update_option(AIRF_OPTION_LAST_STATUS, ['no_products' => true], false); return ['ok' => false, 'notice' => 'missing_products']; } $existing_result = get_option(AIRF_OPTION_LAST_RESULT, []); $baseline_generated_at = is_array($existing_result) ? (string) ($existing_result['generated_at'] ?? '') : ''; $analysis_started_at = time(); // Heartbeat before HTTP call so the watchdog knows we got past payload build. $job_status = get_option(AIRF_OPTION_JOB_STATUS, []); if (is_array($job_status) && ($job_status['state'] ?? '') === 'running') { $job_status['last_heartbeat_at'] = $analysis_started_at; update_option(AIRF_OPTION_JOB_STATUS, $job_status, false); } $this->airf_log('analyze_call', ['products' => count($payload['products'] ?? [])]); $result = $this->api_client->analyze_store($site_token, $payload); if (!$result['ok'] || !is_array($result['data'])) { if ((int) ($result['status'] ?? 0) === 429) { update_option(AIRF_OPTION_LAST_STATUS, ['quota_exceeded' => true], false); return ['ok' => false, 'notice' => 'quota_exceeded']; } // If transport timed out, the API may still have finalized successfully. // Re-sync plan and fetch cached analysis to recover without showing a false failure. if ($this->is_timeout_result($result)) { if ($this->reconcile_after_timeout($site_token, $baseline_generated_at, $analysis_started_at)) { return ['ok' => true, 'notice' => 'analysis_success']; } return [ 'ok' => false, 'notice' => 'analysis_retrying', 'analysis_started_at' => $analysis_started_at, 'baseline_generated_at' => $baseline_generated_at, ]; } // Stale token or drifted signing_secret: attempt HMAC re-registration // once and retry the analysis. if ( ((int) ($result['status'] ?? 0) === 401 && ($result['code'] ?? '') === 'invalid_site_token') || ((int) ($result['status'] ?? 0) === 403 && ($result['code'] ?? '') === 'invalid_signature') ) { $result = $this->handle_stale_token_and_retry($payload); if ($result === null) { return ['ok' => false, 'notice' => 'token_invalid']; } if (!$result['ok'] || !is_array($result['data'])) { return ['ok' => false, 'notice' => 'analysis_failed']; } // Fall through: $result now contains the fresh response. } else { $this->sync_plan(true); return ['ok' => false, 'notice' => 'analysis_failed']; } } if (!empty($result['data']['low_confidence'])) { update_option( AIRF_OPTION_LAST_STATUS, [ 'low_confidence' => true, 'check_back_date' => (string) ($result['data']['check_back_date'] ?? ''), ], false ); $this->advance_rotation_offset(); return ['ok' => true, 'notice' => 'low_confidence']; } update_option(AIRF_OPTION_LAST_RESULT, $result['data'], false); update_option('airf_last_analysis_date', gmdate('Y-m-d'), false); update_option( AIRF_OPTION_LAST_STATUS, [ 'stale' => !empty($result['data']['stale']), 'stale_generated_at' => (string) ($result['data']['stale_generated_at'] ?? ''), 'low_confidence' => false, ], false ); if (isset($result['data']['calls_used_after_request']) && is_array(get_option(AIRF_OPTION_PLAN_META, []))) { $plan_meta = get_option(AIRF_OPTION_PLAN_META, []); if (is_array($plan_meta)) { $plan_meta['calls_used'] = (int) $result['data']['calls_used_after_request']; update_option(AIRF_OPTION_PLAN_META, $plan_meta, false); } } $this->advance_rotation_offset(); return ['ok' => true, 'notice' => 'analysis_success']; } /** * Called when the API returns 401 invalid_site_token during a background analysis. * Attempts HMAC re-registration to refresh the site token, then retries the analysis. * Returns null if re-registration fails (cross-instance recovery — admin must re-verify). * * @param array $payload The analysis payload already built for re-use on retry. * @return array|null API response from the retry, or null if re-registration failed. */ private function handle_stale_token_and_retry(array $payload): ?array { $reg = $this->api_client->register_site(); if (!$reg['ok'] || !is_array($reg['data'])) { // HMAC secret is also stale (e.g. another WP instance did a full recovery). // Clear the token so the admin is prompted to re-register via email verification. delete_option(AIRF_OPTION_SITE_TOKEN); return null; } $this->save_registration_response($reg['data']); $new_token = get_option(AIRF_OPTION_SITE_TOKEN, ''); if (!is_string($new_token) || $new_token === '') { return null; } return $this->api_client->analyze_store($new_token, $payload); } private function build_analysis_payload(): array { global $wpdb; // Step 1 — Aggregate sales rollup (cheap SQL). Returns one row per (item, month). $aggregate_started_at = microtime(true); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Aggregated reporting query across lookup table. $product_rows = $wpdb->get_results( " SELECT CASE WHEN variation_id > 0 THEN variation_id ELSE product_id END AS item_id, DATE_FORMAT(date_created, '%Y-%m') AS sales_month, SUM(product_qty) AS total_qty FROM {$wpdb->prefix}wc_order_product_lookup GROUP BY item_id, sales_month ", ARRAY_A ); $aggregate_ms = (int) round((microtime(true) - $aggregate_started_at) * 1000); if (!is_array($product_rows)) { $product_rows = []; } $row_count = count($product_rows); $this->airf_log('payload_aggregate', [ 'rows' => $row_count, 'ms' => $aggregate_ms, ]); // Group by item_id and compute lifetime totals — all in PHP arrays (no product loads yet). $sales_by_product = []; $lifetime_totals = []; foreach ($product_rows as $row) { $item_id = (int) ($row['item_id'] ?? 0); $sales_month = (string) ($row['sales_month'] ?? ''); $total_qty = max(0, (int) ($row['total_qty'] ?? 0)); if ($item_id <= 0 || $sales_month === '') { continue; } if (!isset($sales_by_product[$item_id])) { $sales_by_product[$item_id] = []; $lifetime_totals[$item_id] = 0; } $sales_by_product[$item_id][$sales_month] = $total_qty; $lifetime_totals[$item_id] += $total_qty; } // Free the raw row buffer early — for 26k+ stores this can be megabytes. unset($product_rows); // Step 2 — Plan-aware truncation BEFORE loading any product objects. $plan_meta = get_option(AIRF_OPTION_PLAN_META, []); $max_products_per_run = is_array($plan_meta) ? (int) ($plan_meta['max_products_per_analysis'] ?? 5) : 5; $hard_ceiling = max(1, (int) apply_filters('airf_max_products_per_run_ceiling', 300)); $max_products_per_run = max(1, min($max_products_per_run, $hard_ceiling)); $selected_item_ids = $this->select_items_for_analysis($lifetime_totals, $max_products_per_run); // Stash a rotation hint so the offset can be advanced ONLY after a // successful API call (transient: 1 h is plenty for one analysis cycle). $remaining_count = max(0, count($lifetime_totals) - ($max_products_per_run - max(0, (int) floor($max_products_per_run * 0.25)))); $rotation_slots = (count($lifetime_totals) > $max_products_per_run) ? max(0, (int) floor($max_products_per_run * 0.25)) : 0; if ($remaining_count > 0 && $rotation_slots > 0) { set_transient('airf_rotation_hint', ['count' => $remaining_count, 'slots' => $rotation_slots], HOUR_IN_SECONDS); } else { delete_transient('airf_rotation_hint'); } $this->airf_log('payload_select', [ 'total_items' => count($lifetime_totals), 'selected' => count($selected_item_ids), 'cap' => $max_products_per_run, ]); unset($lifetime_totals); // Step 3 — Bulk-prime caches for the selected ids (one query each instead of N+1). if (!empty($selected_item_ids)) { // Include parent ids for SKU/lead-day inheritance look-ups. $parent_ids = []; foreach ($selected_item_ids as $iid) { $pid = (int) wp_get_post_parent_id($iid); if ($pid > 0) { $parent_ids[$pid] = true; } } $prime_ids = array_values(array_unique(array_merge($selected_item_ids, array_keys($parent_ids)))); if (function_exists('_prime_post_caches')) { // Skip term-cache priming — payload doesn't use product taxonomies and // priming categories/attributes for hundreds of ids is the dominant // memory cost on taxonomy-heavy stores. Meta priming is enabled here // (third arg true), so a separate update_meta_cache() call is // intentionally omitted. _prime_post_caches($prime_ids, false, true); } else { update_meta_cache('post', $prime_ids); } } // Step 4 — Build the products array using the in-memory aggregates. $products = []; foreach ($selected_item_ids as $item_id) { $product = wc_get_product($item_id); if (!$product) { continue; } // Skip parent variable products \u2014 only analyze concrete items. if ($product->is_type('variable')) { continue; } // Build a unique SKU: prefer variation SKU, fall back to parent SKU + suffix. $sku = (string) $product->get_sku(); if ($sku === '') { $parent_id = $product->get_parent_id(); if ($parent_id) { $parent = wc_get_product($parent_id); $parent_sku = $parent ? (string) $parent->get_sku() : ''; $sku = $parent_sku !== '' ? $parent_sku . '-v' . $item_id : 'v-' . $item_id; } else { $sku = 'p-' . $item_id; } } // Inherit supplier lead days from parent if not set on variation. $lead_days = (int) get_post_meta($item_id, '_airf_supplier_lead_days', true); if (!$lead_days && $product->get_parent_id()) { $lead_days = (int) get_post_meta($product->get_parent_id(), '_airf_supplier_lead_days', true); } $history = $sales_by_product[$item_id] ?? []; $products[] = [ 'sku' => $sku, 'name' => (string) $product->get_name(), 'current_stock' => max(0, (int) $product->get_stock_quantity()), 'price' => (float) $product->get_price(), 'sales_history' => $history, 'last_restock_date' => null, 'supplier_lead_days' => $lead_days ?: 14, ]; } unset($sales_by_product); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Single aggregate date query for payload metadata. $earliest_order_date = (string) $wpdb->get_var( " SELECT DATE(MIN(date_created)) FROM {$wpdb->prefix}wc_order_product_lookup " ); if ($earliest_order_date === '') { $earliest_order_date = gmdate('Y-m-d'); } $last_analysis_date = get_option('airf_last_analysis_date', ''); return [ 'store' => [ 'locale' => get_locale(), 'country' => wc_get_base_location()['country'] ?? 'SE', 'currency' => get_woocommerce_currency(), 'timezone' => wp_timezone_string(), ], 'analysis_date' => gmdate('Y-m-d'), 'earliest_order_date' => $earliest_order_date, 'last_analysis_date' => is_string($last_analysis_date) && $last_analysis_date !== '' ? $last_analysis_date : null, 'products' => $products, ]; } /** * Choose the set of item ids to analyze. Top sellers are always included; the * remainder rotates through a slice so smaller-volume items are revisited over time. * * NOTE: this method does NOT advance `airf_rotation_offset`. The caller advances * the offset only after a successful API call — otherwise repeated transient * failures would silently skip parts of the catalogue. * * @param array $lifetime_totals Map of item_id => lifetime quantity sold. * @return array Ordered list of item_ids (top sellers first, then rotated tail). */ private function select_items_for_analysis(array $lifetime_totals, int $max_products_per_run): array { if (empty($lifetime_totals)) { return []; } // Sort by lifetime quantity desc; ties broken by id for determinism. arsort($lifetime_totals, SORT_NUMERIC); $ranked_ids = array_keys($lifetime_totals); if (count($ranked_ids) <= $max_products_per_run) { return array_map('intval', $ranked_ids); } $rotation_slots = max(0, (int) floor($max_products_per_run * 0.25)); $fixed_slots = $max_products_per_run - $rotation_slots; $fixed_ids = array_slice($ranked_ids, 0, $fixed_slots); $remaining_ids = array_slice($ranked_ids, $fixed_slots); if ($rotation_slots <= 0 || empty($remaining_ids)) { return array_map('intval', $fixed_ids); } $offset = (int) get_option('airf_rotation_offset', 0); $rotated = []; $count = count($remaining_ids); for ($i = 0; $i < $rotation_slots; $i++) { $rotated[] = $remaining_ids[($offset + $i) % $count]; } return array_map('intval', array_merge($fixed_ids, $rotated)); } /** * Advance the rotation offset. Called only after a successful API analysis so * that transient failures do not skip parts of the catalogue. */ private function advance_rotation_offset(): void { global $wpdb; // Recompute the same `count` and `rotation_slots` the selector used. We // store enough state in transient to do this without re-running aggregates. $hint = get_transient('airf_rotation_hint'); if (!is_array($hint) || empty($hint['count']) || empty($hint['slots'])) { return; } $count = max(1, (int) $hint['count']); $slots = max(0, (int) $hint['slots']); if ($slots <= 0) { return; } $offset = (int) get_option('airf_rotation_offset', 0); update_option('airf_rotation_offset', ($offset + $slots) % $count, false); delete_transient('airf_rotation_hint'); } public function render_supplier_lead_days_field(): void { woocommerce_wp_text_input([ 'id' => '_airf_supplier_lead_days', 'label' => __( 'Supplier lead time (days)', 'airf-restock-forecast' ), 'description' => __( 'Used in forecast urgency calculations sent to your API.', 'airf-restock-forecast' ), 'desc_tip' => true, 'type' => 'number', 'custom_attributes' => [ 'min' => 0, 'max' => 365, 'step' => 1, ], ]); } public function register_cron_schedules(array $schedules): array { if (!isset($schedules['weekly'])) { $schedules['weekly'] = [ 'interval' => 7 * DAY_IN_SECONDS, 'display' => __( 'Once Weekly', 'airf-restock-forecast' ), ]; } return $schedules; } public function save_supplier_lead_days_field($product): void { if (!isset($_POST['_airf_supplier_lead_days'])) { return; } $meta_nonce = isset($_POST['woocommerce_meta_nonce']) ? sanitize_text_field(wp_unslash($_POST['woocommerce_meta_nonce'])) : ''; if ($meta_nonce === '' || !wp_verify_nonce($meta_nonce, 'woocommerce_save_data')) { return; } $value = (int) sanitize_text_field(wp_unslash($_POST['_airf_supplier_lead_days'])); $value = max(0, min(365, $value)); $product->update_meta_data('_airf_supplier_lead_days', $value); } public function send_weekly_digest(): void { $settings = $this->get_settings(); if (empty($settings['weekly_digest_enabled'])) { return; } $last_result = get_option(AIRF_OPTION_LAST_RESULT, []); if (!is_array($last_result) || empty($last_result['recommendations']) || !is_array($last_result['recommendations'])) { return; } $to = get_option('admin_email'); if (!is_email($to)) { return; } $rows = ''; $recommendations = array_slice($last_result['recommendations'], 0, 12); foreach ($recommendations as $item) { if (!is_array($item)) { continue; } $rows .= ''; $rows .= '' . esc_html((string) ($item['name'] ?? 'Unknown')) . ''; $rows .= '' . esc_html((string) ($item['urgency'] ?? 'n/a')) . ''; $rows .= '' . esc_html((string) ($item['suggested_reorder_qty'] ?? 'n/a')) . ''; $rows .= '' . esc_html((string) ($item['reasoning'] ?? '')) . ''; $rows .= ''; } if ($rows === '') { return; } $summary = esc_html((string) ($last_result['summary'] ?? 'Your latest weekly forecast digest.')); $generated_at = esc_html((string) ($last_result['generated_at'] ?? gmdate('Y-m-d'))); $subject = __( 'AIRF Restock Forecast Digest', 'airf-restock-forecast' ); $message = '

' . esc_html__( 'AIRF Weekly Restock Forecast', 'airf-restock-forecast' ) . '

'; $message .= '

' . esc_html__( 'Generated:', 'airf-restock-forecast' ) . ' ' . $generated_at . '

'; $message .= '

' . $summary . '

'; $message .= ''; $message .= ''; $message .= ''; $message .= ''; $message .= ''; $message .= ''; $message .= '' . $rows . '
' . esc_html__( 'Product', 'airf-restock-forecast' ) . '' . esc_html__( 'Urgency', 'airf-restock-forecast' ) . '' . esc_html__( 'Suggested Qty', 'airf-restock-forecast' ) . '' . esc_html__( 'Reason', 'airf-restock-forecast' ) . '
'; wp_mail($to, $subject, $message, ['Content-Type: text/html; charset=UTF-8']); } private function get_current_plan(): string { $plan_meta = get_option(AIRF_OPTION_PLAN_META, []); return is_array($plan_meta) ? (string) ($plan_meta['plan'] ?? 'free') : 'free'; } private function is_paid_plan(string $plan): bool { return in_array($plan, ['starter', 'growth'], true); } private function get_billing_cta(string $upgrade_plan = 'starter'): array { $current_plan = $this->get_current_plan(); if ($upgrade_plan === 'growth' && $current_plan !== 'growth') { return [ 'url' => $this->get_checkout_url('growth'), 'label' => __( 'View GROWTH plan', 'airf-restock-forecast' ), ]; } if ($this->is_paid_plan($current_plan)) { return [ 'url' => $this->get_safe_billing_url(AIRF_POLAR_PORTAL_URL), 'label' => __( 'Open billing portal', 'airf-restock-forecast' ), ]; } return [ 'url' => $this->get_checkout_url($upgrade_plan), 'label' => __( 'View plan options', 'airf-restock-forecast' ), ]; } private function get_checkout_url(string $plan): string { $base = $plan === 'growth' ? AIRF_POLAR_GROWTH_CHECKOUT_URL : AIRF_POLAR_STARTER_CHECKOUT_URL; $base = $this->get_safe_billing_url($base); $token = get_option(AIRF_OPTION_SITE_TOKEN, ''); $args = [ 'return_url' => admin_url('admin.php?page=airf-restock-forecast'), ]; if (is_string($token) && $token !== '') { // Always attach the site token so Polar upgrades are tied to the correct site. $args['reference_id'] = $token; } return add_query_arg($args, $base); } private function get_safe_billing_url(string $url): string { $safe_url = trim($url); if ($safe_url !== '') { return $safe_url; } // Submission-safe fallback when billing URLs are not configured. return $this->get_plans_page_url(); } private function get_plans_page_url(): string { $url = defined('AIRF_PRODUCT_PAGE_URL') ? AIRF_PRODUCT_PAGE_URL : ''; if (!is_string($url) || trim($url) === '') { $url = AIRF_SITE_BASE_URL . '/plugin/airf'; } return $url; } private function get_settings(): array { $stored = get_option(AIRF_OPTION_SETTINGS, []); if (!is_array($stored)) { $stored = []; } $valid_days = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday']; $stored_days = isset($stored['auto_analysis_days']) && is_array($stored['auto_analysis_days']) ? $stored['auto_analysis_days'] : ['monday']; $stored_days = array_values(array_intersect($stored_days, $valid_days)); return [ 'weekly_digest_enabled' => isset($stored['weekly_digest_enabled']) ? (bool) $stored['weekly_digest_enabled'] : true, 'auto_analysis_enabled' => isset($stored['auto_analysis_enabled']) ? (bool) $stored['auto_analysis_enabled'] : false, 'auto_analysis_days' => !empty($stored_days) ? $stored_days : ['monday'], 'auto_analysis_time' => (isset($stored['auto_analysis_time']) && preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $stored['auto_analysis_time'])) ? $stored['auto_analysis_time'] : '08:00', ]; } private function normalize_abc_category(string $category): string { $normalized = strtoupper($category); return in_array($normalized, ['A', 'B', 'C'], true) ? $normalized : ''; } private function render_abc_summary_card(array $insights, array $plan_gates): void { $summary = is_array($insights['abc_summary'] ?? null) ? $insights['abc_summary'] : []; if (empty($summary)) { return; } $primary_basis = (string) ($summary['primary_basis'] ?? 'revenue'); $counts = $primary_basis === 'velocity' ? (is_array($summary['velocity_category_counts'] ?? null) ? $summary['velocity_category_counts'] : []) : (is_array($summary['revenue_category_counts'] ?? null) ? $summary['revenue_category_counts'] : []); $shares = $primary_basis === 'velocity' ? (is_array($summary['velocity_share_by_category'] ?? null) ? $summary['velocity_share_by_category'] : []) : (is_array($summary['revenue_share_by_category'] ?? null) ? $summary['revenue_share_by_category'] : []); $total_products = (int) ($summary['total_products'] ?? 0); $basis_label = $primary_basis === 'velocity' ? __('unit velocity', 'airf-restock-forecast') : __('revenue contribution', 'airf-restock-forecast'); $locked = in_array('abc_detailed', $plan_gates['locked_features'] ?? [], true); echo '
'; echo '

' . esc_html__('ABC Inventory Classification', 'airf-restock-forecast') . '

'; echo '

' . esc_html__('Cumulative 80/15/5 split across your catalog.', 'airf-restock-forecast') . '

'; echo '
'; foreach (['A', 'B', 'C'] as $tier) { $count = (int) ($counts[$tier] ?? 0); $share = number_format((float) ($shares[$tier] ?? 0), 1); echo '
'; echo '' . esc_html($tier) . ''; echo '' . esc_html((string) $count) . ''; echo '' . esc_html($share) . '%'; echo '
'; } echo '
'; echo '

' . sprintf( /* translators: 1: primary ABC basis, 2: number of products */ esc_html__('Primary basis: %1$s · Products analyzed: %2$s', 'airf-restock-forecast'), esc_html($basis_label), esc_html((string) $total_products) ) . '

'; if ($locked && AIRF_BILLING_ENABLED) { $billing_cta = $this->get_billing_cta('starter'); echo '

'; echo ' '; echo esc_html__('Per-product ABC details are available on Starter and Growth service plans.', 'airf-restock-forecast') . ' '; echo '' . sprintf( /* translators: %s: billing CTA label */ esc_html__('%s for plan details', 'airf-restock-forecast'), esc_html($billing_cta['label']) ) . ''; echo '

'; } echo '
'; } private function render_recommendations_table($last_result): void { if (!is_array($last_result) || empty($last_result['recommendations']) || !is_array($last_result['recommendations'])) { echo '

' . esc_html__( 'No recommendations yet. Run an analysis to see forecasts here.', 'airf-restock-forecast' ) . '

'; return; } $insights = is_array($last_result['insights'] ?? null) ? $last_result['insights'] : []; $plan_gates = is_array($last_result['plan_gates'] ?? null) ? $last_result['plan_gates'] : []; $abc_map = is_array($insights['abc_classification'] ?? null) ? $insights['abc_classification'] : []; $abc_locked = in_array('abc_detailed', $plan_gates['locked_features'] ?? [], true); $priority = ['critical' => 1, 'soon' => 2, 'monitor' => 3, 'ok' => 4]; $recommendations = $last_result['recommendations']; usort( $recommendations, static function ($a, $b) use ($priority) { $left = is_array($a) ? (string) ($a['urgency'] ?? 'ok') : 'ok'; $right = is_array($b) ? (string) ($b['urgency'] ?? 'ok') : 'ok'; return ($priority[$left] ?? 99) <=> ($priority[$right] ?? 99); } ); $filter_fields = $abc_locked ? 'search,urgency' : 'search,urgency,abc'; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; foreach ($recommendations as $item) { if (!is_array($item)) { continue; } $urgency = (string) ($item['urgency'] ?? 'ok'); $days = $item['days_until_stockout'] ?? null; $trend = (string) ($item['trend'] ?? 'stable'); $sku_rec = (string) ($item['sku'] ?? ''); $abc_entry = isset($abc_map[$sku_rec]) && is_array($abc_map[$sku_rec]) ? $abc_map[$sku_rec] : []; $abc_category = $this->normalize_abc_category((string) ($abc_entry['primary_category'] ?? '')); $stockout_text = $this->format_stockout_display( $days, $urgency, $item['suggested_reorder_qty'] ?? null ); $stockout_class = ''; if (($days !== null && (int) $days < 7) || ($days === null && $urgency === 'critical')) { $stockout_class = 'airf-stockout--critical'; } elseif ($days !== null && (int) $days < 21) { $stockout_class = 'airf-stockout--soon'; } $rec_meta = $this->resolve_product_meta($sku_rec); $abc_html = '—'; if ($abc_locked && AIRF_BILLING_ENABLED) { $abc_html = '' . esc_html__('Starter+', 'airf-restock-forecast') . ''; } elseif ($abc_category !== '') { $abc_html = '' . esc_html($abc_category) . ''; } $search_blob = strtolower( (string) ($item['name'] ?? '') . ' ' . $sku_rec . ' ' . (string) ($item['reasoning'] ?? '') ); echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; } echo '
' . esc_html__( 'Product', 'airf-restock-forecast' ) . '' . esc_html__( 'SKU', 'airf-restock-forecast' ) . '' . esc_html__( 'Stock', 'airf-restock-forecast' ) . '' . esc_html__( 'Urgency', 'airf-restock-forecast' ) . '' . esc_html__( 'ABC', 'airf-restock-forecast' ) . '' . esc_html__( 'Stockout', 'airf-restock-forecast' ) . '' . esc_html__( 'Reorder Qty', 'airf-restock-forecast' ) . '' . esc_html__( 'Trend', 'airf-restock-forecast' ) . '' . esc_html__( 'Reasoning', 'airf-restock-forecast' ) . '
' . esc_html((string) ($item['name'] ?? 'Unknown')) . '' . wp_kses_post($this->render_sku_link($sku_rec, $rec_meta['edit_url'])) . '' . esc_html($rec_meta['stock_display']) . '' . esc_html($urgency) . '' . wp_kses_post($abc_html) . '' . esc_html($stockout_text) . '' . esc_html((string) ($item['suggested_reorder_qty'] ?? 'n/a')) . '' . wp_kses_post($this->render_trend($trend)) . '' . esc_html((string) ($item['reasoning'] ?? '')) . '
'; } private function resolve_product_meta(string $sku): array { $default = ['edit_url' => '', 'stock' => null, 'stock_display' => 'n/a']; if ($sku === '') return $default; $product_id = wc_get_product_id_by_sku($sku); if (!$product_id) return $default; $product = wc_get_product($product_id); if (!$product) return $default; $edit_id = $product->get_parent_id() ?: $product_id; $edit_url = admin_url('post.php?post=' . $edit_id . '&action=edit'); $stock = $product->get_stock_quantity(); return [ 'edit_url' => $edit_url, 'stock' => $stock, 'stock_display' => $stock !== null ? (string) $stock : 'n/a', ]; } private function render_sku_link(string $sku, string $edit_url): string { if ($sku === '') return '—'; if ($edit_url !== '') { return '' . esc_html($sku) . ''; } return '' . esc_html($sku) . ''; } private function format_stockout_display($days, string $urgency, $suggestedQty): string { if ($days !== null && $days !== '') { /* translators: %d: number of days until stockout */ return sprintf( _n( '%d day', '%d days', (int) $days, 'airf-restock-forecast' ), (int) $days ); } if ($urgency === 'critical') { /* translators: zero days until stockout */ return sprintf( _n( '%d day', '%d days', 0, 'airf-restock-forecast' ), 0 ); } if ($urgency === 'ok' && (int) $suggestedQty === 0) { return __( 'No sales data', 'airf-restock-forecast' ); } return __( 'n/a', 'airf-restock-forecast' ); } private function render_trend(string $trend): string { $arrows = [ 'accelerating' => '▲', 'stable' => '▶', 'declining' => '▼', 'seasonal_peak_approaching' => '▴', ]; $label = str_replace('_', ' ', $trend); $arrow = $arrows[$trend] ?? '▶'; return '' . $arrow . ' ' . esc_html(ucfirst($label)) . ''; } private function render_sparkline(array $values, int $width = 80, int $height = 24): string { if (count($values) < 2) { return ''; } $min_val = min($values); $max_val = max($values); $range = $max_val - $min_val; if ($range === 0) $range = 1; $step = $width / (count($values) - 1); $points = []; foreach ($values as $i => $v) { $x = round($i * $step, 1); $y = round($height - (($v - $min_val) / $range) * ($height - 2) - 1, 1); $points[] = $x . ',' . $y; } return '' . '' . ''; } private function human_time_diff(string $datetime): string { if ($datetime === '') { return __( 'Never', 'airf-restock-forecast' ); } $ts = strtotime($datetime); if ($ts === false) { return $datetime; } $diff = time() - $ts; if ($diff < 60) return __( 'Just now', 'airf-restock-forecast' ); /* translators: %d: number of minutes ago */ if ($diff < 3600) return sprintf( __( '%dm ago', 'airf-restock-forecast' ), (int) floor($diff / 60) ); /* translators: %d: number of hours ago */ if ($diff < 86400) return sprintf( __( '%dh ago', 'airf-restock-forecast' ), (int) floor($diff / 3600) ); /* translators: %d: number of days ago */ if ($diff < 604800) return sprintf( __( '%dd ago', 'airf-restock-forecast' ), (int) floor($diff / 86400) ); return wp_date('M j, Y', $ts); } }