<?php

namespace TSNV_SEO;

class ReviewSchema extends AbstractSchema {
  private array $items = [];
  private string $itemName = '';

  public function __construct(array $data = []) {
    parent::__construct();

    $this->itemName = trim((string) ($data['item_name'] ?? ''));

    $reviews = is_array($data['reviews'] ?? null) ? $data['reviews'] : [];

    foreach ($reviews as $review) {
      $author = trim((string) ($review['author'] ?? 'Anonymous'));
      $review_body = trim((string) ($review['review_body'] ?? ''));
      $rating_value = isset($review['rating_value']) ? (int) $review['rating_value'] : null;

      if ($review_body === '') {
        continue;
      }

      $reviewData = [
        '@type' => 'Review',
        'author' => [
          '@type' => 'Person',
          'name' => $author,
        ],
        'reviewBody' => $review_body,
        'itemReviewed' => [
          '@type' => 'VideoGame',
          'name' => $this->itemName,
        ],
      ];

      if ($rating_value !== null) {
        $reviewData['reviewRating'] = [
          '@type' => 'Rating',
          'ratingValue' => (string) $rating_value,
          'bestRating' => '5',
          'worstRating' => '1',
        ];
      }

      $this->items[] = $reviewData;
    }
  }

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

  protected function getJsonLd(): array {
    return [
      '@context' => 'https://schema.org',
      '@graph' => $this->items,
    ];
  }
}
