<?php
/**
 * Frontend output for the AUX Factoid Collection component
 * AUX documentation: https://aggieux.tamu.edu/?path=/docs/components-factoid-collections-standard-factoid-collection-about-standard-factoid-collections--docs
 *
 * Outline:
 * 1. Set variables to null
 * 2. Get fields from the post, if they have values, wrap in html
 * 3. Build the component html
 * 4. Sanitize and output
 *
 * @author Hailey Sanders
 * @since 1.0.0
 */

use WP_AUX\Services\AuxCF\BlocksService;
use WP_AUX\Services\HtmlService;
use WP_AUX\Entities\AuxFramework\Partials\IconEntity;

$factoids = aux_get_field('factoid');
$factoidsCount = count($factoids);

$section = BlocksService::getSection('factoid-collection');

$footnoteClass = 'footnote';
$factoidClass = 'factoid';

if ('inline' === aux_get_field('factoid_layout_switch')) {
  $section->addComponentModifier('inline');
  $factoidClass .= ' factoid--inline';
} else {
  $footnoteClass .= ' footnote--centered';
}

// Loop through factoids to get HTML for each
$factoidsHtml = '';
if ($factoids) {
  foreach ($factoids as $factoid) {
    $icon = !empty($factoid['factoid_icon']) ? IconEntity::create($factoid['factoid_icon']) : '';

    // setting the full heading wrapper only if the heading field is filled out
    if ($factoidHeading = HtmlService::formattedValue($factoid['factoid_heading'], '<span class="heading">%s</span> ')) {
      $factoidHeading =
        sprintf('<div class="factoid__heading">
                   %s
                   %s
                   %s
                 </div>',
        HtmlService::formattedValue($factoid['factoid_superheader'], '<span class="superhead">%s</span>'),
        $factoidHeading,
        HtmlService::formattedValue($factoid['factoid_subheader'], '<span class="subhead">%s</span> ')
      );
    }

    $factoidContent = HtmlService::formattedValue($factoid['factoid_content'], '<span class="factoid__text">%s</span> ');

    $footnote = HtmlService::formattedValue($factoid['factoid_citation'], '<div class="%2$s"><span>%1$s</span></div>', $footnoteClass);

    $factoidsHtml .= <<<HTML
      <div class="$factoidClass">
        $icon
        $factoidHeading
        <div class="factoid__content">
          $factoidContent
          $footnote
        </div>
      </div>
    HTML;
  }
}

$section->setContent(<<<HTML
  <div class="factoid-collection__wrapper" data-cards="$factoidsCount">
    $factoidsHtml
  </div>
HTML);

echo $section;
