<?php
/**
 * Meta Cleanup API Endpoint - COMPLETE FINAL VERSION
 * 
 * Handles cleanup of ALL orphaned meta data with full control
 *
 * @package HvnlyNab\Api\Type\Builders
 * @since 2.0.0
 */

namespace HvnlyNab\Api\Type\Builders;

use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}
class MetaCleanup
{
    /**
     * Storage key for property builder sections
     *
     * @var string
     */
    private $storage_key = 'hvnly_property_builder.sections';

    /**
     * API namespace
     *
     * @var string
     */
    private $namespace = 'hvnlynab/v1';

    /**
     * Route base
     *
     * @var string
     */
    private $route_base = 'meta-cleanup';

    /**
     * Constructor
     */
    public function __construct()
    {
        add_action('rest_api_init', [$this, 'routes']);
    }

    /**
     * Register REST API routes
     */
    public function routes()
    {
        // GET orphaned meta keys
        register_rest_route($this->namespace, '/' . $this->route_base . '/orphaned', [
            'methods' => 'GET',
            'callback' => [$this, 'get_orphaned_meta'],
            'permission_callback' => [$this, 'get_per'],
            'args' => [
                'property_id' => [
                    'required' => false,
                    'type' => 'integer',
                    'sanitize_callback' => 'absint'
                ]
            ]
        ]);

        // POST cleanup orphaned meta
        register_rest_route($this->namespace, '/' . $this->route_base . '/cleanup', [
            'methods' => 'POST',
            'callback' => [$this, 'cleanup_orphaned_meta'],
            'permission_callback' => [$this, 'create_per'],
            'args' => [
                'fields' => [
                    'required' => true,
                    'type' => 'array',
                    'validate_callback' => function($param) {
                        return is_array($param) && !empty($param);
                    }
                ],
                'property_id' => [
                    'required' => false,
                    'type' => 'integer',
                    'sanitize_callback' => 'absint'
                ]
            ]
        ]);

        // POST reset and cleanup combined
        register_rest_route($this->namespace, '/' . $this->route_base . '/reset-and-cleanup', [
            'methods' => 'POST',
            'callback' => [$this, 'reset_and_cleanup_aggressive'],
            'permission_callback' => [$this, 'create_per'],
        ]);

        // GET cleanup stats
        register_rest_route($this->namespace, '/' . $this->route_base . '/stats', [
            'methods' => 'GET',
            'callback' => [$this, 'get_cleanup_stats'],
            'permission_callback' => [$this, 'get_per'],
        ]);

        // POST complete database cleanup
        register_rest_route($this->namespace, '/' . $this->route_base . '/cleanup-all', [
            'methods' => 'POST',
            'callback' => [$this, 'cleanup_all_orphaned'],
            'permission_callback' => [$this, 'create_per'],
        ]);

        // POST final cleanup - removes only old legacy data
        register_rest_route($this->namespace, '/' . $this->route_base . '/final-cleanup', [
            'methods' => 'POST',
            'callback' => [$this, 'final_cleanup'],
            'permission_callback' => [$this, 'create_per'],
        ]);
    }

    /**
     * Permission callback for GET requests
     */
    public function get_per()
    {
        return current_user_can('manage_options');
    }

    /**
     * Permission callback for POST requests
     */
    public function create_per()
    {
        return current_user_can('manage_options');
    }

    /**
     * AGGRESSIVE Reset and cleanup combined operation
     */
    public function reset_and_cleanup_aggressive($request)
    {
        try {
            // Verify nonce
            $nonce = $request->get_header('X-WP-Nonce');
            if (!wp_verify_nonce($nonce, 'wp_rest')) {
                return new WP_Error('rest_forbidden', __('Invalid nonce', 'havenlytics'), ['status' => 403]);
            }

            // Delete the builder configuration
            $reset_result = delete_option($this->storage_key);

            // Get ALL properties
            $properties = get_posts([
                'post_type' => 'hvnly_property',
                'posts_per_page' => -1,
                'post_status' => 'any',
                'fields' => 'ids',
                'suppress_filters' => true
            ]);

            $total_deleted = 0;
            $deleted_by_type = [
                'gallery' => 0,
                'video' => 0,
                'map' => 0,
                'legacy' => 0,
                'other' => 0
            ];

            // For each property, clean up old meta
            foreach ($properties as $property_id) {
                $all_meta = get_post_meta($property_id);
                
                foreach ($all_meta as $meta_key => $meta_values) {
                    // Skip system keys
                    if ($this->is_system_key($meta_key)) {
                        continue;
                    }

                    // Check if this is old plugin data
                    if (strpos($meta_key, 'gallery_') === 0 || 
                        strpos($meta_key, 'video_') === 0 || 
                        strpos($meta_key, 'map_') === 0 ||
                        strpos($meta_key, '_hvnly_gallery') === 0 ||
                        strpos($meta_key, '_hvnly_video') === 0 ||
                        strpos($meta_key, '_hvnly_map') === 0 ||
                        strpos($meta_key, '_havenlytics_') === 0) {
                        
                        $deleted = delete_post_meta($property_id, $meta_key);
                        if ($deleted) {
                            $total_deleted++;
                            
                            if (strpos($meta_key, 'gallery_') === 0) {
                                $deleted_by_type['gallery']++;
                            } elseif (strpos($meta_key, 'video_') === 0) {
                                $deleted_by_type['video']++;
                            } elseif (strpos($meta_key, 'map_') === 0) {
                                $deleted_by_type['map']++;
                            } elseif (strpos($meta_key, '_hvnly_') === 0 || strpos($meta_key, '_havenlytics_') === 0) {
                                $deleted_by_type['legacy']++;
                            } else {
                                $deleted_by_type['other']++;
                            }
                        }
                    }
                }
            }

            return rest_ensure_response([
                'success' => true,
                'message' => sprintf(
                    /* translators: %d: number of deleted entries */
                    __('Configuration reset and %d orphaned entries cleaned up', 'havenlytics'),
                    $total_deleted
                ),
                'reset_complete' => true,
                'cleanup_complete' => true,
                'deleted_count' => $total_deleted,
                'deleted_by_type' => $deleted_by_type,
                'properties_processed' => count($properties)
            ]);

        } catch (\Exception $e) {
            return new WP_Error(
                'reset_cleanup_failed',
                __('Failed to reset and cleanup', 'havenlytics'),
                ['status' => 500]
            );
        }
    }

    /**
     * Cleanup ALL orphaned meta across all properties
     */
    public function cleanup_all_orphaned($request)
    {
        try {
            $nonce = $request->get_header('X-WP-Nonce');
            if (!wp_verify_nonce($nonce, 'wp_rest')) {
                return new WP_Error('rest_forbidden', __('Invalid nonce', 'havenlytics'), ['status' => 403]);
            }

            // Get current field names from builder (if any)
            $current_fields = $this->get_current_field_names();
            
            // Get all properties
            $properties = get_posts([
                'post_type' => 'hvnly_property',
                'posts_per_page' => -1,
                'post_status' => 'any',
                'fields' => 'ids',
                'suppress_filters' => true
            ]);

            $total_deleted = 0;
            $deleted_keys = [];

            foreach ($properties as $property_id) {
                $all_meta = get_post_meta($property_id);
                
                foreach ($all_meta as $meta_key => $meta_values) {
                    // Skip if it's a current field or system key
                    if (in_array($meta_key, $current_fields, true) || $this->is_system_key($meta_key)) {
                        continue;
                    }

                    // Check if it's old plugin data
                    if (strpos($meta_key, 'gallery_') === 0 || 
                        strpos($meta_key, 'video_') === 0 || 
                        strpos($meta_key, 'map_') === 0 ||
                        strpos($meta_key, '_hvnly_') === 0 ||
                        strpos($meta_key, '_havenlytics_') === 0) {
                        
                        $deleted = delete_post_meta($property_id, $meta_key);
                        if ($deleted) {
                            $total_deleted++;
                            if (!in_array($meta_key, $deleted_keys, true)) {
                                $deleted_keys[] = $meta_key;
                            }
                        }
                    }
                }
            }

            return rest_ensure_response([
                'success' => true,
                'message' => sprintf(
                    /* translators: %d: number of deleted entries */
                    __('Cleaned up %d orphaned meta entries', 'havenlytics'),
                    $total_deleted
                ),
                'deleted_count' => $total_deleted,
                'deleted_keys_sample' => array_slice($deleted_keys, 0, 20),
                'properties_processed' => count($properties)
            ]);

        } catch (\Exception $e) {
            return new WP_Error(
                'cleanup_failed',
                __('Failed to cleanup meta', 'havenlytics'),
                ['status' => 500]
            );
        }
    }

    /**
     * FINAL cleanup - removes old legacy data while keeping active fields
     */
    public function final_cleanup($request)
    {
        try {
            $nonce = $request->get_header('X-WP-Nonce');
            if (!wp_verify_nonce($nonce, 'wp_rest')) {
                return new WP_Error('rest_forbidden', __('Invalid nonce', 'havenlytics'), ['status' => 403]);
            }

            // Get all properties
            $properties = get_posts([
                'post_type' => 'hvnly_property',
                'posts_per_page' => -1,
                'post_status' => 'any',
                'fields' => 'ids',
                'suppress_filters' => true
            ]);

            // Keys to KEEP (active/required)
            $keep_keys = [
                // WordPress system keys
                '_edit_last',
                '_edit_lock',
                '_thumbnail_id',
                '_wp_old_slug',
                
                // Havenlytics required keys
                '_hvnly_unique_property_id',
                '_hvnly_property_featured',
                '_hvnly_property_views',
                '_hvnly_property_view_analytics',
                '_hvnly_property_kitchen',
                
                // Active form data
                '_hvnly_property_booking_form_shortcode',
                '_hvnly_property_booking_form_select_shortcode',
                '_hvnly_property_callback_form_shortcode',
                '_hvnly_property_callback_form_select_shortcode',
                '_hvnly_property_arrange_viewing_form_shortcode',
                '_hvnly_property_arrange_viewing_form_select_shortcode',
            ];

            // Preset field prefixes to KEEP
            $preset_prefixes = [
                'preset_hvnly_property_field_'
            ];

            // Keys to DELETE (old/legacy data)
            $delete_patterns = [
                '_hvnly_property_gallery_',
                '_hvnly_dynamic_gallery_fld_',
                '_hvnly_property_video_type',
                '_hvnly_property_youtube_',
                '_hvnly_property_vimeo_',
                '_hvnly_property_map_',
                '_hvnly_property_action_tool_',
                '_hvnly_property_virtual_tour',
                '_hvnly_property_floorplan_img',
                '_hvnly_property_brochure_pdf',
                '_hvnly_property_epc_pdf',
            ];

            $total_deleted = 0;
            $deleted_keys = [];
            $kept_keys = [];

            foreach ($properties as $property_id) {
                $all_meta = get_post_meta($property_id);
                
                foreach ($all_meta as $meta_key => $meta_values) {
                    // Skip if it's a keep key
                    if (in_array($meta_key, $keep_keys, true)) {
                        $kept_keys[] = $meta_key;
                        continue;
                    }

                    // Skip preset fields
                    $is_preset = false;
                    foreach ($preset_prefixes as $prefix) {
                        if (strpos($meta_key, $prefix) === 0) {
                            $is_preset = true;
                            $kept_keys[] = $meta_key;
                            break;
                        }
                    }
                    if ($is_preset) {
                        continue;
                    }

                    // Check if it matches any delete pattern
                    foreach ($delete_patterns as $pattern) {
                        if (strpos($meta_key, $pattern) === 0) {
                            $deleted = delete_post_meta($property_id, $meta_key);
                            if ($deleted) {
                                $total_deleted++;
                                $deleted_keys[] = $meta_key;
                            }
                            break;
                        }
                    }
                }
            }

            return rest_ensure_response([
                'success' => true,
                'message' => sprintf(
                    /* translators: 1: number of deleted entries, 2: number of kept keys */
                    __('Final cleanup removed %1$d old entries. Kept %2$d active keys.', 'havenlytics'),
                    $total_deleted,
                    count(array_unique($kept_keys))
                ),
                'deleted_count' => $total_deleted,
                'deleted_keys_sample' => array_slice($deleted_keys, 0, 20),
                'kept_keys_count' => count(array_unique($kept_keys)),
                'properties_processed' => count($properties)
            ]);

        } catch (\Exception $e) {
            return new WP_Error(
                'cleanup_failed',
                __('Failed to cleanup meta', 'havenlytics'),
                ['status' => 500]
            );
        }
    }

    /**
     * Get orphaned meta keys 
     */
    public function get_orphaned_meta($request)
    {
        try {
            $nonce = $request->get_header('X-WP-Nonce');
            if (!wp_verify_nonce($nonce, 'wp_rest')) {
                return new WP_Error('rest_forbidden', __('Invalid nonce', 'havenlytics'), ['status' => 403]);
            }

            global $wpdb;
            $property_id = $request->get_param('property_id');

            // Get current field names from builder configuration
            $current_fields = $this->get_current_field_names();

            // Build query for meta keys with proper LIKE placeholders
            $like_pattern = '%_hvnly_%';
            
            // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            if ($property_id) {
                // For single property - directly use prepare in get_col
                $meta_keys = $wpdb->get_col(
                    $wpdb->prepare(
                        "SELECT DISTINCT meta_key FROM {$wpdb->postmeta} 
                        WHERE post_id = %d AND meta_key LIKE %s",
                        $property_id,
                        $wpdb->esc_like($like_pattern)
                    )
                );
                
                // Get gallery keys for this property
                $gallery_keys = $wpdb->get_col(
                    $wpdb->prepare(
                        "SELECT DISTINCT meta_key FROM {$wpdb->postmeta} 
                        WHERE post_id = %d AND meta_key LIKE %s",
                        $property_id,
                        $wpdb->esc_like('gallery_') . '%'
                    )
                );
                
                // Get video keys for this property
                $video_keys = $wpdb->get_col(
                    $wpdb->prepare(
                        "SELECT DISTINCT meta_key FROM {$wpdb->postmeta} 
                        WHERE post_id = %d AND meta_key LIKE %s",
                        $property_id,
                        $wpdb->esc_like('video_') . '%'
                    )
                );
                
                // Get map keys for this property
                $map_keys = $wpdb->get_col(
                    $wpdb->prepare(
                        "SELECT DISTINCT meta_key FROM {$wpdb->postmeta} 
                        WHERE post_id = %d AND meta_key LIKE %s",
                        $property_id,
                        $wpdb->esc_like('map_') . '%'
                    )
                );
                
                // Get havenlytics keys for this property
                $havenlytics_keys = $wpdb->get_col(
                    $wpdb->prepare(
                        "SELECT DISTINCT meta_key FROM {$wpdb->postmeta} 
                        WHERE post_id = %d AND meta_key LIKE %s",
                        $property_id,
                        $wpdb->esc_like('_havenlytics_') . '%'
                    )
                );
            } else {
                // For all properties
                $meta_keys = $wpdb->get_col(
                    $wpdb->prepare(
                        "SELECT DISTINCT meta_key FROM {$wpdb->postmeta} 
                        WHERE meta_key LIKE %s",
                        $wpdb->esc_like($like_pattern)
                    )
                );
                
                // Get gallery keys
                $gallery_keys = $wpdb->get_col(
                    $wpdb->prepare(
                        "SELECT DISTINCT meta_key FROM {$wpdb->postmeta} 
                        WHERE meta_key LIKE %s",
                        $wpdb->esc_like('gallery_') . '%'
                    )
                );
                
                // Get video keys
                $video_keys = $wpdb->get_col(
                    $wpdb->prepare(
                        "SELECT DISTINCT meta_key FROM {$wpdb->postmeta} 
                        WHERE meta_key LIKE %s",
                        $wpdb->esc_like('video_') . '%'
                    )
                );
                
                // Get map keys
                $map_keys = $wpdb->get_col(
                    $wpdb->prepare(
                        "SELECT DISTINCT meta_key FROM {$wpdb->postmeta} 
                        WHERE meta_key LIKE %s",
                        $wpdb->esc_like('map_') . '%'
                    )
                );
                
                // Get havenlytics keys
                $havenlytics_keys = $wpdb->get_col(
                    $wpdb->prepare(
                        "SELECT DISTINCT meta_key FROM {$wpdb->postmeta} 
                        WHERE meta_key LIKE %s",
                        $wpdb->esc_like('_havenlytics_') . '%'
                    )
                );
            }
            // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            
            // Merge all keys
            $meta_keys = array_merge($meta_keys, $gallery_keys, $video_keys, $map_keys, $havenlytics_keys);
            $meta_keys = array_unique($meta_keys);

            if (empty($meta_keys)) {
                $meta_keys = [];
            }

            // Find orphaned keys
            $orphaned = array_diff($meta_keys, $current_fields);
            $orphaned = array_filter($orphaned, [$this, 'is_not_system_key']);

            // Group by type
            $grouped = [
                'gallery' => [],
                'video' => [],
                'map' => [],
                'legacy' => [],
                'other' => []
            ];

            foreach ($orphaned as $key) {
                if (strpos($key, 'gallery_') === 0) {
                    $grouped['gallery'][] = $key;
                } elseif (strpos($key, 'video_') === 0) {
                    $grouped['video'][] = $key;
                } elseif (strpos($key, 'map_') === 0) {
                    $grouped['map'][] = $key;
                } elseif (strpos($key, '_hvnly_') === 0 || strpos($key, '_havenlytics_') === 0) {
                    $grouped['legacy'][] = $key;
                } else {
                    $grouped['other'][] = $key;
                }
            }

            return rest_ensure_response([
                'success' => true,
                'data' => $grouped,
                'total' => count($orphaned),
                'property_id' => $property_id
            ]);

        } catch (\Exception $e) {
            return new WP_Error(
                'fetch_failed',
                __('Failed to fetch orphaned meta', 'havenlytics'),
                ['status' => 500]
            );
        }
    }

    /**
     * Cleanup orphaned meta data for specific fields
     */
    public function cleanup_orphaned_meta($request)
    {
        try {
            $nonce = $request->get_header('X-WP-Nonce');
            if (!wp_verify_nonce($nonce, 'wp_rest')) {
                return new WP_Error('rest_forbidden', __('Invalid nonce', 'havenlytics'), ['status' => 403]);
            }

            global $wpdb;
            $fields = $request->get_param('fields');
            $property_id = $request->get_param('property_id');

            if (empty($fields) || !is_array($fields)) {
                return new WP_Error(
                    'invalid_data',
                    __('Fields array is required', 'havenlytics'),
                    ['status' => 400]
                );
            }

            $deleted_count = 0;
            $deleted_keys = [];

            foreach ($fields as $field_name) {
                if (empty($field_name)) {
                    continue;
                }

                // Sanitize field name
                $field_name = sanitize_key($field_name);

                if ($property_id) {
                    $result = delete_post_meta($property_id, $field_name);
                    if ($result) {
                        $deleted_count++;
                        $deleted_keys[] = $field_name;
                    }
                } else {
                    // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    $result = $wpdb->delete(
                        $wpdb->postmeta,
                        ['meta_key' => $field_name],
                        ['%s']
                    );
                    // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
                    
                    if ($result !== false && $result > 0) {
                        $deleted_count += $result;
                        $deleted_keys[] = $field_name;
                    }
                }
            }

            return rest_ensure_response([
                'success' => true,
                'message' => sprintf(
                    /* translators: %d: number of deleted entries */
                    __('Successfully cleaned up %d orphaned meta entries', 'havenlytics'),
                    $deleted_count
                ),
                'deleted_count' => $deleted_count,
                'deleted_keys' => $deleted_keys
            ]);

        } catch (\Exception $e) {
            return new WP_Error(
                'cleanup_failed',
                __('Failed to cleanup meta', 'havenlytics'),
                ['status' => 500]
            );
        }
    }

    /**
     * Get cleanup statistics 
     */
    public function get_cleanup_stats($request)
    {
        try {
            $nonce = $request->get_header('X-WP-Nonce');
            if (!wp_verify_nonce($nonce, 'wp_rest')) {
                return new WP_Error('rest_forbidden', __('Invalid nonce', 'havenlytics'), ['status' => 403]);
            }

            global $wpdb;

            $total_properties = wp_count_posts('hvnly_property')->publish ?? 0;
            
            // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            // Get main _hvnly_ count
            $total_meta = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->postmeta} pm
                    INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
                    WHERE p.post_type = 'hvnly_property'
                    AND pm.meta_key LIKE %s",
                    $wpdb->esc_like('%_hvnly_%')
                )
            );
            
            // Get gallery count
            $gallery_count = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->postmeta} pm
                    INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
                    WHERE p.post_type = 'hvnly_property'
                    AND pm.meta_key LIKE %s",
                    $wpdb->esc_like('gallery_') . '%'
                )
            );
            
            // Get video count
            $video_count = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->postmeta} pm
                    INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
                    WHERE p.post_type = 'hvnly_property'
                    AND pm.meta_key LIKE %s",
                    $wpdb->esc_like('video_') . '%'
                )
            );
            
            // Get map count
            $map_count = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->postmeta} pm
                    INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
                    WHERE p.post_type = 'hvnly_property'
                    AND pm.meta_key LIKE %s",
                    $wpdb->esc_like('map_') . '%'
                )
            );
            
            // Get havenlytics count
            $havenlytics_count = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT COUNT(*) FROM {$wpdb->postmeta} pm
                    INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
                    WHERE p.post_type = 'hvnly_property'
                    AND pm.meta_key LIKE %s",
                    $wpdb->esc_like('_havenlytics_') . '%'
                )
            );
            // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            
            // Sum all counts
            $total_meta = (int) $total_meta + (int) $gallery_count + (int) $video_count + (int) $map_count + (int) $havenlytics_count;

            return rest_ensure_response([
                'success' => true,
                'data' => [
                    'total_properties' => (int) $total_properties,
                    'total_meta_entries' => (int) $total_meta,
                    'storage_key' => $this->storage_key
                ]
            ]);

        } catch (\Exception $e) {
            return new WP_Error(
                'stats_failed',
                __('Failed to get stats', 'havenlytics'),
                ['status' => 500]
            );
        }
    }

    /**
     * Get all current field names from builder configuration
     */
    private function get_current_field_names()
    {
        $sections = get_option($this->storage_key, []);
        $field_names = [];

        if (!is_array($sections)) {
            return $field_names;
        }

        foreach ($sections as $section) {
            if (empty($section['fields']) || !is_array($section['fields'])) {
                continue;
            }

            foreach ($section['fields'] as $field) {
                if (!empty($field['name'])) {
                    $field_names[] = sanitize_key($field['name']);
                } elseif (!empty($field['id'])) {
                    $field_names[] = sanitize_key($field['id']);
                }
            }
        }

        // Add system fields that should never be deleted
        $system_fields = [
            '_hvnly_property_featured',
            '_hvnly_unique_property_id',
            '_hvnly_property_views',
            '_thumbnail_id',
            '_wp_attached_file',
            '_wp_attachment_metadata',
            '_edit_lock',
            '_edit_last'
        ];

        return array_unique(array_merge($field_names, $system_fields));
    }

    /**
     * Check if key is a system key (should not be deleted)
     */
    private function is_system_key($key)
    {
        $system_patterns = [
            '_wp_',
            '_edit_',
            '_encloseme',
            '_pingme',
            '_oembed_',
            '_thumbnail_id'
        ];

        foreach ($system_patterns as $pattern) {
            if (strpos($key, $pattern) === 0) {
                return true;
            }
        }

        return false;
    }

    /**
     * Check if key is not a system key (for array filtering)
     */
    private function is_not_system_key($key)
    {
        return !$this->is_system_key($key);
    }
}