<?php
// ===========================================================================================================
// templates.php
// All HTML rendering functions for the CPR Rescue plugin.
// ===========================================================================================================

// ===========================================================================================================
// Renders the full detail view for a dog - carousel + about panel + biography/story panels
// ===========================================================================================================
function animalDetail($result, $animalID) {
    $sections  = $result['data'][$animalID]['sections'];
    $dogName   = esc_html($result['data'][$animalID]['animalName']);

    $output  = "<div class='container'>\n  <div class='row'>\n";

    $output .= "  <div class='col-md-6 mb-4'>\n";
    $output .= addCarousel($result, $animalID);
    $output .= "  </div>\n";

    $output .= "  <div class='col-md-6 mb-4'>\n";
    $output .= addPanel('About Me', $sections['about']);
    $output .= "  </div>\n";

    $output .= "  </div>\n</div>\n";

    if (!empty($sections['biography'])) {
        $output .= addPanel('Biography',   $sections['biography']);
        $output .= addPanel('Sponsorship', $sections['sponsorship']);
    } else {
        $output .= addPanel("Here's Your Quick Peek", $sections['story']);
    }

    return $output;
}

// ===========================================================================================================
// Renders the searchable animal list grid
// ===========================================================================================================
function animalList($result, $isCPR, $animalName) {
    $output  = "<div class='container mb-4'>\n";
    $output .= "  <form action='index.php/available-dogs'>\n";
    $output .= "    <div class='input-group'>\n";
    $output .= "      <input type='text' class='form-control' name='animalName' value='{$animalName}'\n";
    $output .= "             placeholder='Enter the Name of a Dog or Breed to Search'\n";
    $output .= "             title='Clear search field to reset'\n";
    $output .= "             aria-label='Search dogs by name or breed'>\n";
    $output .= "      <button class='btn btn-outline-secondary' type='submit' aria-label='Search'>\n";
    $output .= "        <i class='bi bi-search' aria-hidden='true'></i>\n";
    $output .= "      </button>\n";
    $output .= "    </div>\n";
    $output .= "  </form>\n";
    $output .= "</div>\n";

    $output .= "<div class='container'>\n  <div class='row'>\n";

    foreach ($result['data'] as $animalID => $animal) {

        // Filter by name or breed if a search term was provided
        if ($animalName) {
            $safeName   = preg_quote($animalName, '/');
            $nameMatch  = preg_match("/$safeName/i", $animal['animalName']);
            $breedMatch = preg_match("/$safeName/i", $animal['animalBreed']);
            if (!$nameMatch && !$breedMatch) {
                continue;
            }
        }

        $name  = $isCPR ? $animal['animalName'] : filterSOSName($animal['animalName']);
        $title = '<strong>' . esc_html($name) . '</strong> <br> <small>' . esc_html($animal['animalBreed']) . '</small>';
        $url   = !empty($animal['animalPictures']['0']['large']['url'])
                 ? $animal['animalPictures']['0']['large']['url']
                 : CPR_PLACEHOLDER_IMG;

        $output .= galleryImage($title, $url, $animalID, $name);
    }

    $output .= "  </div>\n</div>\n";
    return $output;
}

// ===========================================================================================================
// Renders a single animal card in the list grid
// ===========================================================================================================
function galleryImage($title, $url, $animalID, $name) {
    $output  = "  <div class='col-md-4 mb-4'>\n";
    $output .= "    <div class='card h-100'>\n";
    $output .= "      <img src='{$url}' class='card-img-top cpr-animal-thumb' alt='Photo of {$name}'>\n";
    $output .= "      <div class='card-body'>\n";
    $output .= "        <h5 class='card-title'>{$title}</h5>\n";
    $output .= "        <a href='index.php/animal-detail?AnimalID={$animalID}' class='btn btn-primary'\n";
    $output .= "           aria-label='View details for {$name}'>View Details</a>\n";
    $output .= "      </div>\n";
    $output .= "    </div>\n";
    $output .= "  </div>\n";
    return $output;
}

// ===========================================================================================================
// Renders the photo and video carousel for the animal detail page
// ===========================================================================================================
function addCarousel($result, $animalID) {
    $pictures  = $result['data'][$animalID]['animalPictures']  ?? [];
    $videoUrls = $result['data'][$animalID]['animalVideoUrls'] ?? [];
    $dogName   = esc_html($result['data'][$animalID]['animalName']);

    // If there are no pictures or videos, show a placeholder
    if (empty($pictures) && empty($videoUrls)) {
        return "<div class='cpr-no-photo d-flex justify-content-center align-items-center bg-light'>\n"
             . "  <p class='text-muted'>No photos available for {$dogName} yet.</p>\n"
             . "</div>\n";
    }

    $output  = "<div id='dog-carousel' class='carousel slide' data-bs-ride='carousel' aria-label='Photos of {$dogName}'>\n";
    $output .= "  <div class='carousel-inner'>\n";

    $slideIndex  = 0;
    $totalSlides = count($pictures) + count($videoUrls);

    // Photo slides
    foreach ($pictures as $index => $picture) {
        $active  = $slideIndex === 0 ? 'active' : '';
        $url     = $picture['large']['url'];
        $slideNum = $slideIndex + 1;
        $output .= "    <div class='carousel-item {$active}'>\n";
        $output .= "      <img src='{$url}' class='d-block w-100 cpr-carousel-img'\n";
        $output .= "           alt='Photo {$slideNum} of {$totalSlides} — {$dogName}'>\n";
        $output .= "    </div>\n";
        $slideIndex++;
    }

    // YouTube video slides
    foreach ($videoUrls as $video) {
        $active  = $slideIndex === 0 ? 'active' : '';
        $videoID = htmlspecialchars($video['videoID']);
        $slideNum = $slideIndex + 1;
        $output .= "    <div class='carousel-item {$active}'>\n";
        $output .= "      <div class='cpr-video-slide d-flex justify-content-center align-items-center'>\n";
        $output .= "        <iframe class='cpr-video-iframe'\n";
        $output .= "                src='https://www.youtube.com/embed/{$videoID}'\n";
        $output .= "                title='Video {$slideNum} of {$totalSlides} — {$dogName}'\n";
        $output .= "                frameborder='0' allowfullscreen></iframe>\n";
        $output .= "      </div>\n";
        $output .= "    </div>\n";
        $slideIndex++;
    }

    $output .= "  </div>\n";

    // Prev/Next controls
    $output .= "  <button class='carousel-control-prev' type='button' data-bs-target='#dog-carousel' data-bs-slide='prev'>\n";
    $output .= "    <span class='carousel-control-prev-icon' aria-hidden='true'></span>\n";
    $output .= "    <span class='visually-hidden'>Previous photo</span>\n";
    $output .= "  </button>\n";
    $output .= "  <button class='carousel-control-next' type='button' data-bs-target='#dog-carousel' data-bs-slide='next'>\n";
    $output .= "    <span class='carousel-control-next-icon' aria-hidden='true'></span>\n";
    $output .= "    <span class='visually-hidden'>Next photo</span>\n";
    $output .= "  </button>\n";

    // Thumbnail strip — hidden on mobile, visible on md+
    $output .= "  <div class='row mt-3 d-none d-md-flex'>\n";

    $slideIndex = 0;

    foreach ($pictures as $picture) {
        $active  = $slideIndex === 0 ? 'border-primary' : '';
        $url     = $picture['large']['url'];
        $slideNum = $slideIndex + 1;
        $output .= "    <div class='col-2'>\n";
        $output .= "      <a href='#dog-carousel' data-bs-slide-to='{$slideIndex}'\n";
        $output .= "         aria-label='Go to photo {$slideNum}'>\n";
        $output .= "        <img src='{$url}' class='img-fluid border cpr-thumb {$active}'\n";
        $output .= "             alt='Thumbnail {$slideNum} — {$dogName}'>\n";
        $output .= "      </a>\n";
        $output .= "    </div>\n";
        $slideIndex++;
    }

    foreach ($videoUrls as $video) {
        $active   = $slideIndex === 0 ? 'border-primary' : '';
        $thumb    = htmlspecialchars($video['urlThumbnail']);
        $slideNum = $slideIndex + 1;
        $output .= "    <div class='col-2'>\n";
        $output .= "      <a href='#dog-carousel' data-bs-slide-to='{$slideIndex}'\n";
        $output .= "         aria-label='Go to video {$slideNum}'>\n";
        $output .= "        <img src='{$thumb}' class='img-fluid border cpr-thumb {$active}'\n";
        $output .= "             alt='Video thumbnail {$slideNum} — {$dogName}'>\n";
        $output .= "      </a>\n";
        $output .= "    </div>\n";
        $slideIndex++;
    }

    $output .= "  </div>\n";
    $output .= "</div>\n";

    return $output;
}

// ===========================================================================================================
// Renders a content panel with an optional action button for About Me and Sponsorship panels
// ===========================================================================================================
function addPanel($heading, $body) {
    $output  = "<div class='card mb-4'>\n";
    $output .= "  <div class='card-header'><h3>{$heading}</h3></div>\n";
    $output .= "  <div class='card-body'>\n";
    $output .= $body;

    if ($heading === 'About Me') {
        $output .= "    <a href='index.php/application' class='btn btn-success cpr-action-btn'\n";
        $output .= "       role='button' aria-label='Apply to adopt this dog'>Adopt</a>\n";
    }

    if ($heading === 'Sponsorship') {
        $output .= "    <a href='index.php/sponsor-a-dog/' class='btn btn-success cpr-action-btn'\n";
        $output .= "       role='button' aria-label='Donate to sponsor this dog'>Donate</a>\n";
    }

    $output .= "  </div>\n";
    $output .= "</div>\n";
    return $output;
}
