<?php
/**
 * Field Serializer Class
 *
 * Handles serialization of ACF field definitions for copy/paste transfer
 *
 * @package CSCF_ACF
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * ACF_Copy_Addon_Field_Serializer Class
 */
class CSCF_ACF_Field_Serializer
{

    /**
     * Serialize a field for transfer
     *
     * @param array $field ACF field array
     * @return string Base64 encoded JSON string
     */
    public function serialize_field($field)
    {
        // Get clean field data
        $field_data = $this->prepare_field_for_export($field);

        // Encode for transfer
        return $this->encode_for_transfer($field_data);
    }

    /**
     * Prepare field data for export
     *
     * @param array $field ACF field array
     * @return array Cleaned field data
     */
    private function prepare_field_for_export($field)
    {
        // Remove WordPress-specific metadata
        $keys_to_remove = array(
            'ID',
            'id',
            'parent',
            'menu_order',
            'post_type',
            'post_status',
            'post_content',
            'post_title',
            'post_excerpt',
            'post_name',
            'post_parent',
            'guid',
            '_name',
            '_prepare',
            '_valid',
        );

        foreach ($keys_to_remove as $key) {
            unset($field[$key]);
        }

        // Clean field references (media IDs, post IDs, etc.)
        $field = $this->clean_field_references($field);

        // Handle sub-fields for nested field types
        if ($this->has_sub_fields($field)) {
            $field = $this->serialize_sub_fields($field);
        }

        return $field;
    }

    /**
     * Check if field type has sub-fields
     *
     * @param array $field ACF field array
     * @return bool
     */
    private function has_sub_fields($field)
    {
        $nested_types = array('repeater', 'group', 'flexible_content', 'clone');
        return in_array($field['type'], $nested_types, true);
    }

    /**
     * Serialize sub-fields recursively
     *
     * @param array $field Parent field array
     * @return array Field with serialized sub-fields
     */
    private function serialize_sub_fields($field)
    {
        // Handle different nested field types
        switch ($field['type']) {
            case 'repeater':
            case 'group':
                if (!empty($field['sub_fields']) && is_array($field['sub_fields'])) {
                    foreach ($field['sub_fields'] as $index => $sub_field) {
                        $field['sub_fields'][$index] = $this->prepare_field_for_export($sub_field);
                    }
                }
                break;

            case 'flexible_content':
                if (!empty($field['layouts']) && is_array($field['layouts'])) {
                    foreach ($field['layouts'] as $layout_index => $layout) {
                        if (!empty($layout['sub_fields']) && is_array($layout['sub_fields'])) {
                            foreach ($layout['sub_fields'] as $field_index => $sub_field) {
                                $field['layouts'][$layout_index]['sub_fields'][$field_index] =
                                    $this->prepare_field_for_export($sub_field);
                            }
                        }
                    }
                }
                break;
        }

        return $field;
    }

    /**
     * Clean field references (media IDs, post IDs, etc.)
     *
     * @param array $field ACF field array
     * @return array Cleaned field
     */
    private function clean_field_references($field)
    {
        // Media field types - clear default values
        $media_types = array('image', 'file', 'gallery');

        if (in_array($field['type'], $media_types, true)) {
            $field['default_value'] = '';
        }

        // Post object / Page link - clear default values
        $post_types = array('post_object', 'page_link', 'relationship');

        if (in_array($field['type'], $post_types, true)) {
            $field['default_value'] = '';
        }

        // Taxonomy field - clear default values
        if ($field['type'] === 'taxonomy') {
            $field['default_value'] = '';
        }

        // User field - clear default values
        if ($field['type'] === 'user') {
            $field['default_value'] = '';
        }

        return $field;
    }

    /**
     * Encode field data for transfer
     *
     * @param array $field_data Field data array
     * @return string Base64 encoded JSON string
     */
    private function encode_for_transfer($field_data)
    {
        // Convert to JSON
        $json = wp_json_encode($field_data);

        if ($json === false) {
            return '';
        }

        // Base64 encode for safe transfer via clipboard
        return base64_encode($json);
    }

    /**
     * Get field data by key
     *
     * @param string $field_key ACF field key
     * @return array|false Field array or false if not found
     */
    public function get_field_by_key($field_key)
    {
        // Get field object from ACF
        $field = acf_get_field($field_key);

        if (!$field) {
            return false;
        }

        return $field;
    }
}
