<?php

namespace Blazemedia\Affiliation\Providers\Trait;

use Blazemedia\Affiliation\Utils\Logger;

trait HandleZoneFormat {
    /**
     * Handle the zone rendering in the post content
     * @param \WP_Post $post
     * @return \WP_Post
     */
    protected function handleZoneRendering(\WP_Post $post): \WP_Post {
        // Check if the post content contains the zone rendering shortcode
        if (strpos($post->post_content, 'affiliate_zone') === false) {
            return $post;
        }

        // If not, we can proceed with the normal request
        //preg match to find the shortcode
        preg_match_all('/\[affiliate_zone\s+zone_id="(\d+)"\]/', $post->post_content, $matches);

        $zoneIds = isset($matches[1]) ? array_unique($matches[1]) : [];
        foreach ($zoneIds as $zoneId) {
            // Create a new shortcode for the zone rendering
            $shortcode = sprintf('[affiliate_zone zone_id="%s"]', $zoneId);
            // Replace the shortcode in the post content of zone
            $zonePost = get_post($zoneId);

            if ($zonePost) {
                // Track that the current article uses this zone
                $this->trackZoneUsage($zonePost, (int) $post->ID);
                // If the zone post exists, we can inject the shortcode in the content
                $post->post_content = str_replace($shortcode, $zonePost->post_content, $post->post_content);
            } else {
                // If the zone post does not exist, we can log an error
                Logger::write("Zone post with ID {$zoneId} does not exist.", 'ERROR');
            }
        }


        return $post;
    }

    /**
     * Persist the relationship between a zone post and an article post by
     * storing the article ID in a comma-separated meta on the zone post.
     * Duplicates are avoided to keep the list clean.
     *
     * @param \WP_Post $zonePost   The zone post object
     * @param int       $articleId  The ID of the article using the zone
     */
    protected function trackZoneUsage(\WP_Post $zonePost, int $articleId): void
    {
        $metaKey = '_blz_affiliation_zone_posts';

        $existing = get_post_meta($zonePost->ID, $metaKey, true);
        $list = is_string($existing) ? $existing : '';

        $ids = array_filter(array_map('trim', explode(',', $list)));
        $articleIdString = (string) $articleId;

        if (!in_array($articleIdString, $ids, true)) {
            $ids[] = $articleIdString;
            update_post_meta($zonePost->ID, $metaKey, implode(',', $ids));
        }
    }
}
