<?php

namespace FleekDash\Controllers\Schema\FieldProviders;

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

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

        try {
            // DEFENSIVE: Don't access Voxel during plugin activation
            // This prevents errors when Voxel tries to process fields before WordPress is fully initialized
            if (defined('WP_INSTALLING') && WP_INSTALLING) {
                fleekdash_log_debug("FleekDash: Skipping Voxel fields during installation");
                return $fields;
            }

            // DEFENSIVE: Don't access Voxel if we're in activation hook context
            // Check if we're in activation by looking at the call stack
            $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5);
            foreach ($backtrace as $frame) {
                if (isset($frame['function']) && (
                    $frame['function'] === 'register_activation_hook' ||
                    $frame['function'] === 'activate_plugin' ||
                    (isset($frame['file']) && strpos($frame['file'], 'plugin.php') !== false && strpos($frame['function'], 'activate') !== false)
                )) {
                    fleekdash_log_debug("FleekDash: Skipping Voxel fields during plugin activation");
                    return $fields;
                }
            }

            fleekdash_log_debug("FleekDash: Checking Voxel for post type: {$post_type}");

            if (class_exists('\Voxel\Post_Type')) {
                fleekdash_log_debug("FleekDash: Voxel\Post_Type class found");

                // DEFENSIVE: Wrap Voxel access in try-catch to prevent fatal errors
                try {
                    $voxel_post_type = \Voxel\Post_Type::get($post_type);

                    if ($voxel_post_type) {
                        fleekdash_log_debug("FleekDash: Voxel post type found for {$post_type}");

                        // DEFENSIVE: Check if get_fields method exists and is callable
                        if (!method_exists($voxel_post_type, 'get_fields') || !is_callable([$voxel_post_type, 'get_fields'])) {
                            fleekdash_log_debug("FleekDash: Voxel get_fields method not available");
                            return $fields;
                        }

                        $voxel_fields = $voxel_post_type->get_fields();
                        fleekdash_log_debug("FleekDash: Found " . count($voxel_fields) . " Voxel fields");

                        foreach ($voxel_fields as $field) {
                            // DEFENSIVE: Validate field object before accessing methods
                            if (!is_object($field) || !method_exists($field, 'get_key')) {
                                continue;
                            }

                            try {
                                $field_key = $field->get_key();
                                $field_type = method_exists($field, 'get_type') ? $field->get_type() : 'unknown';
                                $field_label = method_exists($field, 'get_label') ? $field->get_label() : $field_key;

                        // SKIP taxonomy fields - they will be handled in getTaxonomies()
                        if ($field_type === 'taxonomy') {
                            fleekdash_log_debug("FleekDash: Skipping Voxel taxonomy field: {$field_key}");
                            continue;
                        }

                        // Get Voxel field configuration
                        $voxel_config = method_exists($field, 'get_props') ? $field->get_props() : [];

                        // Create base field configuration
                        $field_config = [
                            'name' => $field_key,
                            'label' => $field_label,
                            'type' => $this->mapVoxelTypeToComponent($field_type),
                            'component' => $this->getComponentFromVoxelType($field_type),
                            'required' => $field->is_required(),
                            'validation' => [],
                            'description' => $field->get_description() ?? '',
                            'default' => null,
                            'meta_key' => $field_key,
                            'source' => 'Voxel',
                            'source_priority' => 8,
                            'voxel_type' => $field_type,
                            'voxel_config' => $voxel_config
                        ];

                        // Special handling for repeater/group fields
                        if (in_array($field_type, ['repeater', 'group', 'fieldset', 'repeating-group'])) {
                            $field_config['component'] = 'repeater';
                            $field_config['type'] = 'repeater';
                            $field_config['sub_fields'] = [];

                            // Get sub-fields if available
                            if (method_exists($field, 'get_fields')) {
                                $sub_fields = $field->get_fields();
                                foreach ($sub_fields as $sub_field) {
                                    $sub_field_key = $sub_field->get_key();
                                    $sub_field_type = method_exists($sub_field, 'get_type') ? $sub_field->get_type() : 'text';
                                    $sub_field_label = method_exists($sub_field, 'get_label') ? $sub_field->get_label() : $this->formatFieldLabel($sub_field_key);

                                    $field_config['sub_fields'][] = [
                                        'name' => $sub_field_key,
                                        'label' => $sub_field_label,
                                        'type' => $this->mapVoxelTypeToComponent($sub_field_type),
                                        'component' => $this->getComponentFromVoxelType($sub_field_type),
                                        'voxel_type' => $sub_field_type,
                                        'meta_key' => $sub_field_key,
                                        'required' => false,
                                        'validation' => []
                                    ];
                                }
                            }

                            fleekdash_log_debug("FleekDash: Detected Voxel {$field_type} field '{$field_key}' with " . count($field_config['sub_fields']) . " sub-fields");
                        } else {
                            // Extract options for select/product fields
                            $options = $this->getVoxelFieldOptions($field, $field_type, $voxel_config);
                            $field_config['options'] = $options;
                        }

                                $fields[$field_key] = $field_config;

                                $options_count = isset($field_config['options']) ? count($field_config['options']) : 0;
                                $sub_fields_count = isset($field_config['sub_fields']) ? count($field_config['sub_fields']) : 0;
                                fleekdash_log_debug("FleekDash: Added Voxel field: {$field_key} (type: {$field_type}, options: {$options_count}, sub_fields: {$sub_fields_count})");
                            } catch (\Exception $field_error) {
                                // DEFENSIVE: Skip individual field if it causes error
                                fleekdash_log_debug("FleekDash: Error processing Voxel field: " . $field_error->getMessage());
                                continue;
                            }
                        }
                    } else {
                        fleekdash_log_debug("FleekDash: No Voxel post type found for {$post_type}");
                    }
                } catch (\Exception $voxel_error) {
                    // DEFENSIVE: Catch Voxel-specific errors (like file field processing)
                    fleekdash_log_debug("FleekDash: Voxel access error (likely during initialization): " . $voxel_error->getMessage());
                    return $fields; // Return empty fields instead of crashing
                }
            } else {
                fleekdash_log_debug("FleekDash: Voxel\Post_Type class not found");
            }
        } catch (\Exception $e) {
            fleekdash_log_error("FleekDash: Voxel fields error: " . $e->getMessage());
        }

        return $fields;
    }

    /**
     * Map Voxel field type to component type
     */
    private function mapVoxelTypeToComponent($voxel_type)
    {
        $type_map = [
            'text' => 'text',
            'textarea' => 'textarea',
            'number' => 'number',
            'email' => 'email',
            'url' => 'url',
            'wysiwyg' => 'richtext',
            'date' => 'date',
            'color' => 'color',
            'range' => 'range',
            'image' => 'media',
            'file' => 'file',
            'gallery' => 'media',
            'select' => 'select',
            'checkbox' => 'checkbox',
            'radio' => 'radio',
            'switch' => 'boolean',
            'title' => 'text',
            'description' => 'textarea',
            'location' => 'text',
            'recurring-date' => 'date',
            'product' => 'select',
            'relation' => 'select',
            'taxonomy' => 'select',
            'repeater' => 'repeater',
            'group' => 'repeater',
            'fieldset' => 'repeater',
            'repeating-group' => 'repeater',
            'ui-step' => 'text',
            'ui-image' => 'media',
            'ui-heading' => 'text',
        ];

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

    /**
     * Get component from Voxel type
     */
    private function getComponentFromVoxelType($voxel_type)
    {
        $component_map = [
            'text' => 'input',
            'textarea' => 'textarea',
            'number' => 'input',
            'email' => 'input',
            'url' => 'input',
            'wysiwyg' => 'textarea',
            'date' => 'input',
            'color' => 'input',
            'range' => 'input',
            'image' => 'file',
            'file' => 'file',
            'gallery' => 'file',
            'select' => 'select',
            'checkbox' => 'checkbox',
            'radio' => 'radio',
            'switch' => 'checkbox',
            'title' => 'input',
            'description' => 'textarea',
            'location' => 'input',
            'recurring-date' => 'input',
            'product' => 'select',
            'relation' => 'select',
            'taxonomy' => 'select',
            'repeater' => 'repeater',
            'group' => 'repeater',
            'fieldset' => 'repeater',
            'repeating-group' => 'repeater',
            'ui-step' => 'input',
            'ui-image' => 'file',
            'ui-heading' => 'input',
        ];

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

    /**
     * Extract options from Voxel field configuration
     */
    private function getVoxelFieldOptions($field, $field_type, $voxel_config)
    {
        $options = [];

        try {
            switch ($field_type) {
                case 'product':
                    if (!empty($voxel_config['product-types'])) {
                        foreach ($voxel_config['product-types'] as $product_type) {
                            $options[] = [
                                'value' => $product_type,
                                'label' => ucfirst(str_replace(['_', '-'], ' ', $product_type))
                            ];
                        }
                    }
                    break;

                case 'select':
                    if (!empty($voxel_config['choices'])) {
                        foreach ($voxel_config['choices'] as $choice_key => $choice_label) {
                            $options[] = [
                                'value' => $choice_key,
                                'label' => $choice_label
                            ];
                        }
                    }
                    break;

                case 'relation':
                    if (!empty($voxel_config['post-type'])) {
                        $related_post_type = $voxel_config['post-type'];
                        $posts = \get_posts([
                            'post_type' => $related_post_type,
                            'posts_per_page' => 50,
                            'post_status' => 'publish',
                            'fields' => 'ids',
                            'no_found_rows' => true,
                            'update_post_meta_cache' => false,
                            'update_post_term_cache' => false,
                        ]);

                        foreach ($posts as $post_id) {
                            $options[] = [
                                'value' => $post_id,
                                'label' => get_the_title($post_id)
                            ];
                        }
                    }
                    break;

                case 'taxonomy':
                    if (!empty($voxel_config['taxonomy'])) {
                        $taxonomy_slug = $voxel_config['taxonomy'];
                        $terms = \get_terms([
                            'taxonomy' => $taxonomy_slug,
                            'hide_empty' => false,
                            'number' => 100
                        ]);

                        if (!is_wp_error($terms)) {
                            foreach ($terms as $term) {
                                $options[] = [
                                    'value' => $term->term_id,
                                    'label' => $term->name
                                ];
                            }
                        }
                    }
                    break;

                case 'checkbox':
                case 'radio':
                    if (!empty($voxel_config['choices'])) {
                        foreach ($voxel_config['choices'] as $choice_key => $choice_label) {
                            $options[] = [
                                'value' => $choice_key,
                                'label' => $choice_label
                            ];
                        }
                    }
                    break;

                default:
                    if (method_exists($field, 'get_choices')) {
                        $choices = $field->get_choices();
                        if (is_array($choices)) {
                            foreach ($choices as $choice_key => $choice_label) {
                                $options[] = [
                                    'value' => $choice_key,
                                    'label' => $choice_label
                                ];
                            }
                        }
                    }
                    break;
            }
        } catch (\Exception $e) {
            fleekdash_log_error("FleekDash: Error extracting Voxel options for {$field_type}: " . $e->getMessage());
        }

        return $options;
    }

    /**
     * Get Voxel field information for a specific field key
     */
    public function getVoxelFieldInfo($field_key, $post_type_slug)
    {
        try {
            // Direct detection for known date repeaters
            if (in_array($field_key, ['event_date', 'recurring-date'])) {
                fleekdash_log_debug("FleekDash: Direct Voxel date repeater detection: {$field_key}");
                return [
                    'name' => $field_key,
                    'type' => 'repeater',
                    'voxel_type' => 'recurring-date',
                    'component' => 'repeater',
                    'label' => ucfirst(str_replace(['_', '-'], ' ', $field_key))
                ];
            }

            // Try direct Voxel class detection
            if (class_exists('\Voxel\Post_Type')) {
                try {
                    $voxel_post_type = \Voxel\Post_Type::get($post_type_slug);
                    if ($voxel_post_type) {
                        $voxel_field = $voxel_post_type->get_field($field_key);
                        if ($voxel_field) {
                            $voxel_type = method_exists($voxel_field, 'get_type') ? $voxel_field->get_type() : 'unknown';
                            fleekdash_log_debug("FleekDash: Found Voxel field {$field_key} with type: {$voxel_type}");

                            return [
                                'name' => $field_key,
                                'type' => $voxel_type === 'recurring-date' ? 'repeater' : $voxel_type,
                                'voxel_type' => $voxel_type,
                                'component' => $voxel_type === 'recurring-date' ? 'repeater' : $voxel_type,
                                'label' => method_exists($voxel_field, 'get_label') ? $voxel_field->get_label() : ucfirst(str_replace(['_', '-'], ' ', $field_key))
                            ];
                        }
                    }
                } catch (\Exception $voxel_error) {
                    fleekdash_log_debug("FleekDash: Voxel detection error for {$field_key}: " . $voxel_error->getMessage());
                }
            }

            return null;
        } catch (\Exception $e) {
            fleekdash_log_error("FleekDash: Error getting Voxel field info: " . $e->getMessage());
            return null;
        }
    }

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

    /**
     * Investigate Voxel custom fields (debug method)
     */
    public function investigateVoxelFields()
    {
        global $wpdb;
        $investigation = [];

        try {
            // Check for posts
            $place_posts = $wpdb->get_results($wpdb->prepare("
                SELECT ID, post_title, post_status, post_date
                FROM {$wpdb->posts}
                WHERE post_type = %s
                LIMIT 5
            ", 'place'));

            $investigation['place_posts_found'] = count($place_posts);
            $investigation['place_posts'] = $place_posts;

            if (!empty($place_posts)) {
                $post_ids = wp_list_pluck($place_posts, 'ID');
                $meta_fields = $wpdb->get_results($wpdb->prepare("
                    SELECT DISTINCT meta_key, COUNT(*) as count
                    FROM {$wpdb->postmeta}
                    WHERE post_id IN (" . implode(',', array_map('intval', $post_ids)) . ")
                    GROUP BY meta_key
                    ORDER BY count DESC, meta_key ASC
                "));

                $investigation['meta_fields_found'] = count($meta_fields);
                $investigation['meta_fields'] = $meta_fields;
            }

            // Check Voxel classes
            $investigation['voxel_classes'] = [];
            $voxel_classes_to_check = [
                '\Voxel\Post_Types',
                'Voxel\Post_Types',
                'Voxel_Post_Types',
                '\Voxel\Post_Type',
                'Voxel\Post_Type',
                'Voxel_Post_Type'
            ];

            foreach ($voxel_classes_to_check as $class_name) {
                if (class_exists($class_name)) {
                    $investigation['voxel_classes'][] = $class_name;
                }
            }

            // Check globals
            global $voxel, $GLOBALS;
            if (isset($GLOBALS['voxel'])) {
                $investigation['voxel_global'] = 'found';
            }

            if (isset($voxel)) {
                $investigation['voxel_variable'] = 'found';
            }

        } catch (\Exception $e) {
            $investigation['error'] = $e->getMessage();
        }

        return $investigation;
    }
}
