<?php

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

    public function __construct(){
        add_filter( 'wp_kses_allowed_html', [ $this, 'allow_svg_viewbox' ], 10, 2 );
    }

    public static function allow_svg_viewbox( $allowed_tags, $context ) {
        if ( ! isset( $allowed_tags['svg'] ) ) {
            $allowed_tags['svg'] = [];
        }
        $allowed_tags['svg']['viewBox'] = true;
        return $allowed_tags;
    }

    public static function get_woocommerce_products() {
        if (!class_exists('WooCommerce')) return [];
        $args = [
            'post_type'      => 'product',
            'posts_per_page' => 100,
            'post_status'    => 'publish',
        ];
        $products = get_posts($args);
        $choices = [];
        foreach ($products as $product) {
            $choices[$product->ID] = $product->post_title;
        }
        return $choices;
    }

    public static function get_instagram_media($user_id, $access_token, $limit = 8) {
        if (empty($user_id) || empty($access_token)) return [];

        $transient_key = 'pawfect_instagram_media_cache_' . md5($user_id);
        if (false !== ($cached = get_transient($transient_key))) {
            return $cached;
        }

        $request_url = "https://graph.instagram.com/{$user_id}/media?fields=id,media_type,media_url,permalink&access_token={$access_token}&limit={$limit}";
        $response = wp_remote_get($request_url);

        if (is_wp_error($response)) return [];

        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body);

        if (isset($data->data) && is_array($data->data)) {
            $media_items = array_filter($data->data, function ($item) {
                return in_array($item->media_type, ['IMAGE', 'CAROUSEL_ALBUM']);
            });
            set_transient($transient_key, $media_items, 3 * HOUR_IN_SECONDS);
            return $media_items;
        }

        return [];
    }

    /**
     * Get the mapping of section IDs to their template parts and display names.
     *
     * @return array Array of section mappings
     */
    public static function get_frontpage_sections_map() {
        return [
            'hero_slider' => [
                'name' => esc_html__( 'Hero Slider', 'pawfect' ),
                'template' => 'template-parts/front-page/hero-slider',
            ],
            'press_mentions' => [
                'name' => esc_html__( 'Press Mentions', 'pawfect' ),
                'template' => 'template-parts/front-page/press-mentions',
            ],
            'feature_highlight' => [
                'name' => esc_html__( 'Feature Highlight', 'pawfect' ),
                'template' => 'template-parts/front-page/feature-highlight',
            ],
            'why_choose' => [
                'name' => esc_html__( 'Why Choose Us', 'pawfect' ),
                'template' => 'template-parts/front-page/why-choose',
            ],
            'portfolio' => [
                'name' => esc_html__( 'Category Highlights', 'pawfect' ),
                'template' => 'template-parts/front-page/section-category-highlights',
            ],
            'woocommerce' => [
                'name' => esc_html__( 'WooCommerce Featured Products', 'pawfect' ),
                'template' => 'template-parts/front-page/section-woocommerce-featured',
            ],
            'testimonial' => [
                'name' => esc_html__( 'Testimonials', 'pawfect' ),
                'template' => 'template-parts/front-page/index-testimonial',
            ],
            'featured_collection' => [
                'name' => esc_html__( 'Featured Collection', 'pawfect' ),
                'template' => 'template-parts/front-page/featured-collection',
            ],
            'mission' => [
                'name' => esc_html__( 'Mission Statement', 'pawfect' ),
                'template' => 'template-parts/front-page/index-mission',
            ],
            'pet_shop' => [
                'name' => esc_html__( 'Shop by Pet', 'pawfect' ),
                'template' => 'template-parts/front-page/index-shop-by-pet',
            ],
            'promo_timer' => [
                'name' => esc_html__( 'Promo Timer', 'pawfect' ),
                'template' => 'template-parts/front-page/index-promo-timer',
            ],
            'crafted' => [
                'name' => esc_html__( 'Crafted with Care', 'pawfect' ),
                'template' => 'template-parts/front-page/index-crafted',
            ],
            'blog' => [
                'name' => esc_html__( 'Blog Section', 'pawfect' ),
                'template' => 'template-parts/front-page/index-blog',
            ],
            'promo_banner' => [
                'name' => esc_html__( 'Promo Banner', 'pawfect' ),
                'template' => 'template-parts/front-page/index-promo-banner',
            ],
            'countdown_banner' => [
                'name' => esc_html__( 'Countdown Sale Banner', 'pawfect' ),
                'template' => 'template-parts/front-page/countdown-banner',
            ],
            'cta' => [
                'name' => esc_html__( 'Call to Action', 'pawfect' ),
                'template' => 'template-parts/front-page/cta',
            ],
            'instagram' => [
                'name' => esc_html__( 'Instagram Feed', 'pawfect' ),
                'template' => 'template-parts/front-page/index-instagram',
            ],
        ];
    }

    /**
     * Get enabled frontpage sections in order.
     *
     * @return array Array of enabled section IDs in order
     */
    public static function get_enabled_frontpage_sections() {
        // Get from the new layout manager control
        $layout_manager = get_theme_mod( 'layout_manager', array() );

        if ( ! empty( $layout_manager ) && is_array( $layout_manager ) ) {
            // Convert new format to enabled sections list
            $enabled_sections = array();

            // Sort by order
            uasort( $layout_manager, function( $a, $b ) {
                return ( $a['order'] ?? 0 ) - ( $b['order'] ?? 0 );
            });

            // Get only visible sections
            foreach ( $layout_manager as $section_id => $config ) {
                if ( isset( $config['visible'] ) && $config['visible'] ) {
                    $enabled_sections[] = $section_id;
                }
            }

            return $enabled_sections;
        }

        // Fallback to old format for backward compatibility
        $front_page_data = get_theme_mod( 'front_page_data', 'hero_slider,press_mentions,feature_highlight,why_choose,portfolio,featured_collection,testimonial,crafted,promo_banner,blog,cta' );
        return array_filter( explode( ',', $front_page_data ) );
    }

    /**
     * Check if a frontpage section is enabled.
     *
     * @param string $section_id The section ID to check
     * @return bool True if enabled, false otherwise
     */
    public static function is_frontpage_section_enabled( $section_id ) {
        $enabled_sections = self::get_enabled_frontpage_sections();
        return in_array( $section_id, $enabled_sections, true );
    }
}