<?php

namespace TSNV_SEO;

class FAQSchema extends AbstractSchema {
  private array $items = [];

  public function __construct(array $data = []) {
  	parent::__construct();
  	
    foreach ($data as $item) {
      $question = trim((string) ($item['question'] ?? ''));
      $answer = trim((string) ($item['answer'] ?? ''));

      if ($question && $answer) {
        $this->items[] = [
          '@type' => 'Question',
          'name' => $question,
          'acceptedAnswer' => [
            '@type' => 'Answer',
            'text' => $answer,
          ]
        ];
      }
    }
  }

  public function isValid(): bool {
    return !empty($this->items);
  }

  public function getJsonLd(): array {
    if (!$this->isValid()) {
      return [];
    }

    return [
      '@context' => 'https://schema.org',
      '@type' => 'FAQPage',
      'mainEntity' => $this->items,
    ];
  }
}
