<?php

namespace AIPT\Api\BulkGenerator\FAQ;

/**
 * Shortcode handler for FAQ display.
 *
 * Registers the [aipt_faq] shortcode so users can place FAQ content anywhere
 * in product pages, posts, or other content areas. The shortcode renders the
 * same accordion/flat output that the automatic WooCommerce hook would produce.
 *
 * Usage:
 *   [aipt_faq]                   — renders FAQs for the current product
 *   [aipt_faq product_id="123"]  — renders FAQs for a specific product
 *
 * @package AIPT\Api\BulkGenerator\FAQ
 * @since 2.6.0
 */
class FAQShortcode {

    /**
     * Register the [aipt_faq] shortcode.
     *
     * @return void
     */
    public static function register(): void {
        add_shortcode( 'aipt_faq', [ __CLASS__, 'render' ] );
    }

    /**
     * Render the [aipt_faq] shortcode output.
     *
     * Reads FAQ data from _aipt_faq_data post meta, applies display settings,
     * and returns the rendered HTML. Enqueues CSS only when the shortcode is
     * actually used on the page.
     *
     * @param array|string $atts Shortcode attributes.
     * @return string Rendered FAQ HTML or empty string.
     */
    public static function render( $atts = [] ): string {
        $atts = shortcode_atts(
            [
                'product_id' => 0,
            ],
            $atts,
            'aipt_faq'
        );

        $product_id = absint( $atts['product_id'] );
        if ( ! $product_id ) {
            $product_id = get_the_ID();
        }

        if ( ! $product_id ) {
            return '';
        }

        $faq_data = get_post_meta( $product_id, '_aipt_faq_data', true );
        if ( empty( $faq_data ) ) {
            return '';
        }

        $faqs = json_decode( $faq_data, true );
        if ( ! is_array( $faqs ) || empty( $faqs ) ) {
            return '';
        }

        $settings_obj = new FAQDisplaySettings();
        $settings     = $settings_obj->getAll();

        self::enqueue_assets( $settings );

        if ( ! empty( $settings['accordion_enabled'] ) ) {
            $render_settings = [
                'container_class_name' => FAQFrontendRenderer::build_container_classes( $settings ),
            ];
            return FAQTemplateRenderer::renderAccordion( $faqs, $render_settings );
        }

        return FAQTemplateRenderer::renderFlat( $faqs, 'html', $settings );
    }

    /**
     * Enqueue FAQ display CSS and output dynamic CSS variables.
     *
     * Called only when the shortcode actually renders content, ensuring
     * assets are not loaded on pages without FAQs.
     *
     * @param array $settings Display settings array.
     * @return void
     */
    private static function enqueue_assets( array $settings ): void {

        if ( ! wp_style_is( 'aipt-faq-display', 'enqueued' ) ) {
            wp_enqueue_style(
                'aipt-faq-display',
                AIPT_PLUGIN_URL . 'dist/css/faq-display.css',
                [],
                AIPT_VERSION
            );
        }

        static $inline_css_added = false;
        if ( $inline_css_added ) {
            return;
        }
        $inline_css_added = true;

        $css_var_map = [
            'question_color'   => '--aipt-faq-question-color',
            'answer_color'     => '--aipt-faq-answer-color',
            'background_color' => '--aipt-faq-background-color',
            'border_color'     => '--aipt-faq-border-color',
            'font_family'      => '--aipt-faq-font-family',
            'font_size'        => '--aipt-faq-font-size',
            'font_weight'      => '--aipt-faq-font-weight',
            'padding_top'              => '--aipt-faq-padding-top',
            'padding_right'            => '--aipt-faq-padding-right',
            'padding_bottom'           => '--aipt-faq-padding-bottom',
            'padding_left'             => '--aipt-faq-padding-left',
            'margin_top'               => '--aipt-faq-margin-top',
            'margin_right'             => '--aipt-faq-margin-right',
            'margin_bottom'            => '--aipt-faq-margin-bottom',
            'margin_left'              => '--aipt-faq-margin-left',
            'gap'                      => '--aipt-faq-gap',
            'border_radius_top_left'   => '--aipt-faq-border-radius-tl',
            'border_radius_top_right'  => '--aipt-faq-border-radius-tr',
            'border_radius_bottom_right' => '--aipt-faq-border-radius-br',
            'border_radius_bottom_left'  => '--aipt-faq-border-radius-bl',
            'border_width_top'         => '--aipt-faq-border-width-top',
            'border_width_right'       => '--aipt-faq-border-width-right',
            'border_width_bottom'      => '--aipt-faq-border-width-bottom',
            'border_width_left'        => '--aipt-faq-border-width-left',
        ];

        $css_vars = [];
        foreach ( $css_var_map as $key => $var ) {
            if ( ! empty( $settings[ $key ] ) ) {
                $css_vars[] = esc_attr( $var ) . ':' . esc_attr( $settings[ $key ] ) . ';';
            }
        }

        $toggle_icon = isset( $settings['toggle_icon'] ) ? $settings['toggle_icon'] : 'chevron';
        if ( isset( FAQFrontendRenderer::get_toggle_icons()[ $toggle_icon ] ) ) {
            $css_vars[] = '--aipt-faq-toggle-icon: ' . FAQFrontendRenderer::get_toggle_icons()[ $toggle_icon ] . ';';
        }

        $inline_parts = [];

        if ( ! empty( $css_vars ) ) {
            $inline_parts[] = '.aipt-faq-accordion{' . implode( '', $css_vars ) . '}';
        }

        $custom_css = isset( $settings['custom_css'] ) ? trim( (string) $settings['custom_css'] ) : '';
        if ( '' !== $custom_css ) {
            $safe_css       = preg_replace( '#<\s*/?\s*(style|script)\b[^>]*>#i', '', $custom_css );
            $inline_parts[] = $safe_css;
        }

        if ( ! empty( $inline_parts ) ) {
            wp_add_inline_style(
                'aipt-faq-display',
                implode( "\n", $inline_parts )
            );
        }
    }
}
