<?php
/**
 * Frontend output for the AUX Link List Collection - Multiple Lists component
 * AUX documentation: https://aggieux.tamu.edu/?path=/docs/components-link-list-collections-link-list-collection-multiple-lists-about-link-list-collections-multiple-lists--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\Entities\AuxFramework\Partials\LinkListEntity;
use WP_AUX\Services\AuxCF\BlocksService;

$linkListMegaCol = aux_get_field('link_list_multi_list_mega');

// Testing if link lists are non-empty before doing a count
$listCount = 0;
if (!empty($linkListMegaCol)) {
  $listCount = count($linkListMegaCol);
}

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

// setting heading level based on section intro
$headingLevel = $section->hasIntro() ? 3 : 2;

$theLinks = '';
if ($linkListMegaCol) {
  foreach ($linkListMegaCol as $linkListMega) {
    $linkListItems = $linkListMega['link_list_multi_list'];

    // setting the link list and list heading
    $linkList = LinkListEntity::create();
    $linkList->setHeading($linkListMega['multi_list_link_heading'])->setHeadingLevel($headingLevel);

    // Loop through top-level link items to add to link list
    foreach ($linkListItems as $linkItem) {
      $linkListItem = $linkList->addLink($linkItem['multi_list_link_list_link']);

      if (!$linkListItem) {
        continue;
      }

      $linkListItem->setDescription($linkItem['multi_list_link_description']);

      // Check for and loop through nested link items to add to top-level link item
      if (!empty($linkItem['multi_list_link_nested_list'])) {
        foreach ($linkItem['multi_list_link_nested_list'] as $nestedLinkItem) {
          $nestedLinkListItem = $linkListItem->addNestedLink($nestedLinkItem['link_list_multi_list_nested_link']);
          $nestedLinkListItem->setDescription($nestedLinkItem['multi_list_link_nested_description']);
        }
      }
    }

    $theLinks .= $linkList;
  }
}

$section->setContent(<<<HTML
  <div class="link-list__wrapper" data-cards="$listCount">
    $theLinks
  </div>
HTML);

echo $section;
