<?php

/**
 * Public Invitation Render View
 *
 * Renders the full public wedding invitation customized for the guest,
 * supporting dynamic theme styles, section ordering, and visibility checks.
 *
 * Flow Order:
 * 1. Hero Cover
 * 2. Our Love Story
 * 3. Ceremony Agenda
 * 4. Gallery Slider
 * 5. RSVP
 * 6. Leave Your Wishes
 * 7. Gift & QRIS
 * 8. Story Gallery
 * 9. Warm Wishes
 * 10. Digital Entry Pass
 *
 * @package Inveetaire
 * @ref     PILOT-005
 */

/** @var array $workspace */
/** @var array $guest */
/** @var array $invitation */
/** @var array $events */
/** @var array $theme */
/** @var array $sections */
/** @var string $url */
/** @var string $qr_code */
/** @var array|null $rsvp */
/** @var array|null $wish */
/** @var bool $live_preview Live Preview mode flag — true when rendering for the Couple via /{slug}/livepreview. */

$live_preview = (bool) ($live_preview ?? false);

use App\Core\Session;

$groomName = $invitation['groom_display_name'] ?? 'Groom';
$brideName = $invitation['bride_display_name'] ?? 'Bride';
$guestName = $guest['full_name'] ?? 'Guest';
$guestToken = $guest['guest_code'] ?? '';
$weddingDateStr = $workspace['wedding_date'] ?? date('Y-m-d');
$themeSlug = $theme['slug'] ?? 'klasik-putih';
$pax = (int) ($guest['invited_pax'] ?? 1);

// Extract session success/error notification banners
$errorsList = Session::get('errors') ?? [];
$successMessage = Session::get('success') ?? null;
Session::set('errors', null);
Session::set('success', null);

// Theme-specific CSS styling configurations
$themeStyles = [
    'klasik-putih' => [
        'bg'          => 'bg-slate-50',
        'cardBg'      => 'bg-white',
        'borderColor' => 'border-slate-200',
        'textColor'   => 'text-slate-800',
        'subText'     => 'text-slate-500',
        'accent'      => 'text-amber-600',
        'accentBg'    => 'bg-amber-50',
        'accentBorder'=> 'border-amber-100',
        'primaryBtn'  => 'bg-amber-500 hover:bg-amber-600 text-white',
        'fontSerif'   => 'font-serif-fancy',
        'accentLine'  => 'from-amber-200 via-amber-400 to-amber-200',
    ],
    'rustic-brown' => [
        'bg'          => 'bg-stone-100',
        'cardBg'      => 'bg-[#faf7f2]',
        'borderColor' => 'border-[#e4ded0]',
        'textColor'   => 'text-stone-800',
        'subText'     => 'text-stone-500',
        'accent'      => 'text-[#8c6239]',
        'accentBg'    => 'bg-[#efe9db]',
        'accentBorder'=> 'border-[#e4ded0]',
        'primaryBtn'  => 'bg-[#8c6239] hover:bg-[#735130] text-white',
        'fontSerif'   => 'font-serif-fancy',
        'accentLine'  => 'from-stone-300 via-stone-400 to-stone-300',
    ],
    'dark-elegance' => [
        'bg'          => 'bg-zinc-950',
        'cardBg'      => 'bg-zinc-900',
        'borderColor' => 'border-zinc-800',
        'textColor'   => 'text-zinc-100',
        'subText'     => 'text-zinc-400',
        'accent'      => 'text-emerald-400',
        'accentBg'    => 'bg-emerald-950/50',
        'accentBorder'=> 'border-emerald-900',
        'primaryBtn'  => 'bg-emerald-600 hover:bg-emerald-700 text-white',
        'fontSerif'   => 'font-serif-fancy',
        'accentLine'  => 'from-emerald-800 via-emerald-600 to-emerald-800',
    ]
];

$style = $themeStyles[$themeSlug] ?? $themeStyles['klasik-putih'];

// Index sections by slug for deterministic flow layout
$sectionMap = [];
foreach ($sections as $sec) {
    $sectionMap[$sec['slug']] = $sec['config'];
}

// Extract media configuration details
$mediaConfig = $sectionMap['media'] ?? [];
$musicEnabled   = (bool) ($mediaConfig['music_enabled'] ?? false);
$musicFile      = $mediaConfig['music_file'] ?? null;
$musicFileUrl   = $musicFile ? url('/i/media/serve') . '?path=' . urlencode($musicFile) : '';
$musicCover     = $mediaConfig['music_cover'] ?? null;
$musicCoverUrl  = $musicCover ? url('/i/media/serve') . '?path=' . urlencode($musicCover) : '';
$songTitle      = $mediaConfig['music_title'] ?? 'Wedding Song';
$songArtist     = $mediaConfig['music_artist'] ?? '';
$autoplay       = (bool) ($mediaConfig['music_autoplay'] ?? true);
$loop           = (bool) ($mediaConfig['music_loop'] ?? true);
$startMinimized = (bool) ($mediaConfig['music_minimized'] ?? false);
$volume         = (int) ($mediaConfig['music_volume'] ?? 30);

?>
<!DOCTYPE html>
<html lang="en">
<?php require __DIR__ . '/identity/partials/head.php'; ?>

<body class="font-sans-modern <?= $style['bg'] ?> min-h-screen flex flex-col items-center pt-0 sm:pt-6 pb-28 md:pb-36 px-0 sm:px-4 md:px-6">

    <div class="w-full max-w-5xl space-y-4 my-0 sm:my-2">
        
        <!-- Banners Success/Error Warnings -->
        <?php if (!empty($errorsList)): ?>
            <div class="rounded-2xl bg-red-50 border border-red-200 p-4 text-xs text-red-700 shadow-sm mx-4 sm:mx-0">
                <ul class="list-disc pl-4 space-y-1">
                    <?php foreach ($errorsList as $err): ?>
                        <li><?= escape_html($err) ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <?php if ($successMessage !== null): ?>
            <div class="rounded-2xl bg-emerald-50 border border-emerald-200 p-4 text-xs text-emerald-800 font-semibold text-center shadow-sm mx-4 sm:mx-0">
                <?= escape_html($successMessage) ?>
            </div>
        <?php endif; ?>
        
        <?php
            // Get Section Background media
            $bgMedia = $mediaConfig['background'] ?? null;
            $bgDesktopUrl = '';
            $bgMobileUrl = '';
            
            if (is_array($bgMedia)) {
                $bgDesktopUrl = !empty($bgMedia['desktop']) ? url('/i/media/serve') . '?path=' . urlencode($bgMedia['desktop']) : '';
                $bgMobileUrl = !empty($bgMedia['mobile']) ? url('/i/media/serve') . '?path=' . urlencode($bgMedia['mobile']) : '';
            } elseif (is_string($bgMedia) && $bgMedia !== '') {
                $bgDesktopUrl = url('/i/media/serve') . '?path=' . urlencode($bgMedia);
            }
            if ($bgMobileUrl === '') {
                $bgMobileUrl = $bgDesktopUrl;
            }
        ?>
        <!-- Main Responsive Invitation Container -->
        <div class="<?= $style['cardBg'] ?> rounded-none sm:rounded-[2rem] border-0 sm:border <?= $style['borderColor'] ?> shadow-2xl overflow-hidden relative">
            
            <?php if ($bgDesktopUrl !== ''): ?>
                <picture class="absolute inset-0 w-full h-full z-0 pointer-events-none opacity-20">
                    <source media="(max-width: 767px)" srcset="<?= escape_html($bgMobileUrl) ?>">
                    <img src="<?= escape_html($bgDesktopUrl) ?>" alt="Section Background" class="w-full h-full object-cover object-center fixed">
                </picture>
            <?php endif; ?>

            <!-- Container for content, ensuring it sits above background -->
            <div class="relative z-10 w-full h-full">

            <!-- Dynamic Accent Top Border Line -->
            <div class="h-4 bg-gradient-to-r <?= $style['accentLine'] ?>"></div>

            <?php require __DIR__ . '/identity/sections/hero.php'; ?>
            <?php require __DIR__ . '/identity/sections/story.php'; ?>
            <?php require __DIR__ . '/identity/sections/countdown.php'; ?>
            <?php require __DIR__ . '/identity/sections/ceremony.php'; ?>
            <?php require __DIR__ . '/identity/sections/venue.php'; ?>
            <?php require __DIR__ . '/identity/sections/gallery.php'; ?>
            <?php require __DIR__ . '/identity/sections/rsvp.php'; ?>
            <?php require __DIR__ . '/identity/sections/wishes.php'; ?>
            <?php require __DIR__ . '/identity/sections/gift.php'; ?>
            <?php require __DIR__ . '/identity/sections/story_gallery.php'; ?>
            <?php require __DIR__ . '/identity/sections/warm_wishes.php'; ?>
            <?php require __DIR__ . '/identity/sections/entry_pass.php'; ?>
            </div> <!-- Close z-10 wrapper -->
    </div>

    <?php require __DIR__ . '/identity/partials/footer.php'; ?>

    <!-- ================================================================= -->
    <!-- MODALS & POPUPS                                                   -->
    <!-- ================================================================= -->

    <?php require __DIR__ . '/identity/partials/pass_modal.php'; ?>
    <?php require __DIR__ . '/identity/partials/qris_modal.php'; ?>
    <!-- ================================================================= -->
    <?php require __DIR__ . '/identity/partials/scripts.php'; ?>
</body>
</html>
