false, 'no_api' => true, 'has_api' => false, 'provider' => $provider, 'message' => __('আপনি কোনো API অ্যাড করেন নাই। Courier Ratio দেখতে সেটিংস থেকে API Key যুক্ত করুন।', 'advance-fake-order-protector'), 'is_blocked' => AFOP_Blocklist::is_blocked('phone', $normalized_phone) ); } return null; } /** * Fetch courier stats for a given phone number * * @param string $phone * @param bool $force_refresh * @param string $provider * @return array */ public static function get_delivery_stats($phone, $force_refresh = false, $provider = '') { $normalized_phone = AFOP_Validator::normalize_phone($phone); if (empty($normalized_phone)) { return array( 'success' => false, 'message' => __('Invalid phone number provided.', 'advance-fake-order-protector') ); } if (empty($provider)) { $provider = get_option('afop_courier_provider', 'bdcourier'); } if (!in_array($provider, array('bdcourier', 'steadfast', 'pathao'), true)) { return array('success' => false, 'no_api' => true, 'has_api' => false, 'message' => __('Choose a supported courier provider in settings.', 'advance-fake-order-protector')); } // Check if API key is configured for this provider if (!self::is_provider_configured($provider)) { return array( 'success' => false, 'no_api' => true, 'has_api' => false, 'phone' => $normalized_phone, 'provider' => $provider, /* translators: Numeric placeholders are counts; string placeholders identify the provider, customer or blocklist item. */ 'message' => sprintf(__('আপনি %s API অ্যাড করেন নাই। Courier Ratio দেখতে সেটিংস থেকে API Key যুক্ত করুন।', 'advance-fake-order-protector'), ucfirst($provider)), 'is_blocked' => AFOP_Blocklist::is_blocked('phone', $normalized_phone), 'from_cache' => false ); } // Check local cache if not force refresh if (!$force_refresh) { $cached = self::get_cached_stats($normalized_phone, $provider); if ($cached) { $cached['is_blocked'] = AFOP_Blocklist::is_blocked('phone', $normalized_phone); $cached['from_cache'] = true; $cached['has_api'] = true; $cached['no_api'] = false; return $cached; } } // Fetch live stats from chosen API provider $stats = null; if ($provider === 'steadfast') { $stats = self::fetch_steadfast_stats($normalized_phone); } elseif ($provider === 'pathao') { $stats = self::fetch_pathao_stats($normalized_phone); } else { $stats = self::fetch_bdcourier_stats($normalized_phone); } if (!$stats || empty($stats['success'])) { if (!isset($stats['message'])) { $stats = array('success' => false, 'message' => __('API Data Unavailable', 'advance-fake-order-protector')); } $stats['has_api'] = true; $stats['no_api'] = false; } else { $stats['has_api'] = true; $stats['no_api'] = false; // Cache the live successful response self::save_to_cache($normalized_phone, $provider, $stats); } $stats['is_blocked'] = AFOP_Blocklist::is_blocked('phone', $normalized_phone); $stats['from_cache'] = false; return $stats; } /** * Issue or retrieve cached Pathao OAuth Access Token * Uses OAuth 2.0 grant_type password / refresh_token as documented in Pathao Courier Merchant API */ public static function get_pathao_access_token() { if (get_option('afop_courier_consent', 'no') !== 'yes') { return new WP_Error('no_consent', 'External courier requests are disabled.'); } $client_id = trim(get_option('afop_pathao_client_id', '')); $client_secret = trim(get_option('afop_pathao_client_secret', '')); $username = trim(get_option('afop_pathao_username', '')); $password = trim(get_option('afop_pathao_password', '')); $base_url = rtrim(trim(get_option('afop_pathao_base_url', 'https://courier-api-sandbox.pathao.com')), '/'); if (!in_array($base_url, array('https://courier-api-sandbox.pathao.com', 'https://api-hermes.pathao.com'), true)) { return new WP_Error('invalid_host', 'Invalid Pathao API host.'); } if (empty($client_id) || empty($client_secret) || empty($username) || empty($password)) { return new WP_Error('missing_credentials', __('Pathao API Credentials missing. Please enter Client ID, Secret, Username and Password in Settings.', 'advance-fake-order-protector')); } // Check stored token in option $token_data = get_option('afop_pathao_token_data', array()); $now = time(); // If access token is valid (with 5-minute safety buffer), return it if (!empty($token_data['access_token']) && !empty($token_data['expires_at']) && ($token_data['expires_at'] - 300) > $now) { return $token_data['access_token']; } $endpoint = $base_url . '/aladdin/api/v1/issue-token'; // Try refresh token if available if (!empty($token_data['refresh_token'])) { $refresh_payload = array( 'client_id' => $client_id, 'client_secret' => $client_secret, 'grant_type' => 'refresh_token', 'refresh_token' => $token_data['refresh_token'] ); $response = wp_safe_remote_post($endpoint, array( 'headers' => array( 'Content-Type' => 'application/json', 'Accept' => 'application/json' ), 'body' => wp_json_encode($refresh_payload), 'timeout' => 15, 'redirection' => 0 )); if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) { $body = json_decode(wp_remote_retrieve_body($response), true); if (!empty($body['access_token'])) { $expires_in = isset($body['expires_in']) ? intval($body['expires_in']) : 432000; $token_info = array( 'access_token' => $body['access_token'], 'refresh_token' => isset($body['refresh_token']) ? $body['refresh_token'] : $token_data['refresh_token'], 'expires_at' => time() + $expires_in ); update_option('afop_pathao_token_data', $token_info); return $body['access_token']; } } } // Fallback to issuing new token using grant_type password $payload = array( 'client_id' => $client_id, 'client_secret' => $client_secret, 'grant_type' => 'password', 'username' => $username, 'password' => $password ); $response = wp_safe_remote_post($endpoint, array( 'headers' => array( 'Content-Type' => 'application/json', 'Accept' => 'application/json' ), 'body' => wp_json_encode($payload), 'timeout' => 15, 'redirection' => 0 )); if (is_wp_error($response)) { return $response; } $code = wp_remote_retrieve_response_code($response); $body = json_decode(wp_remote_retrieve_body($response), true); if ($code !== 200 || empty($body['access_token'])) { $err_msg = isset($body['message']) ? $body['message'] : (isset($body['error']) ? $body['error'] : __('Failed to issue Pathao access token.', 'advance-fake-order-protector')); return new WP_Error('pathao_auth_error', 'Pathao Auth Error: ' . $err_msg); } $expires_in = isset($body['expires_in']) ? intval($body['expires_in']) : 432000; $token_info = array( 'access_token' => $body['access_token'], 'refresh_token' => isset($body['refresh_token']) ? $body['refresh_token'] : '', 'expires_at' => time() + $expires_in ); update_option('afop_pathao_token_data', $token_info); return $body['access_token']; } /** Fetch the production merchant customer-rating report. */ private static function fetch_pathao_stats($phone) { $base_url = rtrim(trim(get_option('afop_pathao_base_url', 'https://courier-api-sandbox.pathao.com')), '/'); if ($base_url !== 'https://api-hermes.pathao.com') { return array('success' => false, 'message' => __('Pathao customer ratings require the Production / Live environment. Sandbox credentials cannot retrieve live customer history.', 'advance-fake-order-protector')); } $token = self::get_pathao_access_token(); if (is_wp_error($token)) { return array('success' => false, 'message' => $token->get_error_message()); } $clean_phone = AFOP_Validator::normalize_phone($phone); if (empty($clean_phone)) { return array('success' => false, 'message' => __('Invalid phone number provided.', 'advance-fake-order-protector')); } // Customer ratings use the merchant API, not the Aladdin shipment API. $endpoint = 'https://merchant.pathao.com/api/v1/user/success'; for ($attempt = 0; $attempt < 2; $attempt++) { $response = wp_safe_remote_post($endpoint, array( 'headers' => array('Authorization' => 'Bearer ' . $token, 'Content-Type' => 'application/json', 'Accept' => 'application/json'), 'body' => wp_json_encode(array('phone' => $clean_phone)), 'timeout' => 15, 'redirection' => 0, )); if (is_wp_error($response)) { return array('success' => false, 'message' => __('Pathao could not be reached. Please try again later.', 'advance-fake-order-protector')); } $code = (int) wp_remote_retrieve_response_code($response); $body = json_decode(wp_remote_retrieve_body($response), true); $unauthorized = $code === 401 || ($code === 200 && is_array($body) && self::pathao_response_failed($body) && isset($body['message']) && is_string($body['message']) && preg_match('/unauthori[sz]ed|token.*(?:expired|invalid)/i', $body['message'])); if ($unauthorized && $attempt === 0) { delete_option('afop_pathao_token_data'); $token = self::get_pathao_access_token(); if (is_wp_error($token)) { return array('success' => false, 'message' => $token->get_error_message()); } continue; } if ($unauthorized || $code === 403) { return array('success' => false, 'message' => __('Pathao rejected the customer-rating request. Re-save your credentials or confirm customer-rating API access with Pathao.', 'advance-fake-order-protector')); } if ($code !== 200 || !is_array($body) || self::pathao_response_failed($body)) { return array('success' => false, 'message' => __('Pathao could not provide a customer report. Please try again later.', 'advance-fake-order-protector')); } return self::format_pathao_response($clean_phone, $body); } return array('success' => false, 'message' => __('Pathao could not provide a customer report.', 'advance-fake-order-protector')); } /** Pathao may return an application-level error with HTTP 200. */ private static function pathao_response_failed($data) { if (isset($data['success']) && in_array($data['success'], array(false, 0, '0', 'false'), true)) { return true; } if (!empty($data['error']) || !empty($data['errors'])) { return true; } foreach (array('code', 'status') as $key) { if (isset($data[$key]) && is_numeric($data[$key]) && (int) $data[$key] >= 400) { return true; } } return isset($data['type']) && is_string($data['type']) && in_array(strtolower($data['type']), array('error', 'failed'), true); } /** Preserve provider ratings without inventing counts or percentage estimates. */ private static function format_pathao_response($phone, $raw) { $invalid = array('success' => false, 'message' => __('Pathao returned an unrecognized customer report. No delivery percentage is available.', 'advance-fake-order-protector')); if (!is_array($raw) || self::pathao_response_failed($raw)) { return $invalid; } $data = isset($raw['data']) && is_array($raw['data']) ? $raw['data'] : $raw; if (self::pathao_response_failed($data)) { return $invalid; } $rating = isset($data['customer_rating']) && is_string($data['customer_rating']) ? sanitize_key($data['customer_rating']) : ''; $rating_labels = array( 'new_customer' => __('New Customer', 'advance-fake-order-protector'), 'excellent_customer' => __('Excellent Customer', 'advance-fake-order-protector'), 'good_customer' => __('Good Customer', 'advance-fake-order-protector'), 'moderate_customer' => __('Moderate Customer', 'advance-fake-order-protector'), 'risky_customer' => __('Risky Customer', 'advance-fake-order-protector'), 'bad_customer' => __('Bad Customer', 'advance-fake-order-protector'), ); $rating_label = $rating ? ($rating_labels[$rating] ?? __('Customer Rating', 'advance-fake-order-protector')) : ''; $total = self::courier_count($data, array('total_orders', 'total_parcel', 'total_parcels', 'total')); $delivered = self::courier_count($data, array('delivered_orders', 'delivered', 'success_parcel')); $returned = self::courier_count($data, array('returned_orders', 'returned', 'cancelled_parcel', 'cancel')); // A provider's explicit show_count=false overrides any hidden placeholder counts. if (isset($data['show_count']) && in_array($data['show_count'], array(false, 0, '0', 'false'), true)) { $total = null; $delivered = null; $returned = null; } elseif (null === $total && null !== $delivered && null !== $returned) { $total = $delivered + $returned; } $rate = self::courier_percent($data, array('success_rate', 'delivery_rate', 'delivery_ratio')); $return_rate = self::courier_percent($data, array('return_rate', 'return_ratio')); if (null === $rate && null !== $delivered && null !== $total) { $rate = $total > 0 ? round($delivered / $total * 100, 1) : null; } if (null === $return_rate && null !== $returned && null !== $total) { $return_rate = $total > 0 ? round($returned / $total * 100, 1) : null; } if (!$rating && null === $rate && null === $total) { return $invalid; } if (null !== $total && ((null !== $delivered && $delivered > $total) || (null !== $returned && $returned > $total))) { return $invalid; } if (null !== $total && null !== $delivered && null !== $returned && $delivered + $returned > $total) { return $invalid; } $risk = 'unknown'; if (in_array($rating, array('risky_customer', 'bad_customer'), true)) { $risk = 'high'; } elseif ($rating === 'moderate_customer') { $risk = 'medium'; } elseif (in_array($rating, array('excellent_customer', 'good_customer'), true)) { $risk = 'safe'; } elseif (!$rating && null !== $rate && 0 !== $total) { $risk = $rate < 65 || (null !== $return_rate && $return_rate >= 30) ? 'high' : ($rate < 80 || (null !== $return_rate && $return_rate >= 15) ? 'medium' : 'safe'); } $type = $rating && null === $total ? 'rating' : 'delivery'; $notice = $type === 'rating' ? __('Pathao supplied a customer rating. Parcel counts and delivery percentages are shown only when provided by Pathao.', 'advance-fake-order-protector') : ''; return array( 'success' => true, 'phone' => $phone, 'provider' => 'Pathao Courier API', 'provider_key' => 'pathao', 'total_orders' => $total, 'delivered' => $delivered, 'returned' => $returned, 'cancelled' => $returned, 'delivery_rate' => $rate, 'return_rate' => $return_rate, 'risk_level' => $risk, 'data_type' => $type, 'customer_rating' => $rating, 'rating_label' => $rating_label, 'report_notice' => $notice, '_afop_pathao_schema' => 2, 'pathao_environment' => get_option('afop_pathao_base_url', 'https://courier-api-sandbox.pathao.com'), 'couriers' => array(array('name' => 'Pathao Courier', 'data_type' => $type, 'total' => $total, 'delivered' => $delivered, 'returned' => $returned, 'delivery_rate' => $rate, 'success_rate' => $rate, 'customer_rating' => $rating, 'rating_label' => $rating_label, 'risk_level' => $risk)), ); } /** * Fetch from BDCourier API (api.bdcourier.com) */ private static function fetch_bdcourier_stats($phone) { $api_key = trim(get_option('afop_bdcourier_api_key', '')); if (empty($api_key)) { return array( 'success' => false, 'message' => __('BDCourier API Key is not configured.', 'advance-fake-order-protector') ); } $endpoint = 'https://api.bdcourier.com/courier-check'; $response = wp_safe_remote_post($endpoint, array( 'headers' => array( 'Authorization' => 'Bearer ' . $api_key, 'Content-Type' => 'application/json', 'Accept' => 'application/json' ), 'body' => wp_json_encode(array('phone' => $phone)), 'timeout' => 15, 'redirection' => 0 )); if (is_wp_error($response)) { return array( 'success' => false, 'message' => $response->get_error_message() ); } $code = wp_remote_retrieve_response_code($response); $body = json_decode(wp_remote_retrieve_body($response), true); if ($code !== 200 || empty($body)) { return array( 'success' => false, 'message' => isset($body['message']) ? $body['message'] : __('BDCourier API error response.', 'advance-fake-order-protector') ); } return self::format_courier_response($phone, 'BD Courier', $body); } /** * Fetch from Steadfast Courier API */ private static function fetch_steadfast_stats($phone) { $api_key = trim(get_option('afop_steadfast_api_key', '')); $secret_key = trim(get_option('afop_steadfast_secret_key', '')); if (empty($api_key) || empty($secret_key)) { return array( 'success' => false, 'message' => __('Steadfast API Key or Secret is missing.', 'advance-fake-order-protector') ); } $endpoint = 'https://portal.packzy.com/api/v1/fraud_check/score/' . rawurlencode($phone); $response = wp_safe_remote_get($endpoint, array( 'headers' => array( 'Api-Key' => $api_key, 'Secret-Key' => $secret_key, 'Accept' => 'application/json', 'Content-Type'=> 'application/json' ), 'timeout' => 15, 'redirection' => 0 )); if (is_wp_error($response)) { return array( 'success' => false, 'message' => $response->get_error_message() ); } $code = wp_remote_retrieve_response_code($response); $body = json_decode(wp_remote_retrieve_body($response), true); if ($code !== 200 || !is_array($body) || empty($body)) { return array( 'success' => false, /* translators: %d: HTTP response status code. */ 'message' => sprintf(__('Steadfast request failed (HTTP %d). Check your credentials and courier access.', 'advance-fake-order-protector'), $code) ); } return self::format_steadfast_response($phone, $body); } /** Read exact counts without turning ranges, nulls or percentages into counts. */ private static function courier_count($data, $keys) { foreach ($keys as $key) { if (isset($data[$key]) && is_scalar($data[$key]) && !is_bool($data[$key]) && preg_match('/^\d+$/D', (string) $data[$key])) { return min(PHP_INT_MAX, (int) $data[$key]); } } return null; } /** Read a provider percentage, preserving an explicitly supplied zero. */ private static function courier_percent($data, $keys) { foreach ($keys as $key) { if (!isset($data[$key]) || !is_scalar($data[$key]) || is_bool($data[$key])) { continue; } $value = rtrim(trim((string) $data[$key]), '%'); if (is_numeric($value) && (float) $value >= 0 && (float) $value <= 100) { return round((float) $value, 1); } } return null; } /** Normalize the current Steadfast Score API and its legacy count fields. */ private static function format_steadfast_response($phone, $raw) { if ((isset($raw['success']) && false === $raw['success']) || (isset($raw['status']) && (is_numeric($raw['status']) ? (int) $raw['status'] >= 400 : in_array(strtolower((string) $raw['status']), array('error', 'failed', 'unauthorized'), true)))) { return array('success' => false, 'message' => __('Steadfast could not provide a report. Check your credentials and courier access.', 'advance-fake-order-protector')); } $data = isset($raw['data']) && is_array($raw['data']) ? $raw['data'] : $raw; $total = self::courier_count($data, array('total_parcels', 'total_parcel', 'total_orders', 'volume_range')); $delivered = self::courier_count($data, array('delivered_count', 'total_delivered', 'success_parcel', 'delivered')); $returned = self::courier_count($data, array('cancelled_count', 'total_cancelled', 'cancelled_parcel', 'returned', 'cancelled')); $rate = self::courier_percent($data, array('delivery_ratio', 'success_ratio', 'delivery_rate')); $return_rate = self::courier_percent($data, array('return_ratio', 'cancellation_ratio', 'return_rate')); // total_reports counts fraud reports, never parcel volume. if (null === $total && null !== $delivered && null !== $returned && empty($data['volume_range'])) { $total = $delivered + $returned; } if (null === $rate && null !== $total && null !== $delivered) { $rate = $total > 0 ? round($delivered / $total * 100, 1) : 0; } if (null === $return_rate && null !== $total && null !== $returned) { $return_rate = $total > 0 ? round($returned / $total * 100, 1) : 0; } if ((null === $rate && null === $total) || (null !== $total && ((null !== $delivered && $delivered > $total) || (null !== $returned && $returned > $total)))) { return array('success' => false, 'message' => __('Steadfast returned an unrecognized report. Please try again later.', 'advance-fake-order-protector')); } $risk = 'unknown'; if (null !== $rate && 0 !== $total) { $risk = 'safe'; if ($rate < 60 || (null !== $return_rate && $return_rate >= 35)) { $risk = 'high'; } elseif ($rate < 80 || (null !== $return_rate && $return_rate >= 15)) { $risk = 'medium'; } } $volume = isset($data['volume_range']) && is_scalar($data['volume_range']) ? sanitize_text_field((string) $data['volume_range']) : ''; return array( 'success' => true, 'phone' => $phone, 'provider' => 'Steadfast', 'provider_key' => 'steadfast', 'total_orders' => $total, 'delivered' => $delivered, 'returned' => $returned, 'cancelled' => 0, 'volume_range' => $volume, 'delivery_rate' => $rate, 'return_rate' => $return_rate, 'risk_level' => $risk, '_afop_steadfast_schema' => 2, 'couriers' => array(array('name' => 'Steadfast', 'data_type' => 'delivery', 'total' => $total, 'delivered' => $delivered, 'returned' => $returned, 'volume_range' => $volume, 'delivery_rate' => $rate)), ); } /** * Standardize legacy courier API responses into unified schema */ private static function format_courier_response($phone, $provider_name, $raw) { $total_orders = 0; $delivered = 0; $returned = 0; $cancelled = 0; $couriers = array(); if (isset($raw['data'])) { $data = $raw['data']; $total_orders = isset($data['total_parcel']) ? intval($data['total_parcel']) : (isset($data['total_orders']) ? intval($data['total_orders']) : 0); $delivered = isset($data['success_parcel']) ? intval($data['success_parcel']) : (isset($data['delivered']) ? intval($data['delivered']) : 0); $returned = isset($data['cancelled_parcel']) ? intval($data['cancelled_parcel']) : (isset($data['returned']) ? intval($data['returned']) : 0); if (isset($data['courier_details']) && is_array($data['courier_details'])) { foreach ($data['courier_details'] as $c_name => $c_stat) { $couriers[] = array( 'name' => ucfirst($c_name), 'data_type' => 'delivery', 'total' => isset($c_stat['total']) ? intval($c_stat['total']) : 0, 'delivered' => isset($c_stat['success']) ? intval($c_stat['success']) : 0, 'returned' => isset($c_stat['cancelled']) ? intval($c_stat['cancelled']) : 0, ); } } } else { $total_orders = isset($raw['total_orders']) ? intval($raw['total_orders']) : 0; $delivered = isset($raw['delivered']) ? intval($raw['delivered']) : 0; $returned = isset($raw['returned']) ? intval($raw['returned']) : 0; $cancelled = isset($raw['cancelled']) ? intval($raw['cancelled']) : 0; } if ($total_orders == 0 && ($delivered > 0 || $returned > 0)) { $total_orders = $delivered + $returned + $cancelled; } $delivery_rate = ($total_orders > 0) ? round(($delivered / $total_orders) * 100, 1) : 0; $return_rate = ($total_orders > 0) ? round(($returned / $total_orders) * 100, 1) : 0; // Risk Level Calculation $risk_level = 'safe'; if ($total_orders > 0) { if ($return_rate >= 35 || $delivery_rate < 60) { $risk_level = 'high'; } elseif ($return_rate >= 15 || $delivery_rate < 80) { $risk_level = 'medium'; } } return array( 'success' => true, 'phone' => $phone, 'provider' => $provider_name, 'provider_key' => strtolower(str_replace(' ', '', $provider_name)), 'total_orders' => $total_orders, 'delivered' => $delivered, 'returned' => $returned, 'cancelled' => $cancelled, 'delivery_rate' => $delivery_rate, 'return_rate' => $return_rate, 'risk_level' => $risk_level, 'couriers' => $couriers, 'raw_data' => $raw ); } /** * Save a successful provider response to the local courier cache. */ private static function save_to_cache($phone, $provider, $stats) { global $wpdb; $table = $wpdb->prefix . 'afop_courier_cache'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- This updates the plugin-owned courier cache; no read cache should suppress writes. $wpdb->replace( $table, array( 'phone' => $phone, 'provider' => $provider, 'delivery_rate' => $stats['delivery_rate'], 'return_rate' => $stats['return_rate'], 'total_orders' => $stats['total_orders'], 'delivered_count' => $stats['delivered'], 'return_count' => $stats['returned'], 'cancelled_count' => isset($stats['cancelled']) ? $stats['cancelled'] : 0, 'raw_response' => wp_json_encode($stats), 'updated_at' => current_time('mysql') ), array('%s', '%s', '%f', '%f', '%d', '%d', '%d', '%d', '%s', '%s') ); } /** * Get from cache table */ private static function get_cached_stats($phone, $provider) { global $wpdb; $table = $wpdb->prefix . 'afop_courier_cache'; $hours = intval(get_option('afop_courier_cache_hours', 24)); $cutoff = gmdate('Y-m-d H:i:s', current_time('timestamp') - ($hours * 3600)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- This is the plugin-owned courier cache itself; writes update that cache and reads enforce its expiry. $row = $wpdb->get_row($wpdb->prepare( "SELECT raw_response FROM %i WHERE phone = %s AND provider = %s AND updated_at >= %s LIMIT 1", $table, $phone, $provider, $cutoff )); if ($row && !empty($row->raw_response)) { $stats = json_decode($row->raw_response, true); if ($provider === 'steadfast' && (!is_array($stats) || empty($stats['_afop_steadfast_schema']) || 2 !== $stats['_afop_steadfast_schema'])) { return null; } if ($provider === 'pathao' && (!is_array($stats) || ($stats['_afop_pathao_schema'] ?? 0) !== 2 || ($stats['pathao_environment'] ?? '') !== get_option('afop_pathao_base_url', 'https://courier-api-sandbox.pathao.com'))) { return null; } return $stats; } return null; } /** * Admin AJAX to fetch courier delivery stats */ public function ajax_get_courier_ratio() { check_ajax_referer('afop_admin_nonce', 'nonce'); if (!current_user_can('manage_woocommerce')) { wp_send_json_error(array('message' => 'Unauthorized.')); } $phone = isset($_POST['phone']) ? sanitize_text_field(wp_unslash($_POST['phone'])) : ''; $force = isset($_POST['force_refresh']) && $_POST['force_refresh'] === 'true'; $provider = isset($_POST['provider']) ? sanitize_text_field(wp_unslash($_POST['provider'])) : ''; if (empty($phone)) { wp_send_json_error(array('message' => 'Phone number is required.')); } if ($provider === 'all' || empty($provider)) { // Return all 3 providers for multi-tab rendering $providers_data = array( 'bdcourier' => self::get_delivery_stats($phone, $force, 'bdcourier'), 'steadfast' => self::get_delivery_stats($phone, $force, 'steadfast'), 'pathao' => self::get_delivery_stats($phone, $force, 'pathao') ); wp_send_json_success(array( 'multi_provider' => true, 'phone' => AFOP_Validator::normalize_phone($phone), 'is_blocked' => AFOP_Blocklist::is_blocked('phone', $phone), 'providers' => $providers_data, 'active_provider' => in_array(get_option('afop_courier_provider', 'bdcourier'), array('bdcourier', 'steadfast', 'pathao'), true) ? get_option('afop_courier_provider', 'bdcourier') : 'bdcourier', 'has_any_api' => self::has_any_api_configured(), 'configured_status' => array( 'bdcourier' => self::is_provider_configured('bdcourier'), 'steadfast' => self::is_provider_configured('steadfast'), 'pathao' => self::is_provider_configured('pathao') ) )); } else { $stats = self::get_delivery_stats($phone, $force, $provider); if (!$stats) { wp_send_json_error(array('message' => 'Failed to fetch stats.')); } wp_send_json_success($stats); } } /** * Admin AJAX to check saved credential fields locally, without contacting a provider. */ public function ajax_test_courier_api() { check_ajax_referer('afop_admin_nonce', 'nonce'); if (!current_user_can('manage_woocommerce')) { wp_send_json_error(array('message' => 'Unauthorized.')); } if (get_option('afop_courier_consent', 'no') !== 'yes') { wp_send_json_error(array('message' => 'Enable external courier requests in settings first.')); } $active_provider = get_option('afop_courier_provider', 'bdcourier'); if (!self::is_provider_configured($active_provider)) { wp_send_json_error(array('message' => __('Select a supported provider and save all required credentials first.', 'advance-fake-order-protector'))); } if ($active_provider === 'pathao' && (empty(trim(get_option('afop_pathao_username', ''))) || empty(trim(get_option('afop_pathao_password', ''))))) { wp_send_json_error(array('message' => __('Save the Pathao merchant username and password first.', 'advance-fake-order-protector'))); } wp_send_json_success(array('message' => __('Required credentials are saved. No external request was sent and the credentials have not been authenticated. Use an authorized order lookup to verify live access.', 'advance-fake-order-protector'))); } }