<?php

namespace Blazemedia\Affiliation\Providers\Trait;

use Blazemedia\Affiliation\Utils\Logger;
use Blazemedia\Affiliation\Rendering\RenderResponse;

trait HasPostMetaManager
{
    /**
     * Save the formats in the post meta
     * 
     * @param \WP_Post $post
     * @param RenderResponse $renderResponse
     */
    protected function setMetaRenderResponse(\WP_Post $post, RenderResponse $renderResponse, bool $isChild = false): void
    {
        $signature = isset($renderResponse->getRequest()['parameters']) 
            ? $renderResponse->getRequest()['parameters']->getSignature() 
            : '';

        // Preserve the parameter name for backward compatibility, but map to new suffix
        $suffix = $isChild ? '_hook' : '';

        // When saving hook meta, merge with existing instead of replacing
        $newResponse = $renderResponse->getResponse();
        if ($suffix === '_hook') {
            $existingRaw = get_post_meta($post->ID, '_blz_affiliation_formats' . $suffix, true);
            $existing     = is_string($existingRaw) ? @unserialize($existingRaw) : $existingRaw;
            if (!is_array($existing)) {
                $existing = [];
            }

            $existingRepl = isset($existing['replacements']) && is_array($existing['replacements']) ? $existing['replacements'] : [];
            $newRepl      = isset($newResponse['replacements']) && is_array($newResponse['replacements']) ? $newResponse['replacements'] : [];

            // Merge replacements avoiding duplicates by 'html' key
            $mergedRepl = $existingRepl;
            $seenHtml   = [];
            foreach ($existingRepl as $item) {
                if (isset($item['html'])) {
                    $seenHtml[$item['html']] = true;
                }
            }
            foreach ($newRepl as $item) {
                $htmlKey = isset($item['html']) ? $item['html'] : null;
                if ($htmlKey === null || !isset($seenHtml[$htmlKey])) {
                    $mergedRepl[] = $item;
                    if ($htmlKey !== null) {
                        $seenHtml[$htmlKey] = true;
                    }
                }
            }

            $merged = $existing;
            $merged['replacements'] = $mergedRepl;

            // Prefer existing bm_post if present; otherwise take new
            if (!isset($merged['bm_post']) || empty($merged['bm_post'])) {
                if (isset($newResponse['bm_post'])) {
                    $merged['bm_post'] = $newResponse['bm_post'];
                }
            }

            update_post_meta($post->ID, '_blz_affiliation_formats' . $suffix, serialize($merged));
        } else {
            update_post_meta($post->ID, '_blz_affiliation_formats' . $suffix, serialize($newResponse));
        }

        update_post_meta($post->ID, '_blz_affiliation_formats_signature' . $suffix, $signature);
    }

    /**
     * Delete the formats from the post meta
     * @param \WP_Post $post
     */
    protected function deleteMetaRenderResponse(\WP_Post $post): void
    {
        delete_post_meta($post->ID, '_blz_affiliation_formats');
        delete_post_meta($post->ID, '_blz_affiliation_formats_signature');
        delete_post_meta($post->ID, '_blz_affiliation_formats_hook');
        delete_post_meta($post->ID, '_blz_affiliation_formats_signature_hook');
    }

    protected function getMetaRenderResponse(\WP_Post $post, bool $isChild = false): RenderResponse
    {
        $suffix = $isChild ? '_hook' : '';
        $renderResponseBody = unserialize(get_post_meta($post->ID, '_blz_affiliation_formats' . $suffix, true));

        if (empty($renderResponseBody)) return new RenderResponse();

        return new RenderResponse(json_encode($renderResponseBody));
    }

    protected function getMetaSignature(\WP_Post $post, bool $isChild = false): string
    {
        $suffix = $isChild ? '_hook' : '';
        return get_post_meta($post->ID, '_blz_affiliation_formats_signature' . $suffix, true) ?? '';
    }
}
