<?php

namespace Convertforce\Frontend;

use Convertforce\Core\Post;

class Frontend
{
    private static $rendered = '';

    public static function init()
    {
        wp_register_style(
            'convertforce-frontend-style',
            CONVERTFORCE_URL . '/build/frontend-style.css',
            [],
            CONVERTFORCE_VERSION
        );
    }

    public static function prepare_conversions()
    {
        global $post;
        $main_post = $post;
        $args = [
            'post_status' => 'publish',
            'post_type' => Post::POST_TYPE,
            'posts_per_page' => -1,
        ];

        $query = new \WP_Query($args);
        if (!$query->have_posts()) {
            return;
        }

        while ($query->have_posts()) {
            $query->the_post();
            $post_meta = get_post_meta(get_the_ID(), Post::META_KEY, true);
            $display_conditions = $post_meta['displayConditions'] ?? [];
          

            // Ensure display_conditions is an array
            if (!is_array($display_conditions)) {
                $display_conditions = [];
            }

            $advanced_conditions = $post_meta['advancedConditions'] ?? [];
            if (!is_array($advanced_conditions)) {
                $advanced_conditions = [];
            }

            if (!DisplayCondition::should_show_popup($display_conditions, $main_post)) {
                continue;
            }

            // Server-side advanced targeting conditions (URL, query, referrer,
            // cookie, user, UA-based browser/device). Implemented by the Pro
            // addon via this filter; defaults to true so popups show without Pro.
            if (!apply_filters('convertforce_advanced_conditions_passes', true, $advanced_conditions)) {
                continue;
            }

            $content = get_the_content();
            self::$rendered .= apply_filters('the_content', $content);
        }
        wp_reset_postdata();
    }


    public static function render()
    {
        // @codingStandardsIgnoreStart
        echo self::$rendered;
        // @codingStandardsIgnoreEnd
    }
}