<?php

namespace SEOAIC\content_editor_blocks\providers;

use SEOAIC\interfaces\BlocksInterface;
use SEOAIC\content_editor_blocks\blocks\FAQBlock;

class RankMathBlocks implements BlocksInterface
{
    private $blockPrefix = 'rank-math';

    public function faq($questions=[])
    {
        if (
            empty($questions)
            || !is_array($questions)
        ) {
            return '';
        }

        array_walk($questions, function(&$item) {
            $item = [
                'title' => $item['question'],
                'content' => $item['answer'],
                'visible' => true,
            ];
        });

        $attrs = [
            'listStyle'         => '',
            'textAlign'         => 'left',
            'titleWrapper'      => 'h3',
            'listCssClasses'    => '',
            'titleCssClasses'   => '',
            'contentCssClasses' => '',
            'questions'         => $questions,
            'className'         => '',
        ];

        $block = new FAQBlock(
            $this->blockPrefix,
            $attrs,
            $this->faqHTML($attrs)
        );

        return $block->render();
    }

    private function faqHTML($attributes)
    {
		$out = ['<div class="wp-block-rank-math-faq-block">'];

		foreach ($attributes['questions'] as $question) {
			if (
                empty($question['title'])
                || empty($question['content'])
                // || empty($question['visible'])
            ) {
				continue;
			}

			$out[] = '<div class="rank-math-faq-item">';
			$out[] = sprintf(
				'<%1$s class="rank-math-question">%2$s</%1$s>',
				$attributes['titleWrapper'],
				$question['title']
			);

			$out[] = sprintf(
				'<div class="rank-math-answer">%2$s</div>',
				$attributes['titleWrapper'],
				$question['content']
			);

			$out[] = '</div>';
		}

		$out[] = '</div>';

		return join('', $out);
	}
}
