<?php

namespace AIPT\Api\BulkGenerator\FAQ;

/**
 * Unified HTML template engine for FAQ output.
 *
 * Consolidates three previously inconsistent FAQ HTML outputs into one:
 *  - AI prompt format (`<dl class="aipt-faq-list">`) — NOT produced here; lives in FAQGeneratorService.
 *  - Backend storage format — produced by renderFlat() / renderAccordion().
 *  - Frontend serialization — kept in sync via matching CSS class names.
 */
class FAQTemplateRenderer {

    /**
     * Return default settings used when none are provided.
     *
     * @return array<string, mixed>
     */
    public static function getDefaultSettings(): array {
        return [
            'container_class_name' => '',
        ];
    }

    /**
     * Render FAQ list as a native HTML accordion using <details>/<summary>.
     *
     * @param array<int, array<string, string>> $faqs     List of ['question' => ..., 'answer' => ...] pairs.
     * @param array<string, mixed>              $settings Optional display settings; supports 'container_class_name'.
     *
     * @return string Sanitized accordion HTML.
     */
    public static function renderAccordion(array $faqs, array $settings = []): string {
        $settings = array_merge(static::getDefaultSettings(), $settings);

        $container_class = 'aipt-faq-accordion';
        $custom_class    = isset($settings['container_class_name']) ? trim((string) $settings['container_class_name']) : '';
        if ($custom_class !== '') {
            $container_class .= ' ' . $custom_class;
        }

        $items = [];
        foreach ($faqs as $faq) {
            if (!is_array($faq)) {
                continue;
            }

            $question = isset($faq['question']) ? trim((string) $faq['question']) : '';
            $answer   = isset($faq['answer']) ? trim((string) $faq['answer']) : '';

            if ($question === '' && $answer === '') {
                continue;
            }

            $items[] = sprintf(
                '<details class="aipt-faq-item">' . "\n" .
                '  <summary class="aipt-faq-question">%s</summary>' . "\n" .
                '  <div class="aipt-faq-answer">%s</div>' . "\n" .
                '</details>',
                esc_html($question),
                wp_kses_post($answer)
            );
        }

        if (empty($items)) {
            return '';
        }

        return sprintf(
            '<div class="%s">' . "\n%s\n" . '</div>',
            esc_attr($container_class),
            implode("\n", $items)
        );
    }

    /**
     * Render FAQ list in the flat (non-accordion) format.
     *
     * @param array<int, array<string, string>> $faqs     List of ['question' => ..., 'answer' => ...] pairs.
     * @param string                            $format   'html' or 'text'.
     * @param array<string, mixed>              $settings Optional display settings for Q/A labels.
     *
     * @return string Rendered FAQ content.
     */
    public static function renderFlat( array $faqs, string $format, array $settings = [] ): string {
        $lines = [];

        $labels_enabled = isset( $settings['qa_labels_enabled'] ) ? (bool) $settings['qa_labels_enabled'] : true;
        $q_label        = isset( $settings['question_label'] ) ? trim( (string) $settings['question_label'] ) : 'Q';
        $a_label        = isset( $settings['answer_label'] ) ? trim( (string) $settings['answer_label'] ) : 'A';

        foreach ( $faqs as $faq ) {
            if ( ! is_array( $faq ) ) {
                continue;
            }

            $question = isset( $faq['question'] ) ? trim( (string) $faq['question'] ) : '';
            $answer   = isset( $faq['answer'] ) ? trim( (string) $faq['answer'] ) : '';

            if ( $format === 'html' ) {
                if ( $labels_enabled && $q_label !== '' ) {
                    $q_prefix = '<span class="aipt-faq-label">' . esc_html( $q_label ) . ':</span> ';
                } else {
                    $q_prefix = '';
                }
                if ( $labels_enabled && $a_label !== '' ) {
                    $a_prefix = '<span class="aipt-faq-label">' . esc_html( $a_label ) . ':</span> ';
                } else {
                    $a_prefix = '';
                }

                $lines[] = sprintf(
                    '<div class="aipt-faq-item"><h3 class="aipt-faq-question">%s%s</h3><div class="aipt-faq-answer">%s%s</div></div>',
                    $q_prefix,
                    esc_html( $question ),
                    $a_prefix,
                    wp_kses_post( $answer )
                );
                continue;
            }

            if ( $question !== '' ) {
				$q_text_prefix = ( $labels_enabled && $q_label !== '' ) ? $q_label . ': ' : '';
                $lines[]       = $q_text_prefix . $question;
            }
            if ( $answer !== '' ) {
				$a_text_prefix = ( $labels_enabled && $a_label !== '' ) ? $a_label . ': ' : '';
                $lines[]       = $a_text_prefix . $answer;
            }
            $lines[] = '';
        }

        if ( $format === 'html' && ! empty( $lines ) ) {
            return '<div class="aipt-faq-flat">' . "\n" . implode( "\n", $lines ) . "\n" . '</div>';
        }

        return trim( implode( "\n", $lines ) );
    }

    /**
     * Delegate to accordion or flat renderer based on caller intent.
     *
     * This is the primary entry-point for FAQGeneratorController.
     *
     * @param array<int, array<string, string>> $faqs             List of FAQ pairs.
     * @param string                            $format           'html' or 'text'.
     * @param bool                              $accordion_enabled Whether to use the accordion template.
     * @param array<string, mixed>              $settings         Optional display settings passed to renderAccordion().
     *
     * @return string Rendered FAQ content.
     */
    public static function renderForStorage(
        array $faqs,
        string $format,
        bool $accordion_enabled = false,
        array $settings = []
    ): string {
        if ( $accordion_enabled && $format === 'html' ) {
            return static::renderAccordion( $faqs, $settings );
        }

        return static::renderFlat( $faqs, $format, $settings );
    }
}
