<?php

namespace FleekDash\Controllers\Post;

/**
 * Post meta and taxonomy processing
 *
 * Handles processing of meta field values and taxonomy term assignments.
 * Supports WordPress native meta, Voxel fields, and complex field types.
 *
 * @package FleekDash\Controllers\Post
 * @since 2.2.0
 */
class PostMetaProcessor
{
    /**
     * Process meta field value before saving
     *
     * Handles special field types like Voxel fields, galleries, file uploads,
     * and complex arrays with appropriate formatting.
     *
     * @param string $meta_key The meta field key
     * @param mixed  $meta_value The meta field value
     * @return mixed Processed meta value
     */
    public static function processMetaFieldValue($meta_key, $meta_value)
    {
        // Special handling for Voxel fields
        if (strpos($meta_key, 'voxel:') === 0) {
            // If it's a JSON string, try to decode it
            if (is_string($meta_value) && (strpos($meta_value, '{') === 0 || strpos($meta_value, '[') === 0)) {
                $decoded = json_decode($meta_value, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    return $decoded;
                }
            }
            // If it's already an array, keep it as is
            else if (is_array($meta_value)) {
                return $meta_value;
            }
            // For other data types, convert to JSON string (Voxel format)
            else {
                return json_encode($meta_value);
            }
        }

        // Handle gallery fields (comma-separated IDs)
        if ($meta_key === 'gallery') {
            if (is_array($meta_value)) {
                // Extract attachment IDs from array of objects or direct IDs
                $ids = [];
                foreach ($meta_value as $item) {
                    if (is_array($item) && isset($item['attachment_id'])) {
                        $ids[] = $item['attachment_id'];
                    } elseif (is_numeric($item)) {
                        $ids[] = $item;
                    }
                }
                return implode(',', $ids);
            } elseif (is_string($meta_value)) {
                return $meta_value; // Already comma-separated
            }
        }

        // Handle file upload objects
        if (is_array($meta_value) && isset($meta_value['attachment_id'])) {
            return $meta_value['attachment_id'];
        }

        // Handle arrays that should be serialized (WordPress format)
        if (is_array($meta_value)) {
            // Check if it's a simple array of values (like taxonomy terms)
            $is_simple_array = true;
            foreach ($meta_value as $item) {
                if (is_array($item) || is_object($item)) {
                    $is_simple_array = false;
                    break;
                }
            }

            if ($is_simple_array && count($meta_value) <= 1) {
                // Single value - store as string or number
                return count($meta_value) === 1 ? $meta_value[0] : '';
            } elseif ($is_simple_array) {
                // Multiple simple values - store as comma-separated string
                return implode(',', $meta_value);
            } else {
                // Complex array - serialize it (WordPress format)
                return maybe_serialize($meta_value);
            }
        }

        // Return as-is for simple values
        return $meta_value;
    }

    /**
     * Process taxonomy terms assignment
     *
     * Handles assigning taxonomy terms to a post, converting term objects
     * to IDs and properly formatting for wp_set_object_terms().
     *
     * @param int    $post_id  The post ID
     * @param string $taxonomy The taxonomy name
     * @param mixed  $terms    The terms to assign (array or single value)
     * @return void
     */
    public static function processTaxonomyTerms($post_id, $taxonomy, $terms)
    {
        // Ensure terms is an array
        if (!is_array($terms)) {
            $terms = [$terms];
        }

        // Convert term objects to IDs if needed
        $term_ids = [];
        foreach ($terms as $term) {
            if (is_array($term) && isset($term['id'])) {
                $term_ids[] = intval($term['id']);
            } elseif (is_numeric($term)) {
                $term_ids[] = intval($term);
            }
        }

        // Always set the terms (empty array will clear all terms for this taxonomy)
        wp_set_object_terms($post_id, $term_ids, $taxonomy);
    }
}
