<?php
/**
 * Frontend output for the AUX Collection Feature component
 * AUX documentation: https://aggieux.tamu.edu/?path=/docs/components-collection-features-about-collection-features--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\IconEntity;
use WP_AUX\Enum\SocialMediaProfilesEnum;
use WP_AUX\Services\AuxFramework\ElementClassesService;
use WP_AUX\Services\HtmlService;

$socialListItems =
$background =
$socialBannerHeading = null;

// Get fields from the post
$socialBannerHeading = aux_get_field('social_banner_heading');
$socialLinks = aux_get_field('social_banner_links');
$background = aux_get_field('social_banner_background');

// Setting background and style classes with helpers
$sectionClasses = ElementClassesService::buildClasses('section-wrap', '', $background);
$componentClasses = ElementClassesService::buildClasses('social-collection', '', $sectionClasses);

// Setting the heading
$socialBannerHeading = HtmlService::formattedValue($socialBannerHeading, '<span class="social-collection__heading">%s</span> ');

$socialList = '';
if ($socialLinks) {
  // Setting the link list of social profiles
  $socialListItems = '';

  foreach ($socialLinks as $socialLink) {
    $platform = SocialMediaProfilesEnum::tryFrom($socialLink['social_banner_links_platform']);

    if (empty($platform)) {
      continue;
    }

    $handle = @$socialLink['social_banner_links_handle'];
    $link = @$socialLink['social_banner_links_link'];

    if (SocialMediaProfilesEnum::LinkedIn === $platform) {
      $handle = @$link['url'];
      $text = @$link['title'];
    } else {
      $text = '@' . $handle;
    }

    $itemIcon = IconEntity::create($platform->icon(), false);
    $url = $platform->url($handle);

    if (empty($url)) {
      continue;
    }

    $socialListItems .= sprintf(
      '<li><a href="%s" aria-label="%s">%s</a></li>',
      $url,
      esc_attr($text),
      (string) $itemIcon,
    );
  }

  $socialList = sprintf('<ul class="social-collection__list">%s</ul>', $socialListItems);
}


// Build the output html for the component
$output = <<<HTML
  <section class="$sectionClasses">
    <div class="$componentClasses social-collection--divider">
        $socialBannerHeading
        $socialList
    </div>
  </section>
  HTML;

echo $output;
