<?php
// includes/template_generator.php

function generateWeddingIndex(array $p, array $photos): string {
    $groomName   = htmlspecialchars($p['groom_name']);
    $brideName   = htmlspecialchars($p['bride_name']);
    $dirName     = htmlspecialchars($p['directory_name']);
    $quote       = htmlspecialchars($p['quote'] ?? '');
    $quoteRef    = htmlspecialchars($p['quote_reference'] ?? '');
    $groomFamily = htmlspecialchars($p['groom_family'] ?? '');
    $brideFamily = htmlspecialchars($p['bride_family'] ?? '');
    $churchName  = htmlspecialchars($p['church_name'] ?? '');
    $churchUrl   = htmlspecialchars($p['church_location_url'] ?? '#');
    $venueName   = htmlspecialchars($p['venue_name'] ?? '');
    $venueUrl    = htmlspecialchars($p['venue_location_url'] ?? '#');
    $giftMethod  = $p['gift_method'] ?? 'whish';
    $giftNumber  = htmlspecialchars($p['gift_number'] ?? '');
    $giftLabel   = strtoupper($giftMethod) . ' Money';
    $rsvpDeadline = isset($p['rsvp_deadline']) ? date('F j, Y', strtotime($p['rsvp_deadline'])) : '';
    $groomPhone  = htmlspecialchars($p['groom_phone'] ?? '');
    $bridePhone  = htmlspecialchars($p['bride_phone'] ?? '');
    $thumbnail   = htmlspecialchars($p['thumbnail_file'] ?? 'img/thumbnail.jpg');
    $lastImage   = htmlspecialchars($p['last_image_file'] ?? 'img/love.png');
    $music       = htmlspecialchars($p['music_file'] ?? 'img/music.mp3');
    $ogUrl       = htmlspecialchars($p['og_url'] ?? '');

    // Wedding datetime for JS countdown (UTC)
    $weddingDT   = new DateTime($p['wedding_datetime']);
    $weddingDT->setTimezone(new DateTimeZone('UTC'));
    $jsDate = "new Date(Date.UTC({$weddingDT->format('Y')}, " . ($weddingDT->format('n') - 1) . ", {$weddingDT->format('j')}, {$weddingDT->format('G')}, {$weddingDT->format('i')}, 0))";

    // Format displayed date
    $displayDate = date('F j, Y \a\t g:i A', strtotime($p['wedding_datetime']));

    // Background images
    $bgImages = '';
    foreach ($photos as $photo) {
        $bgImages .= "      <img src=\"img/" . htmlspecialchars($photo) . "\" />\n";
    }

    $html = <<<HTML
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta property="og:title" content="Wedding of {$groomName} &amp; {$brideName}" />
    <meta property="og:description" content="Check out this Invitation!" />
    <meta property="og:image" content="{$ogUrl}/img/{$thumbnail}" />
    <meta property="og:url" content="{$ogUrl}" />
    <meta property="og:type" content="website" />
    <meta property="og:image:width" content="1200" />
    <meta property="og:image:height" content="630" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Wedding of {$groomName} &amp; {$brideName}</title>
    <link rel="stylesheet" href="css/main.css" />
  </head>
  <body>
    <div class="background">
{$bgImages}    </div>
    <div class="background-overlay"></div>
    <audio id="bg-music" loop autoplay>
      <source src="{$music}" type="audio/mpeg" />
    </audio>
    <button id="music-toggle" onclick="toggleMusic()">
      <svg id="music-icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
        <path d="M3 9v6h4l5 5V4L7 9H3z" />
        <path d="M14 8v8c1.38 0 2.63-.56 3.54-1.46a4.97 4.97 0 0 0 0-5.08A4.978 4.978 0 0 0 14 8z" />
      </svg>
    </button>
    <div class="burger" id="burger" onclick="toggleMenu()">
      <span></span><span></span><span></span>
    </div>
    <nav class="menu" id="menu">
      <a href="#home" onclick="toggleMenu()">Home</a>
      <a href="#invitation" onclick="toggleMenu()">Invitation</a>
      <a href="#location" onclick="toggleMenu()">Location</a>
      <a href="#registry" onclick="toggleMenu()">Gift Registry</a>
      <a href="#rsvp" onclick="toggleMenu()">Reservation</a>
      <a href="#love" onclick="toggleMenu()">Love.</a>
    </nav>
    <div class="carousel">

      <section class="slide visible" id="start">
        <button id="start-button" onclick="startExperience()">Start</button>
      </section>

      <section class="slide" id="home">
        {$groomName}<br />&amp;<br />{$brideName}
        <span class="married">Are Getting Married</span>
        <div id="countdown">Loading countdown...</div>
        <div class="swipe-down">Swipe Up</div>
      </section>

      <section class="slide" id="invitation">
        <div style="max-width:600px;width:100%;padding:0 20px">
          <p class="quote">&ldquo;{$quote}&rdquo;</p>
          <p class="verse">{$quoteRef}</p>
          <p class="families">{$groomFamily} &amp; {$brideFamily}<br />Families</p>
          <p class="invite">invite you to celebrate the wedding of</p>
          <p class="names">{$groomName} &amp; {$brideName}</p>
        </div>
        <div class="swipe-down">Swipe Up</div>
      </section>

      <section class="slide" id="location">
        <div class="ceremony-title">Ceremony</div>
        <div class="location-block">
          <img src="img/icon-date.png" alt="Date Icon" class="icon" />
          <div class="location-name">{$displayDate}</div>
        </div>
        <div class="location-block">
          <img src="img/icon-church.png" alt="Church Icon" class="icon" />
          <div class="location-name">{$churchName}</div>
          <a class="map-button" href="{$churchUrl}" target="_blank">Location Map</a>
        </div>
        <div class="location-block">
          <img src="img/icon-venue.png" alt="Venue Icon" class="icon" />
          <div class="location-name">{$venueName}</div>
          <a class="map-button" href="{$venueUrl}" target="_blank">Location Map</a>
        </div>
        <div class="swipe-down">Swipe Up</div>
      </section>

      <section class="slide" id="registry">
        <div style="max-width:600px;width:100%;padding:0 20px">
          <p class="registry-text">
            Your love, laughter, and company on our wedding day are the greatest gifts of all.
            However, if you would like to contribute to our new journey, a wedding list is available at
          </p>
          <p class="whish-code">{$giftLabel} # {$giftNumber}</p>
        </div>
        <div class="swipe-down">Swipe Up</div>
      </section>

      <section class="slide" id="rsvp">
        <br /><br />
        <p style="font-family:'Luxurious Roman',serif;font-size:24px;color:white;">
          Kindly Confirm your Reservation by {$rsvpDeadline}
        </p>
        <div id="inviteeList" style="margin-top:20px"></div>
        <div id="updateMessage" class="update-message" style="display:none;margin-top:20px"></div>
        <div class="swipe-down">Swipe Up</div>
      </section>

      <section class="slide" id="love">
        <img src="{$lastImage}" alt="Love" style="width:80%;max-width:400px;height:auto" />
        <p style="font-family:'Luxurious Roman',serif;font-size:18px;color:white;text-align:center;margin-top:20px;">
          Powered by Agenz | 71998578
        </p>
      </section>

    </div>

    <script>
      const countdown = document.getElementById('countdown');
      const weddingDateUTC = {$jsDate};
      function updateCountdown() {
        const now = new Date();
        const diff = weddingDateUTC - now;
        if (diff <= 0) { countdown.textContent = 'The wedding has started!'; clearInterval(intervalId); return; }
        const days    = Math.floor(diff / (1000*60*60*24));
        const hours   = Math.floor((diff % (1000*60*60*24)) / (1000*60*60));
        const minutes = Math.floor((diff % (1000*60*60)) / (1000*60));
        const seconds = Math.floor((diff % (1000*60)) / 1000);
        countdown.textContent = days+'d '+hours+'h '+minutes+'m '+seconds+'s';
      }
      const intervalId = setInterval(updateCountdown, 1000);
      updateCountdown();

      function toggleMenu() {
        document.getElementById('burger').classList.toggle('open');
        document.getElementById('menu').classList.toggle('open');
      }
      function toggleMusic() {
        const music = document.getElementById('bg-music');
        const icon  = document.getElementById('music-icon');
        if (music.paused) { music.play(); icon.style.fill='white'; }
        else { music.pause(); icon.style.fill='gray'; }
      }
      function startExperience() {
        const music = document.getElementById('bg-music');
        if (music.paused) music.play();
        document.getElementById('home').scrollIntoView({behavior:'smooth'});
      }

      const urlParams = new URLSearchParams(window.location.search);
      const token = urlParams.get('token');

      function loadInvitees() {
        const container = document.getElementById('inviteeList');
        const updateMessage = document.getElementById('updateMessage');
        if (!token) return;
        fetch('get_invitees.php?token='+encodeURIComponent(token))
          .then(r => r.json())
          .then(data => {
            container.innerHTML = '';
            updateMessage.style.display = 'none';
            if (!data.invitees || !data.invitees.length) return;
            let hasResponse = false;
            data.invitees.forEach(inv => {
              const div = document.createElement('div');
              div.style.cssText = 'margin-bottom:15px;text-align:center';
              let html = '<p>'+inv.name+'</p>';
              if (inv.response_status) {
                html += '<p style="color:#B8A67C;">You responded: <strong>'+inv.response_status+'</strong></p>';
                hasResponse = true;
              } else {
                html += '<div><button class="accept-btn" onclick="respond(\''+token+'\','+inv.invitee_id+',\'Accept\')">Accept</button>'
                      + '<button class="decline-btn" onclick="respond(\''+token+'\','+inv.invitee_id+',\'Decline\')">Decline</button></div>';
              }
              div.innerHTML = html;
              container.appendChild(div);
            });
            if (hasResponse) {
              updateMessage.innerHTML = 'In case you need to update your Reservation<br />Kindly contact:<br />{$groomName}: {$groomPhone}<br />{$brideName}: {$bridePhone}';
              updateMessage.style.display = 'block';
            }
          }).catch(console.error);
      }

      function respond(token, invitee_id, status) {
        fetch('respond.php?token='+encodeURIComponent(token)+'&invitee_id='+invitee_id+'&status='+encodeURIComponent(status))
          .then(r => r.json())
          .then(data => {
            if (data.success) { alert('Thank you for your response!'); loadInvitees(); }
            else alert('There was a problem submitting your response.');
          }).catch(() => alert('Error submitting response.'));
      }

      window.onload = () => { updateCountdown(); loadInvitees(); };

      const slides = document.querySelectorAll('.slide');
      const observer = new IntersectionObserver(entries => {
        entries.forEach(e => e.target.classList.toggle('visible', e.isIntersecting));
      }, {threshold: 0.1});
      slides.forEach(s => observer.observe(s));
    </script>
  </body>
</html>
HTML;

    return $html;
}
