<?php

namespace Miruni\Kadence;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class Miruni_Kadence_Manager
{
    /**
     * Checks if the page uses the Kadence theme or Kadence blocks
     * @param int $post_id The post ID to check
     * @return bool True if the page uses Kadence, false otherwise
     */
    public static function is_kadence_page(int $post_id): bool
    {
        try {
            // Check if Kadence theme is active
            $current_theme = get_template();
            if (strpos($current_theme, 'kadence') !== false) {
                return true;
            }

            // Check if the post content contains Kadence blocks
            $post = get_post($post_id);
            if (!$post instanceof \WP_Post) {
                return false;
            }

            $post_content = $post->post_content;

            // Check for Kadence block patterns in the content
            if (strpos($post_content, 'wp:kadence/') !== false) {
                return true;
            }

            // Check for Kadence-specific meta fields
            $kadence_meta_keys = [
                '_kad_post_transparent',
                '_kad_post_title',
                '_kad_post_layout',
                '_kad_post_sidebar_id',
                '_kad_post_content_style',
                '_kad_post_vertical_padding',
                '_kad_post_feature',
                '_kad_post_feature_position',
                '_kad_post_header',
                '_kad_post_footer'
            ];

            foreach ($kadence_meta_keys as $meta_key) {
                if (get_post_meta($post_id, $meta_key, true)) {
                    return true;
                }
            }

            return false;

        } catch (\Exception $e) {
            do_action('miruni_plugin_error', $e, [
                'context' => 'Miruni_Kadence_Manager.is_kadence_page',
                'operation' => "Checking if post_id: $post_id uses Kadence",
                'user_id' => get_current_user_id()
            ]);
            return false;
        }
    }
}
