table_name = $wpdb->prefix . 'aipt_store_index_profiles'; } /** * Back-fill the freed content fields (`description`, `tags`) into profiles * that still use the previous default `included_fields`. * * The 2026-09 Free/Business tier decision freed description + tags for * every plan so free RAG actually works, but DEFAULT_INCLUDED_FIELDS only * affects NEW profiles; pre-existing rows keep their persisted * included_fields. Profiles with any customization are left unchanged. * Run once, gated by FREE_CONTENT_FIELDS_BACKFILL_OPTION. * * @return int Number of profile rows mutated. */ public static function migrateExistingProfilesToIncludeFreeContentFields(): int { if ( \get_option( self::FREE_CONTENT_FIELDS_BACKFILL_OPTION ) ) { return 0; } global $wpdb; $table = $wpdb->prefix . 'aipt_store_index_profiles'; $rows = $wpdb->get_results( "SELECT id, settings FROM {$table}", ARRAY_A ); if ( ! is_array( $rows ) ) { return 0; } $mutated = 0; $expected = 0; $failed = false; foreach ( $rows as $row ) { $id = isset( $row['id'] ) ? (int) $row['id'] : 0; $settings = isset( $row['settings'] ) ? json_decode( (string) $row['settings'], true ) : null; if ( $id <= 0 || ! is_array( $settings ) ) { continue; } $included = $settings['included_fields'] ?? null; if ( ! is_array( $included ) ) { continue; } if ( ! self::matchesPreviousDefaultShape( $included ) ) { continue; } $missing = array_values( array_diff( self::FREE_CONTENT_FIELDS, $included ) ); if ( empty( $missing ) ) { continue; } $expected++; $settings['included_fields'] = array_values( array_merge( $included, $missing ) ); $updated = $wpdb->update( $table, [ 'settings' => \wp_json_encode( $settings ) ], [ 'id' => $id ], [ '%s' ], [ '%d' ] ); if ( false === $updated ) { $failed = true; continue; } if ( $updated > 0 ) { $mutated++; } } if ( ! $failed && $mutated === $expected ) { \update_option( self::FREE_CONTENT_FIELDS_BACKFILL_OPTION, 1, false ); } return $mutated; } /** * Whether a profile's `included_fields` is still the previous default * set (PREVIOUS_DEFAULT_INCLUDED_FIELDS), in any order and whether or not * the Business 'sku' default later added to it (2026-06-03) is present. * * Any profile persisted before that 'sku' default existed - on any plan - * never had 'sku' in its stored set and can never equal the constant * directly; comparing with 'sku' removed from both sides treats that * earlier set the same as the set 'sku' was later added to, while a * profile missing any OTHER field (a deliberate exclusion) still fails * the comparison and is left alone. * * @param mixed $included Profile's included_fields. * @return bool */ private static function matchesPreviousDefaultShape( $included ): bool { if ( ! is_array( $included ) ) { return false; } $stored = array_values( array_diff( $included, array( 'sku' ) ) ); $previous = array_values( array_diff( self::PREVIOUS_DEFAULT_INCLUDED_FIELDS, array( 'sku' ) ) ); sort( $stored ); sort( $previous ); return $stored === $previous; } /** * Get all profiles. * * @return array List of all profiles. */ public function getAll(): array { global $wpdb; $sql = "SELECT * FROM {$this->table_name} ORDER BY is_default DESC, name ASC"; $profiles = $wpdb->get_results($sql, ARRAY_A); if ( ! is_array( $profiles ) ) { if ( $wpdb->last_error ) { } return array(); } return array_map( array( $this, 'formatProfile' ), $profiles ); } /** * Get a profile by ID. * * @param int $id Profile ID. * @return array|null Profile data or null if not found. */ public function getById( int $id ): ?array { global $wpdb; $sql = "SELECT * FROM {$this->table_name} WHERE id = %d"; $profile = $wpdb->get_row($wpdb->prepare($sql, $id), ARRAY_A); if ( ! $profile ) { return null; } return $this->formatProfile( $profile ); } /** * Get the default profile. * * @return array|null Default profile data or null if not found. */ public function getDefault(): ?array { global $wpdb; $sql = "SELECT * FROM {$this->table_name} WHERE is_default = %d"; $profile = $wpdb->get_row($wpdb->prepare($sql, 1), ARRAY_A); if ( ! $profile ) { return null; } return $this->formatProfile( $profile ); } /** * Get the currently active profile. * * @return array|null Active profile data or null if not found. */ public function getActive(): ?array { global $wpdb; $sql = "SELECT * FROM {$this->table_name} WHERE is_active = %d"; $profile = $wpdb->get_row($wpdb->prepare($sql, 1), ARRAY_A); if ( ! $profile ) { return $this->getDefault(); } return $this->formatProfile( $profile ); } /** * Get the active profile ID. * * @return int Active profile ID or 0 if not found. */ public function getActiveId(): int { $active = $this->getActive(); return $active ? (int) $active['id'] : 0; } /** * Update a profile's settings. * * @param int $id Profile ID. * @param array $data Data to update (settings and/or name). * @return bool True on success. * @throws \InvalidArgumentException If profile not found or name invalid. */ public function update( int $id, array $data ): bool { global $wpdb; $profile = $this->getById( $id ); if ( ! $profile ) { throw new \InvalidArgumentException( __( 'Profile not found.', 'ai-product-tools' ) ); } $update_data = array(); $update_format = array(); if ( isset( $data['name'] ) ) { $name = $data['name']; $this->validateName( $name ); $sql = "SELECT id FROM {$this->table_name} WHERE name = %s AND id != %d"; $exists = $wpdb->get_var($wpdb->prepare($sql, $name, $id)); if ( $exists ) { throw new \InvalidArgumentException( __( 'A profile with this name already exists.', 'ai-product-tools' ) ); } $update_data['name'] = $name; $update_format[] = '%s'; } if ( isset( $data['settings'] ) && is_array( $data['settings'] ) ) { $current_settings = $profile['settings']; $new_settings = array_merge( $current_settings, $data['settings'] ); if ( isset( $new_settings['included_fields'] ) ) { $new_settings['included_fields'] = array_values( array_intersect( $new_settings['included_fields'], self::AVAILABLE_FIELDS ) ); $new_settings['included_fields'] = self::ensureMandatoryFields( $new_settings['included_fields'] ); } $update_data['settings'] = wp_json_encode( $new_settings ); $update_format[] = '%s'; } if ( empty( $update_data ) ) { return true; } $update_data['updated_at'] = current_time( 'mysql' ); $update_format[] = '%s'; $suppress = $wpdb->suppress_errors( true ); $result = $wpdb->update( $this->table_name, $update_data, array( 'id' => $id ), $update_format, array( '%d' ) ); $wpdb->suppress_errors( $suppress ); if ( false === $result ) { $last_error = $wpdb->last_error; if ( strpos( $last_error, 'Duplicate entry' ) !== false || strpos( $last_error, '1062' ) !== false ) { throw new \InvalidArgumentException( __( 'A profile with this name already exists.', 'ai-product-tools' ) ); } throw new \RuntimeException( sprintf( /* translators: %1$d: profile ID, %2$s: database error message */ __( 'Failed to update profile %1$d: %2$s', 'ai-product-tools' ), $id, $last_error ?: __( 'Unknown database error', 'ai-product-tools' ) ) ); } return true; } /** * Update a profile's status. * * @param int $id Profile ID. * @param array $status Status data to update. * @return bool True on success. */ public function updateStatus( int $id, array $status ): bool { global $wpdb; $profile = $this->getById( $id ); if ( ! $profile ) { return false; } $current_status = $profile['status']; $new_status = array_merge( $current_status, $status ); $result = $wpdb->update( $this->table_name, array( 'status' => wp_json_encode( $new_status ), 'updated_at' => current_time( 'mysql' ), ), array( 'id' => $id ), array( '%s', '%s' ), array( '%d' ) ); return $result !== false; } /** * Delete a profile. * * Operation order is important for transactional integrity: * 1. Validate profile exists and is not default * 2. Delete from database first (critical operation) * 3. Switch active profile if needed (after successful DB deletion) * 4. Delete index file last (non-critical, logged if fails) * * @param int $id Profile ID. * @return bool True on success. * @throws \InvalidArgumentException If profile is default or not found. */ public function delete( int $id ): bool { global $wpdb; $profile = $this->getById( $id ); if ( ! $profile ) { throw new \InvalidArgumentException( __( 'Profile not found.', 'ai-product-tools' ) ); } if ( $profile['is_default'] ) { throw new \InvalidArgumentException( __( 'Cannot delete the default profile.', 'ai-product-tools' ) ); } $was_active = $profile['is_active']; $result = $wpdb->delete( $this->table_name, array( 'id' => $id ), array( '%d' ) ); if ( false === $result ) { return false; } if ( $was_active ) { $default = $this->getDefault(); if ( $default ) { try { $this->setActive( (int) $default['id'] ); } catch ( \InvalidArgumentException $e ) { error_log( sprintf( '[AIPT] ProfileManager: Failed to activate default profile after deleting profile %d: %s', $id, $e->getMessage() ) ); } } } $this->cleanupChatbotProfileReference( $id ); $storage = new IndexStorage( $id ); $storage->delete(); return true; } /** * Set a profile as the active profile. * * Only one profile can be active at a time. Uses a single atomic UPDATE * statement to prevent race conditions that could leave no profile active. * * Note: No pre-check for profile existence to avoid TOCTOU race conditions. * Instead, we verify the target profile was actually updated by checking * that the target row's is_active value changed. * * @param int $id Profile ID. * @return bool True on success. * @throws \InvalidArgumentException If profile not found (detected after UPDATE). */ public function setActive( int $id ): bool { global $wpdb; $current_time = current_time( 'mysql' ); $sql = "UPDATE {$this->table_name} SET is_active = CASE WHEN id = %d THEN 1 ELSE 0 END, updated_at = CASE WHEN id = %d THEN %s ELSE updated_at END"; $result = $wpdb->query($wpdb->prepare($sql, $id, $id, $current_time)); if ( false === $result ) { return false; } $verify_sql = "SELECT id FROM {$this->table_name} WHERE id = %d AND is_active = 1"; $activated = $wpdb->get_var($wpdb->prepare($verify_sql, $id)); if ( ! $activated ) { throw new \InvalidArgumentException( __( 'Profile not found.', 'ai-product-tools' ) ); } return true; } /** * Get global building status. * * Checks all profiles for any ongoing builds. * * @return array Building status information. */ public function getGlobalBuildingStatus(): array { $profiles = $this->getAll(); $building_profiles = array(); foreach ( $profiles as $profile ) { $status = $profile['status']; if ( isset( $status['status'] ) && 'building' === $status['status'] ) { $building_profiles[] = array( 'id' => $profile['id'], 'name' => $profile['name'], 'progress_percent' => $status['progress_percent'] ?? 0, ); } } return array( 'any_building' => ! empty( $building_profiles ), 'building_profiles' => $building_profiles, ); } /** * Ensure default profile exists. * * Creates a default profile if none exists. * * @return void * @throws \RuntimeException If database insert fails. */ public function ensureDefaultExists(): void { $default = $this->getDefault(); if ( $default ) { return; } global $wpdb; $suppress = $wpdb->suppress_errors( true ); $result = $wpdb->insert( $this->table_name, array( 'name' => 'Default', 'is_default' => 1, 'is_active' => 1, 'settings' => wp_json_encode( self::newProfileSettings() ), 'status' => wp_json_encode( self::newProfileStatus() ), 'created_at' => current_time( 'mysql' ), ), array( '%s', '%d', '%d', '%s', '%s', '%s' ) ); $wpdb->suppress_errors( $suppress ); if ( false === $result ) { $last_error = $wpdb->last_error; if ( strpos( $last_error, 'Duplicate entry' ) !== false || strpos( $last_error, '1062' ) !== false ) { return; } error_log( sprintf( '[AIPT] Failed to create default Store Index profile: %s', $last_error ?: 'Unknown database error' ) ); } } /** * Settings a new profile starts with: the default profile here, and every * further profile the Premium build creates. * * @return array */ public static function newProfileSettings(): array { return array( 'enabled' => false, 'max_products' => 10000, 'batch_size' => 100, 'categories' => array(), 'tags' => array(), 'stock_filter' => 'all', 'date_filter_days' => 0, 'filter_mode' => 'all', 'scheduled_enabled' => false, 'schedule_frequency' => 'daily', 'included_fields' => self::getDefaultIncludedFields(), ); } /** * Build status a new profile starts with. * * @return array */ public static function newProfileStatus(): array { return array( 'status' => 'idle', 'last_build' => null, 'product_count' => 0, 'category_count' => 0, 'file_size' => 0, 'trimmed_count' => 0, 'shard_count' => 0, 'error' => null, 'build_progress' => 0, 'progress_percent' => 0, 'processed_product_count' => 0, 'estimated_total_products' => 0, 'build_job_id' => 0, ); } /** * Validate a profile name. * * Shared by renaming here and by the Premium build's profile creation. * * @param string $name Profile name. * @return void * @throws \InvalidArgumentException If name is invalid. */ public function validateName( string $name ): void { if ( empty( $name ) ) { throw new \InvalidArgumentException( __( 'Profile name cannot be empty.', 'ai-product-tools' ) ); } if ( strlen( $name ) > self::MAX_NAME_LENGTH ) { throw new \InvalidArgumentException( sprintf( /* translators: %d: maximum name length */ __( 'Profile name cannot exceed %d characters.', 'ai-product-tools' ), self::MAX_NAME_LENGTH ) ); } if ( ! preg_match( '/^[a-zA-Z0-9 \-]+$/', $name ) ) { throw new \InvalidArgumentException( __( 'Profile name can only contain letters, numbers, spaces, and dashes.', 'ai-product-tools' ) ); } } /** * Format a profile row from database. * * @param array $row Database row. * @return array Formatted profile data. */ private function formatProfile( array $row ): array { return array( 'id' => (int) $row['id'], 'name' => $row['name'], 'is_default' => (bool) $row['is_default'], 'is_active' => (bool) $row['is_active'], 'settings' => json_decode( $row['settings'], true ) ?? array(), 'status' => json_decode( $row['status'], true ) ?? array(), 'created_at' => $row['created_at'], 'updated_at' => $row['updated_at'], ); } /** * Get default included fields for new profiles under the current plan. * * @return array Default fields. */ public static function getDefaultIncludedFields(): array { return self::buildDefaultIncludedFields( (array) apply_filters( 'aipt_index_validate_included_fields', self::DEFAULT_INCLUDED_FIELDS ), (bool) apply_filters( 'aipt_index_can_use_business_fields', false ) ); } /** * Display-only variant of getDefaultIncludedFields(). * * Resolves BOTH the Business entitlement AND the field-validation clamp through * their cache-only filter siblings so it can be called while a page is rendering * (Store Index admin asset localization, the display-only available-fields route) * without risking a synchronous Freemius API call. Reaching for the authoritative * 'aipt_index_validate_included_fields' filter here would defeat the cache-only * entitlement resolved right below it, because the premium handler for that filter * (PremiumIndexService::validateIncludedFields) calls canUseBusinessFeatures(). * Profile writes must keep calling getDefaultIncludedFields(). * * @return array Default fields. */ public static function getDefaultIncludedFieldsForDisplay(): array { return self::buildDefaultIncludedFields( (array) apply_filters( 'aipt_index_validate_included_fields_cache_only', self::DEFAULT_INCLUDED_FIELDS ), (bool) apply_filters( 'aipt_index_can_use_business_fields_cache_only', false ) ); } /** * Apply the resolved Business entitlement to an already-validated field list. * * @param array $fields Candidate fields, post-validation-filter. * @param bool $can_use_business_fields Whether Business-only fields are allowed. * @return array Default fields. */ private static function buildDefaultIncludedFields( array $fields, bool $can_use_business_fields ): array { if ( $can_use_business_fields ) { return $fields; } return array_values( array_diff( $fields, array( 'sku' ) ) ); } /** * Get all available fields. * * @return array Available fields. */ public static function getAvailableFields(): array { return self::AVAILABLE_FIELDS; } /** * Get the store's registered global product attribute taxonomies. * * Backs both the admin picker (StoreIndexController::get_attribute_options()) * and the 'attributes' setting's sanitizer (IndexSettings), so a saved slug * list only ever holds attributes the picker can offer. Only global * (`pa_*`) attribute taxonomies are listed: they are the only attribute * slugs enumerable store-wide, unlike a per-product custom attribute's * name. * * @return array Slug (e.g. 'pa_color') and display label. */ public static function getAvailableAttributeOptions(): array { if ( ! function_exists( 'wc_get_attribute_taxonomies' ) ) { return array(); } $options = array(); foreach ( (array) wc_get_attribute_taxonomies() as $attribute ) { if ( ! isset( $attribute->attribute_name ) || '' === $attribute->attribute_name ) { continue; } $slug = 'pa_' . $attribute->attribute_name; if ( ! empty( $attribute->attribute_label ) ) { $label = (string) $attribute->attribute_label; } elseif ( function_exists( 'wc_attribute_label' ) ) { $label = (string) wc_attribute_label( $slug ); } else { $label = $slug; } $options[] = array( 'slug' => $slug, 'label' => $label, ); } return $options; } /** * Get the store's registered global product attribute taxonomy slugs. * * @return string[] Attribute taxonomy slugs, e.g. 'pa_color'. */ public static function getAvailableAttributeSlugs(): array { return array_column( self::getAvailableAttributeOptions(), 'slug' ); } /** * Get available fields for the current user's plan. * * Uses filter hook to allow premium code to expand available fields. * Free users: limited fields (default), Premium users: all fields (via filter). * * SECURITY NOTE: Default MUST be restrictive (free tier fields) because * when premium code is stripped from free build, filters return their defaults. * * @return array Available fields for current plan. */ public static function getAvailableFieldsForPlan(): array { return apply_filters( 'aipt_index_available_fields_for_plan', self::FREE_TIER_FIELDS ); } /** * Get premium-only fields list. * * Uses filter hook to get premium-only fields from premium code. * * @return array Premium-only fields. */ public static function getPremiumOnlyFields(): array { return apply_filters( 'aipt_index_premium_only_fields', array() ); } /** * Check if user can filter by categories. * * Uses filter hook to check premium capability. * Free users: false (default), Premium users: true (via filter). * * SECURITY NOTE: Default MUST be false because when premium code is * stripped from free build, filters return their defaults. * * @return bool True if category filtering allowed. */ public static function canFilterCategories(): bool { return apply_filters( 'aipt_index_can_filter_categories', false ); } /** * Check if user can filter by tags. * * Uses filter hook to check premium capability. * Free users: false (default), Premium users: true (via filter). * * SECURITY NOTE: Default MUST be false because when premium code is * stripped from free build, filters return their defaults. * * @return bool True if tag filtering allowed. */ public static function canFilterTags(): bool { return apply_filters( 'aipt_index_can_filter_tags', false ); } /** * Get mandatory fields that cannot be disabled. * * @return array Mandatory fields. */ public static function getMandatoryFields(): array { return self::MANDATORY_FIELDS; } /** * Ensure mandatory fields are included in a field list. * * @param array $fields Field list to check. * @return array Field list with mandatory fields included. */ public static function ensureMandatoryFields( array $fields ): array { return array_values( array_unique( array_merge( self::MANDATORY_FIELDS, $fields ) ) ); } /** * Global settings keys (shared across all profiles). * * @var array */ private const GLOBAL_SETTINGS_KEYS = array( 'enabled', 'max_products', 'batch_size', 'scheduled_enabled', 'schedule_frequency', ); /** * Get global settings from default profile. * * Global settings are stored in the default profile and apply to all profiles. * * @return array Global settings. */ public function getGlobalSettings(): array { $default = $this->getDefault(); if ( ! $default ) { return array( 'enabled' => false, 'max_products' => 10000, 'batch_size' => 100, 'scheduled_enabled' => false, 'schedule_frequency' => 'daily', ); } return $this->extractGlobalSettings( $default['settings'] ); } /** * Extract the global settings from a default profile's settings. * * @param array $settings Default profile settings. * @return array Global settings. */ private function extractGlobalSettings( array $settings ): array { $global = array(); foreach ( self::GLOBAL_SETTINGS_KEYS as $key ) { $global[ $key ] = $settings[ $key ] ?? $this->getGlobalDefault( $key ); } return $global; } /** * Update global settings in default profile. * * @param array $settings Global settings to update. * @return bool True on success. * @throws \RuntimeException If default profile not found. */ public function updateGlobalSettings( array $settings ): bool { $this->last_coerced_fields = array(); $this->last_coerced_reason = ''; $this->last_plan_denial = null; $default = $this->getDefault(); if ( ! $default ) { throw new \RuntimeException( __( 'Default profile not found.', 'ai-product-tools' ) ); } $global_updates = array(); foreach ( self::GLOBAL_SETTINGS_KEYS as $key ) { if ( array_key_exists( $key, $settings ) ) { $global_updates[ $key ] = $this->sanitizeGlobalSetting( $key, $settings[ $key ] ); } } if ( empty( $global_updates ) ) { return true; } $current_settings = $default['settings']; $old_globals = $this->extractGlobalSettings( $current_settings ); if ( ! empty( $global_updates['scheduled_enabled'] ) && empty( $old_globals['scheduled_enabled'] ) && ! apply_filters( 'aipt_index_scheduled_updates_enabled', false ) ) { $reason = PlanDenial::reason( 'scheduledIndexUpdates', PlanDenial::PLAN_PAID ); if ( PlanDenial::isVerificationUnavailable( $reason ) ) { $this->last_plan_denial = PlanDenial::error( 'scheduledIndexUpdates', PlanDenial::PLAN_PAID, __( 'Business plan adds scheduled index updates.', 'ai-product-tools' ), 'premium_required', array( 'fields' => array( 'scheduled_enabled' ) ) ); return false; } $global_updates['scheduled_enabled'] = false; $this->last_coerced_fields = array( 'scheduled_enabled' ); $this->last_coerced_reason = $reason; } $new_settings = array_merge( $current_settings, $global_updates ); global $wpdb; $result = $wpdb->update( $this->table_name, array( 'settings' => wp_json_encode( $new_settings ), 'updated_at' => current_time( 'mysql' ), ), array( 'id' => $default['id'] ), array( '%s', '%s' ), array( '%d' ) ); if ( false === $result ) { return false; } /** * Fires after the global Store Index settings were saved. * * Both save routes (/store-index/global-settings and the global keys of * /store-index/settings) end here, so the premium scheduler schedules or * unschedules the recurring rebuild from this action. * * @since 2.7.2 * * @param array $new_globals Global settings after the save. * @param array $old_globals Global settings before the save. */ do_action( 'aipt_index_global_settings_updated', $this->extractGlobalSettings( $new_settings ), $old_globals ); return true; } /** * Global setting keys clamped by a plan gate during the last updateGlobalSettings(). * * @return string[] */ public function getLastCoercedFields(): array { return $this->last_coerced_fields; } /** * Denial reason of the clamps applied during the last updateGlobalSettings(). * * @return string A PlanDenial reason, or '' when nothing was clamped. */ public function getLastCoercedReason(): string { return $this->last_coerced_reason; } /** * Plan denial that rejected the last updateGlobalSettings(). * * @return WP_Error|null */ public function getLastPlanDenial(): ?WP_Error { return $this->last_plan_denial; } /** * Get default value for a global setting. * * @param string $key Setting key. * @return mixed Default value. */ private function getGlobalDefault( string $key ) { $defaults = array( 'enabled' => false, 'max_products' => 10000, 'batch_size' => 100, 'scheduled_enabled' => false, 'schedule_frequency' => 'daily', ); return $defaults[ $key ] ?? null; } /** * Sanitize a global setting value. * * @param string $key Setting key. * @param mixed $value Setting value. * @return mixed Sanitized value. */ private function sanitizeGlobalSetting( string $key, $value ) { switch ( $key ) { case 'enabled': case 'scheduled_enabled': return (bool) $value; case 'max_products': $value = (int) $value; return max( 1, min( 50000, $value ) ); case 'batch_size': $value = (int) $value; return max( 50, min( 500, $value ) ); case 'schedule_frequency': $valid = array( 'hourly', 'two_hourly', 'six_hourly', 'daily' ); return in_array( $value, $valid, true ) ? $value : 'daily'; default: return $value; } } /** * Get global settings keys. * * @return array Global settings keys. */ public static function getGlobalSettingsKeys(): array { return self::GLOBAL_SETTINGS_KEYS; } /** * Clean up chatbot settings if they reference a deleted profile. * * Resets the chatbot's index_profile setting to the default profile if it * was pointing to the deleted profile, ensuring a valid profile is always set. * * @param int $deleted_profile_id The ID of the profile being deleted. * @return void */ private function cleanupChatbotProfileReference( int $deleted_profile_id ): void { $option_key = 'aipt_chatbot_settings'; $settings = get_option( $option_key, array() ); if ( isset( $settings['behavior']['index_profile'] ) && (int) $settings['behavior']['index_profile'] === $deleted_profile_id ) { $default_profile = $this->getDefault(); if ( $default_profile ) { $settings['behavior']['index_profile'] = (int) $default_profile['id']; update_option( $option_key, $settings ); } else { } } } }