<?php

namespace SEOAIC\shortcodes;

use SEOAIC\shortcodes\interfaces\ShortcodeInterface;

class FAQ implements ShortcodeInterface
{
    private $attrs;
    private $content;

    public function __construct($attrs, $content = '')
    {
        $this->attrs = empty($attrs) ? [] : (is_array($attrs) ? $attrs : [$attrs]);
        $this->content = $content;
    }

    private function makeHTML(array $questions, array $attrs = []): string
    {
        ob_start();
        ?>
        <div class="wp-block-seoaic-faq-block">
            <h2 class="seoaic-faq-section-title"><?php esc_html_e('Frequently Asked Questions', 'seoaic');?></h2>
            <?php
            foreach ($questions as $i => $question) {
                ?>
                <div class="seoaic-faq-item">
                    <h3 class="seoaic-question">
                        <?php echo esc_html($question['title']);?>
                    </h3>
                    <p class="seoaic-answer">
                        <?php
                        echo wp_kses($question['content'], [
                            'a'     => [
                                'href'      => [],
                                'target'    => [],
                                'class'     => [],
                                'title'     => [],
                            ],
                            'br'    => [],
                            'b'     => [],
                            'i'     => [],
                        ]);
                        ?>
                    </p>
                </div>
                <?php
            }
            ?>
        </div>
        <?php
        $html = ob_get_clean();

        return $html;
    }

    public function html(): string
    {
        $content = html_entity_decode($this->content);
        // $content = stripslashes($content);

        $questions = json_decode($content, true);
        $jsonError = json_last_error();

        if ($jsonError !== JSON_ERROR_NONE) {
            return esc_html__('FAQ broken data:', 'seoaic') . ' JSON error ' . $jsonError;
        }

        $html = $this->makeHTML($questions);

        return $html;
    }
}
