<?php

namespace Miruni\ThemePreview;

use Exception;
use Miruni\Breakdance\Miruni_Breakdance_Service;
use Miruni\Miruni_Preview_Meta_Keys; // Import the class

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Breakdance-specific theme preview manager
 * This class will only be instantiated when Breakdance is active
 */
class Miruni_Breakdance_Theme_Preview_Manager extends Miruni_Theme_Preview_Manager
{
    /**
     * Constructor for Breakdance theme preview manager
     */
    public function __construct()
    {
        parent::__construct();

        // Add Breakdance-specific hooks only if Breakdance is active
        // Note: Replace 'function_exists('breakdance_init')' with the correct check for Breakdance activation
        if (function_exists('breakdance_init')) {
            // Add Breakdance-specific hooks
            add_filter('breakdance_builder_post_content_data', [$this, 'filter_breakdance_data'], 10, 2);

        }
    }

    /**
     * Filter Breakdance data in preview mode
     *
     * @param array<string|int, mixed>|null $data The Breakdance data array.
     * @param int $post_id The ID of the post being rendered.
     * @return array<string|int, mixed>|null The filtered data.
     */
    public function filter_breakdance_data(?array $data, int $post_id): ?array
    {
        if (!$this->validate_is_preview()) {
            return $data;
        }

        $preview_id = $this->get_preview_id();
        if (!$preview_id) {
            return $data;
        }

        // Check for stored Breakdance data for this post in the preview meta
        // Use the constant for the meta key
        $preview_data = get_post_meta($preview_id, Miruni_Preview_Meta_Keys::BREAKDANCE_DATA, true);

        if (is_array($preview_data) && isset($preview_data[$post_id])) {
            // Ensure the stored data is an array before returning
            return is_array($preview_data[$post_id]) ? $preview_data[$post_id] : $data;
        }

        return $data;
    }


    /**
     * Apply stored Breakdance data to actual posts upon publishing the preview
     *
     * @param int $draft_id The ID of the draft/preview post.
     * @return array<int> Array of updated post IDs.
     */
    public function publish_breakdance_changes(int $draft_id): array
    {
        $applied_changes = [];
        // Use the constant for the meta key
        $breakdance_data = get_post_meta($draft_id, Miruni_Preview_Meta_Keys::BREAKDANCE_DATA, true);

        if (is_array($breakdance_data) && !empty($breakdance_data)) {
            foreach ($breakdance_data as $post_id => $data) {
                // Ensure data is an array
                if (!is_array($data))
                    continue;

                // Update Breakdance data
                // Note: Replace '_breakdance_post_settings' with the actual meta key Breakdance uses to store post data
                $meta_key = apply_filters('miruni_breakdance_data_meta_key', '_breakdance_post_settings', $post_id);
                update_post_meta($post_id, $meta_key, $data);

                $applied_changes[] = (int) $post_id;
            }

            // Clean up the meta data
            // Use the constant for the meta key
            delete_post_meta($draft_id, Miruni_Preview_Meta_Keys::BREAKDANCE_DATA);
        }

        return $applied_changes;
    }

    /**
     * Filter post meta for Breakdance data key during preview.
     *
     * @param mixed  $value     The value to return, either null or the override value.
     * @param int    $object_id ID of the object metadata is for.
     * @param string $meta_key  Meta key.
     * @param bool   $single    Whether to return only the first value of the specified $meta_key.
     * @return mixed Filtered meta value or null.
     */
    public function filter_breakdance_post_meta($value, int $object_id, string $meta_key, bool $single)
    {
        if ($meta_key !== "_breakdance_data") {
            return null; // Let WordPress handle this key
        }


        $preview_id = $this->get_preview_id();
        if (!$preview_id) {
            return null; // No preview ID available
        }

        $stored_value = $this->get_stored_preview_value(
            $preview_id,
            $object_id,
            Miruni_Preview_Meta_Keys::BREAKDANCE_DATA,

        );
        if ($stored_value) {
            // If we have a stored value, return it
            $breakdance_data = Miruni_Breakdance_Service::tree_to_breakdance_data($stored_value);

            if ($breakdance_data) {
                return json_encode($breakdance_data);
            }
            error_log("No breakdance data found for post ID: " . $object_id);

        }

        return null; // No preview data found, let WordPress proceed
    }


    /**
     * Override the maybe_use_preview_theme method if needed for Breakdance specifics
     */
    public function maybe_use_preview_theme(): void
    {
        // Basic check, might need refinement based on Breakdance preview mechanisms

        if (!$this->validate_is_preview()) {
            return;
        }

        parent::maybe_use_preview_theme();

        // Add the post meta filter specifically for Breakdance data
        add_filter('get_post_metadata', [$this, 'filter_breakdance_post_meta'], 10, 4);

        $post = get_post();
        // @phpstan-ignore function.alreadyNarrowedType
        if (!$post || !is_object($post) || !is_a($post, 'WP_Post')) {
            return;
        }
        $post_id = $post->ID;
        if (!$post_id) {
            return;
        }

        Miruni_Breakdance_Service::render_breakdance_page($post->ID);

    }
}
