<?php

namespace FleekDash\Controllers\Schema\FieldProviders;

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

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

        // Check if ACF is active
        if (!function_exists('acf_get_field_groups')) {
            return $fields;
        }

        try {
            // Get field groups for this post type
            $field_groups = \acf_get_field_groups([
                'post_type' => $post_type
            ]);

            foreach ($field_groups as $group) {
                $group_fields = \acf_get_fields($group['key']);

                if ($group_fields) {
                    foreach ($group_fields as $field) {
                        $fields[$field['name']] = [
                            'name' => $field['name'],
                            'label' => $field['label'],
                            'type' => $this->mapACFTypeToComponent($field['type']),
                            'component' => $this->getComponentFromACFType($field['type']),
                            'required' => $field['required'] ?? false,
                            'validation' => $this->getACFValidation($field),
                            'description' => $field['instructions'] ?? '',
                            'default' => $field['default_value'] ?? null,
                            'meta_key' => $field['name'],
                            'source' => 'ACF',
                            'source_priority' => 10,
                            'field_group' => $group['title'],
                            'acf_type' => $field['type'],
                            'options' => $this->getACFFieldOptions($field)
                        ];
                    }
                }
            }
        } catch (\Exception $e) {
            // ACF functions might fail, continue silently
            fleekdash_log_error("FleekDash: Error in getACFFields: " . $e->getMessage());
        }

        return $fields;
    }

    /**
     * Map ACF field type to component type
     *
     * @param string $acf_type ACF field type
     * @return string Mapped component type
     */
    private function mapACFTypeToComponent($acf_type)
    {
        $type_map = [
            'text' => 'text',
            'textarea' => 'textarea',
            'number' => 'number',
            'email' => 'email',
            'url' => 'url',
            'password' => 'password',
            'wysiwyg' => 'richtext',
            'image' => 'media',
            'file' => 'file',
            'select' => 'select',
            'checkbox' => 'checkbox',
            'radio' => 'radio',
            'true_false' => 'boolean',
            'date_picker' => 'date',
            'date_time_picker' => 'datetime',
            'time_picker' => 'time',
            'color_picker' => 'color',
            'range' => 'range',
            'user' => 'select',
            'post_object' => 'select',
            'page_link' => 'select',
            'relationship' => 'multiselect',
            'taxonomy' => 'multiselect',
            'gallery' => 'gallery',
            'repeater' => 'repeater',
            'flexible_content' => 'flexible',
            'group' => 'group'
        ];

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

    /**
     * Get component from ACF type
     *
     * @param string $acf_type ACF field type
     * @return string Component name
     */
    private function getComponentFromACFType($acf_type)
    {
        $component_map = [
            'text' => 'input',
            'textarea' => 'textarea',
            'number' => 'input',
            'email' => 'input',
            'url' => 'input',
            'password' => 'input',
            'wysiwyg' => 'textarea',
            'image' => 'file',
            'file' => 'file',
            'select' => 'select',
            'checkbox' => 'checkbox',
            'radio' => 'radio',
            'true_false' => 'checkbox',
            'date_picker' => 'input',
            'date_time_picker' => 'input',
            'time_picker' => 'input',
            'color_picker' => 'input',
            'range' => 'input',
            'user' => 'select',
            'post_object' => 'select',
            'page_link' => 'select',
            'relationship' => 'select',
            'taxonomy' => 'select',
            'gallery' => 'file',
            'repeater' => 'textarea',
            'flexible_content' => 'textarea',
            'group' => 'textarea'
        ];

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

    /**
     * Get ACF field validation rules
     *
     * @param array $field ACF field configuration
     * @return array Validation rules
     */
    private function getACFValidation($field)
    {
        $validation = [];

        if ($field['required'] ?? false) {
            $validation['required'] = true;
        }

        if (isset($field['min_length']) && $field['min_length']) {
            $validation['minLength'] = (int) $field['min_length'];
        }

        if (isset($field['max_length']) && $field['max_length']) {
            $validation['maxLength'] = (int) $field['max_length'];
        }

        return $validation;
    }

    /**
     * Get ACF field options (for select, checkbox, radio fields)
     *
     * @param array $field ACF field configuration
     * @return array Field options
     */
    private function getACFFieldOptions($field)
    {
        $options = [];

        if (isset($field['choices']) && is_array($field['choices'])) {
            foreach ($field['choices'] as $value => $label) {
                $options[] = ['value' => $value, 'label' => $label];
            }
        }

        return $options;
    }
}
