<?php

namespace FleekDash\Controllers\Schema\FieldProviders;

if (!\function_exists('fleekdash_log_debug')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

/**
 * REST Field Provider
 *
 * Handles WordPress REST API registered meta fields
 *
 * @package FleekDash\Controllers\Schema\FieldProviders
 */
class RESTFieldProvider
{
    /**
     * Get WordPress REST API registered meta fields
     *
     * @param string $post_type The post type to get fields for
     * @return array Array of field configurations
     */
    public function getRESTMetaFields(string $post_type): array
    {
        global $wp_meta_keys;
        $fields = [];

        if (isset($wp_meta_keys['post'])) {
            foreach ($wp_meta_keys['post'] as $meta_key => $meta_config) {
                $object_subtype = $meta_config['object_subtype'] ?? '';
                if ($object_subtype !== '' && $object_subtype !== $post_type) {
                    continue;
                }

                if (isset($meta_config['show_in_rest']) && $meta_config['show_in_rest']) {
                    $field_type = $meta_config['type'] ?? 'string';
                    $component = $this->getComponentFromType($field_type);

                    $fields[$meta_key] = [
                        'name' => $meta_key,
                        'label' => $this->formatFieldLabel($meta_key),
                        'type' => $field_type,
                        'component' => $component,
                        'required' => false,
                        'validation' => $this->getValidationFromMeta($meta_config),
                        'description' => $meta_config['description'] ?? '',
                        'default' => $meta_config['default'] ?? null,
                        'meta_key' => $meta_key,
                        'source' => 'WordPress REST',
                        'source_priority' => 7
                    ];
                }
            }
        }

        return $fields;
    }

    /**
     * Get existing meta fields from database
     * Only include fields that haven't been detected by higher-priority sources
     *
     * @param string $post_type The post type to get fields for
     * @param array $existing_keys Meta keys already detected by higher priority sources
     * @return array Array of field configurations
     */
    public function getExistingMetaFields($post_type, $existing_keys = [])
    {
        global $wpdb;
        $fields = [];

        try {
            // Get a sample of recent posts of this type to extract meta keys
            $post_ids = $wpdb->get_col($wpdb->prepare("
                SELECT ID
                FROM {$wpdb->posts}
                WHERE post_type = %s
                AND post_status IN ('publish', 'draft', 'private')
                ORDER BY ID DESC
                LIMIT 10
            ", $post_type));

            if (!empty($post_ids)) {
                $meta_keys = $wpdb->get_col("
                    SELECT DISTINCT meta_key
                    FROM {$wpdb->postmeta}
                    WHERE post_id IN (" . implode(',', array_map('intval', $post_ids)) . ")
                    AND meta_key NOT LIKE '\_%'
                    AND meta_key NOT IN ('_edit_lock', '_edit_last')
                    ORDER BY meta_key
                ");

                foreach ($meta_keys as $meta_key) {
                    // Skip if already detected by higher-priority sources
                    if (in_array($meta_key, $existing_keys)) {
                        continue;
                    }

                    $fields[$meta_key] = [
                        'name' => $meta_key,
                        'label' => $this->formatFieldLabel($meta_key),
                        'type' => 'text',
                        'component' => 'input',
                        'required' => false,
                        'validation' => [],
                        'description' => "Meta field: {$meta_key}",
                        'default' => null,
                        'meta_key' => $meta_key,
                        'source' => 'Database Meta',
                        'source_priority' => 1
                    ];
                }
            }
        } catch (\Exception $e) {
            // Database query might fail, continue silently
            fleekdash_log_error("FleekDash: Error in getExistingMetaFields: " . $e->getMessage());
        }

        return $fields;
    }

    /**
     * Helper: Get component from field type
     *
     * @param string $type Field type
     * @return string Component name
     */
    private function getComponentFromType($type)
    {
        $component_map = [
            'string' => 'input',
            'number' => 'input',
            'integer' => 'input',
            'boolean' => 'checkbox',
            'array' => 'multiselect',
            'textarea' => 'textarea'
        ];

        return $component_map[$type] ?? 'input';
    }

    /**
     * Helper: Format field key into readable label
     *
     * @param string $key Field key
     * @return string Formatted label
     */
    private function formatFieldLabel($key)
    {
        return ucwords(str_replace(['_', '-'], ' ', $key));
    }

    /**
     * Helper: Get validation rules from meta config (REST schema subset).
     *
     * @param array<string, mixed> $meta_config Meta configuration from register_meta / register_post_meta
     * @return array<string, mixed> Validation rules for the schema UI
     */
    private function getValidationFromMeta(array $meta_config): array
    {
        $rules = [];
        if (isset($meta_config['single'])) {
            $rules['single'] = (bool) $meta_config['single'];
        }

        $show_in_rest = $meta_config['show_in_rest'] ?? null;
        $schema = null;
        if (is_array($show_in_rest) && isset($show_in_rest['schema']) && is_array($show_in_rest['schema'])) {
            $schema = $show_in_rest['schema'];
        }

        if ($schema !== null) {
            foreach (['minimum', 'maximum', 'minLength', 'maxLength', 'pattern'] as $key) {
                if (isset($schema[$key])) {
                    $rules[$key] = $schema[$key];
                }
            }
        }

        return $rules;
    }
}
