<?php
/**
 * ITSWEBER CMS – Default Theme: Social Embed Section Template
 * Page Builder section template (3.2.0)
 *
 * Variables: $data (array), $section (DB row), $sectionId (string)
 *
 * @author  Benny Weber
 * @copyright ITSWEBER, www.itsweber.de
 */

$title            = $data['title'] ?? '';
$subtitle         = $data['subtitle'] ?? '';
$colorScheme      = $data['color_scheme'] ?? '';
$sectionTextColor = $data['section_text_color'] ?? '';
$columns          = $data['columns'] ?? '3';
$ctaText          = $data['cta_text'] ?? '';
$ctaUrl           = $data['cta_url'] ?? '';
$items            = (isset($data['items']) && is_array($data['items'])) ? $data['items'] : [];

if (empty($items)) return;

// Check if consent module is enabled (for gating external embeds)
$consentEnabled = function_exists('consent_enabled') && consent_enabled();

// Provider detection helper (may already be loaded from plugin, define if not)
if (!function_exists('ses_detect_provider')) {
    function ses_detect_provider(string $url): array {
        $url = trim($url);
        if (preg_match('#(?:https?://)?(?:www\.)?tiktok\.com/@([^/]+)/video/(\d+)#i', $url, $m)) {
            return ['provider' => 'tiktok', 'id' => $m[2], 'username' => $m[1]];
        }
        if (preg_match('#(?:https?://)?vm\.tiktok\.com/([a-zA-Z0-9]+)#i', $url, $m)) {
            return ['provider' => 'tiktok', 'id' => $m[1], 'username' => ''];
        }
        if (preg_match('#(?:https?://)?(?:www\.)?instagram\.com/(?:p|reel)/([a-zA-Z0-9_-]+)#i', $url, $m)) {
            return ['provider' => 'instagram', 'id' => $m[1], 'username' => ''];
        }
        if (preg_match('#(?:https?://)?(?:www\.)?youtube\.com/shorts/([\w-]+)#i', $url, $m)) {
            return ['provider' => 'youtube_shorts', 'id' => $m[1], 'username' => ''];
        }
        return ['provider' => 'unknown', 'id' => '', 'username' => ''];
    }
}

// Build CSS classes
$cls = 'social-embed-section';
if ($colorScheme !== '')      $cls .= ' section--scheme-' . e($colorScheme);
$surface = $data['section_surface'] ?? '';
if ($surface !== '')          $cls .= ' section--surface-' . e($surface);
if ($sectionTextColor !== '') $cls .= ' section--text-' . e($sectionTextColor);
$cls .= ' ses--cols-' . e($columns);
?>
<section class="<?= $cls ?>" id="<?= e($sectionId) ?>"<?php if ($consentEnabled): ?> data-ses-consent="functional"<?php endif; ?>>
    <div class="container">
        <?php if ($title !== '' || $subtitle !== ''): ?>
        <div class="ses-header reveal">
            <?php if ($subtitle !== ''): ?>
            <div class="ses-label"><?= e($subtitle) ?></div>
            <?php endif; ?>
            <?php if ($title !== ''): ?>
            <h2 class="ses-title"><?= e($title) ?></h2>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <div class="ses-grid">
            <?php foreach ($items as $item):
                $url        = $item['url'] ?? '';
                $provider   = $item['provider'] ?? '';
                $providerId = $item['provider_id'] ?? '';
                $username   = $item['username'] ?? '';
                $itemTitle  = $item['title'] ?? '';
                $itemDesc   = $item['description'] ?? '';

                // Fallback: detect provider from URL if not pre-populated
                if (($provider === '' || $provider === 'unknown') && $url !== '') {
                    $_detected  = ses_detect_provider($url);
                    $provider   = $_detected['provider'];
                    $providerId = $_detected['id'];
                    $username   = $_detected['username'];
                }
            ?>
            <div class="ses-item ses-item--<?= e($provider) ?>" data-ses-provider="<?= e($provider) ?>" data-ses-url="<?= e($url) ?>">
                <?php if ($provider === 'tiktok' && $providerId !== ''): ?>
                    <!-- TikTok embed: consent-gated -->
                    <div class="ses-embed-wrap" data-ses-embed="pending">
                        <div class="ses-consent-placeholder">
                            <div class="ses-consent-icon">
                                <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                    <path d="M34.1 10.2c-2.4-1.5-4-4.1-4.3-7.2h-6.5v26.5c0 3.3-2.7 6-6 6s-6-2.7-6-6 2.7-6 6-6c.6 0 1.2.1 1.7.3v-6.6c-.6-.1-1.1-.1-1.7-.1-7 0-12.6 5.7-12.6 12.6S10.3 42.3 17.3 42.3s12.6-5.7 12.6-12.6V15.8c2.6 1.9 5.8 3 9.2 3v-6.5c-1.9 0-3.6-.7-5-2.1z" fill="currentColor" opacity=".6"/>
                                </svg>
                            </div>
                            <p class="ses-consent-text">External content from TikTok</p>
                            <button type="button" class="ses-consent-btn btn">Load Content</button>
                        </div>
                        <template class="ses-embed-template">
                            <blockquote class="tiktok-embed"
                                cite="<?= e($url) ?>"
                                data-video-id="<?= e($providerId) ?>"
                                style="max-width:100%;min-width:280px;">
                                <section>
                                    <a target="_blank" href="<?= e($url) ?>">View on TikTok</a>
                                </section>
                            </blockquote>
                        </template>
                    </div>
                <?php elseif ($provider === 'instagram' && $providerId !== ''): ?>
                    <!-- Instagram embed: consent-gated -->
                    <div class="ses-embed-wrap" data-ses-embed="pending">
                        <div class="ses-consent-placeholder">
                            <div class="ses-consent-icon">
                                <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                    <rect x="6" y="6" width="36" height="36" rx="10" stroke="currentColor" stroke-width="3" fill="none" opacity=".6"/>
                                    <circle cx="24" cy="24" r="9" stroke="currentColor" stroke-width="3" fill="none" opacity=".6"/>
                                    <circle cx="35" cy="13" r="2.5" fill="currentColor" opacity=".6"/>
                                </svg>
                            </div>
                            <p class="ses-consent-text">External content from Instagram</p>
                            <button type="button" class="ses-consent-btn btn">Load Content</button>
                        </div>
                        <template class="ses-embed-template">
                            <blockquote class="instagram-media"
                                data-instgrm-permalink="<?= e($url) ?>"
                                style="max-width:100%;min-width:280px;">
                                <a href="<?= e($url) ?>" target="_blank">View on Instagram</a>
                            </blockquote>
                        </template>
                    </div>
                <?php elseif ($provider === 'youtube_shorts' && $providerId !== ''): ?>
                    <!-- YouTube Shorts embed: consent-gated -->
                    <div class="ses-embed-wrap" data-ses-embed="pending">
                        <div class="ses-consent-placeholder">
                            <div class="ses-consent-icon">
                                <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                    <path d="M43 15.5a5.3 5.3 0 0 0-3.7-3.8C36 11 24 11 24 11s-12 0-15.3.7A5.3 5.3 0 0 0 5 15.5 55.6 55.6 0 0 0 4.3 24c0 2.9.2 5.7.7 8.5a5.3 5.3 0 0 0 3.7 3.8C12 37 24 37 24 37s12 0 15.3-.7a5.3 5.3 0 0 0 3.7-3.8c.5-2.8.7-5.6.7-8.5 0-2.9-.2-5.7-.7-8.5z" fill="currentColor" opacity=".6"/>
                                    <path d="M20 30.5V17.5l10 6.5-10 6.5z" fill="white"/>
                                </svg>
                            </div>
                            <p class="ses-consent-text">External content from YouTube</p>
                            <button type="button" class="ses-consent-btn btn">Load Content</button>
                        </div>
                        <template class="ses-embed-template">
                            <iframe
                                src="https://www.youtube-nocookie.com/embed/<?= e($providerId) ?>"
                                title="<?= e($itemTitle ?: 'YouTube Short') ?>"
                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                allowfullscreen
                                style="width:100%;aspect-ratio:9/16;border:0;border-radius:8px;">
                            </iframe>
                        </template>
                    </div>
                <?php else: ?>
                    <!-- Unknown provider: plain link -->
                    <div class="ses-embed-wrap ses-embed-wrap--fallback">
                        <a href="<?= e($url) ?>" target="_blank" rel="noopener noreferrer" class="ses-fallback-link">
                            View on <?= e(ucfirst($provider)) ?>
                        </a>
                    </div>
                <?php endif; ?>

                <?php if ($itemTitle !== '' || $itemDesc !== ''): ?>
                <div class="ses-item-meta">
                    <?php if ($itemTitle !== ''): ?>
                    <h3 class="ses-item-title"><?= e($itemTitle) ?></h3>
                    <?php endif; ?>
                    <?php if ($itemDesc !== ''): ?>
                    <p class="ses-item-description"><?= e($itemDesc) ?></p>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>

        <?php if ($ctaText !== '' && $ctaUrl !== ''): ?>
        <div class="ses-cta">
            <a href="<?= e($ctaUrl) ?>" class="btn" target="_blank" rel="noopener noreferrer"><?= e($ctaText) ?></a>
        </div>
        <?php endif; ?>
    </div>
</section>
