<?php

  function renderAssociatedMedia($artists = [], $books = [], $genres = [], $movies = [], $posts = [], $shows = [])
  {
    $media = array_merge($artists, $books, $genres, $movies, $posts, $shows);

    if (empty($media)) return;

    $sections = [
      "artists" => ["icon" => "headphones", "css_class" => "music", "label" => "Related artist(s)"],
      "books"   => ["icon" => "books", "css_class" => "books", "label" => "Related book(s)"],
      "genres"  => ["icon" => "headphones", "css_class" => "music", "label" => "Related genre(s)"],
      "movies"  => ["icon" => "movie", "css_class" => "movies", "label" => "Related movie(s)"],
      "posts"   => ["icon" => "article", "css_class" => "article", "label" => "Related post(s)"],
      "shows"   => ["icon" => "device-tv-old", "css_class" => "tv", "label" => "Related show(s)"]
    ];

    echo '<div class="associated-media">';

    foreach ($sections as $key => $section) {
      switch ($key) {
        case "artists":
          $items = $artists;
          break;
        case "books":
          $items = $books;
          break;
        case "genres":
          $items = $genres;
          break;
        case "movies":
          $items = $movies;
          break;
        case "posts":
          $items = $posts;
          break;
        case "shows":
          $items = $shows;
          break;
        default:
          $items = [];
      }

      if (!empty($items)) {
        echo '<p id="' . htmlspecialchars($key) . '" class="' . htmlspecialchars($section['css_class']) . '">';
        echo '<span class="icon">' . getTablerIcon($section['icon']) . '</span> ';
        echo htmlspecialchars($section['label']);
        echo '</p>';
        echo '<ul>';

        foreach ($items as $item) {
          echo '<li class="' . htmlspecialchars($section['css_class']) . '">';
          echo '<a href="' . htmlspecialchars($item['url']) . '">' . htmlspecialchars($item['title'] ?? $item['name'] ?? 'Untitled') . '</a>';

          if ($key === "artists" && isset($item['total_plays']) && $item['total_plays'] > 0) {
            echo ' (' . htmlspecialchars($item['total_plays']) . ' play' . ($item['total_plays'] > 1 ? 's' : '') . ')';
          } elseif ($key === "books" && isset($item['author'])) {
            echo ' by ' . htmlspecialchars($item['author']);
          } elseif (($key === "movies" || $key === "shows") && isset($item['year'])) {
            echo ' (' . htmlspecialchars($item['year']) . ')';
          } elseif ($key === "posts" && isset($item['date'])) {
            echo ' (' . date("F j, Y", strtotime($item['date'])) . ')';
          }

          echo '</li>';
        }

        echo '</ul>';
      }
    }

    echo '</div>';
  }

?>