<?php

namespace FleekDash\Controllers\Schema\FieldProviders;

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

/**
 * Meta Box Field Provider
 *
 * Handles Meta Box plugin fields integration
 *
 * @package FleekDash\Controllers\Schema\FieldProviders
 */
class MetaBoxFieldProvider
{
    /**
     * Get Meta Box fields for a post type
     *
     * @param string $post_type The post type to get fields for
     * @return array Array of field configurations
     */
    public function getMetaBoxFields($post_type)
    {
        $fields = [];

        // Check if Meta Box is active
        if (!class_exists('RWMB_Loader')) {
            return $fields;
        }

        try {
            // Get Meta Box field groups
            if (function_exists('rwmb_get_registry')) {
                $registry = \rwmb_get_registry('meta_box');
                $meta_boxes = $registry->all();

                foreach ($meta_boxes as $meta_box) {
                    if (in_array($post_type, $meta_box->post_types ?? [])) {
                        foreach ($meta_box->fields as $field) {
                            $fields[$field['id']] = [
                                'name' => $field['id'],
                                'label' => $field['name'] ?? $field['id'],
                                'type' => $this->mapMetaBoxTypeToComponent($field['type']),
                                'component' => $this->getComponentFromMetaBoxType($field['type']),
                                'required' => $field['required'] ?? false,
                                'validation' => [],
                                'description' => $field['desc'] ?? '',
                                'default' => $field['std'] ?? null,
                                'meta_key' => $field['id'],
                                'source' => 'Meta Box',
                                'source_priority' => 9,
                                'metabox_type' => $field['type']
                            ];
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            // Meta Box functions might fail, continue silently
            fleekdash_log_error("FleekDash: Error in getMetaBoxFields: " . $e->getMessage());
        }

        return $fields;
    }

    /**
     * Map Meta Box field type to component type
     *
     * @param string $mb_type Meta Box field type
     * @return string Mapped component type
     */
    private function mapMetaBoxTypeToComponent($mb_type)
    {
        $type_map = [
            'text' => 'text',
            'textarea' => 'textarea',
            'number' => 'number',
            'email' => 'email',
            'url' => 'url',
            'password' => 'password',
            'wysiwyg' => 'richtext',
            'image' => 'media',
            'image_upload' => 'media',
            'file' => 'file',
            'file_upload' => 'file',
            'select' => 'select',
            'select_advanced' => 'select',
            'checkbox' => 'checkbox',
            'checkbox_list' => 'checkbox',
            'radio' => 'radio',
            'switch' => 'boolean',
            'date' => 'date',
            'datetime' => 'datetime',
            'time' => 'time',
            'color' => 'color',
            'range' => 'range',
            'slider' => 'range',
            'user' => 'select',
            'post' => 'select',
            'taxonomy' => 'multiselect'
        ];

        return $type_map[$mb_type] ?? 'text';
    }

    /**
     * Get component from Meta Box type
     *
     * @param string $mb_type Meta Box field type
     * @return string Component name
     */
    private function getComponentFromMetaBoxType($mb_type)
    {
        $component_map = [
            'text' => 'input',
            'textarea' => 'textarea',
            'number' => 'input',
            'email' => 'input',
            'url' => 'input',
            'password' => 'input',
            'wysiwyg' => 'textarea',
            'image' => 'file',
            'image_upload' => 'file',
            'file' => 'file',
            'file_upload' => 'file',
            'select' => 'select',
            'select_advanced' => 'select',
            'checkbox' => 'checkbox',
            'checkbox_list' => 'checkbox',
            'radio' => 'radio',
            'switch' => 'checkbox',
            'date' => 'input',
            'datetime' => 'input',
            'time' => 'input',
            'color' => 'input',
            'range' => 'input',
            'slider' => 'input',
            'user' => 'select',
            'post' => 'select',
            'taxonomy' => 'select'
        ];

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