<?php
// =============================================================================
// /api/webview/tmdb/autoads_0.php — TMDB content rotation with ad slot.
// Pulls from TMDB v3 with the API key stored in webview_settings.tmdb_api_key.
//
// Admin live-preview mode: pass ?preview=1 plus any of the override params
// below, and the renderer will use those instead of the persisted webview_settings:
//     style          one of: banner | grid | carousel | hero
//     slide_ms       milliseconds between slides
//     accent         hex color (#f39c12)
//     show_title|show_year|show_genre|show_vote|show_overview   '0' or '1'
// =============================================================================
require_once __DIR__ . '/../_wv_common.php';

$is_preview = !empty($_GET['preview']);
$key        = (string)(db_one('SELECT value FROM webview_settings WHERE key=?', ['tmdb_api_key'])['value'] ?? '');
$feed       = (string)(db_one('SELECT value FROM webview_settings WHERE key=?', ['feed_type'])['value'] ?? 'trending_week');
$region     = (string)(db_one('SELECT value FROM webview_settings WHERE key=?', ['region'])['value'] ?? 'US');
$lang       = (string)(db_one('SELECT value FROM webview_settings WHERE key=?', ['metadata_language'])['value'] ?? 'en-US');

// Content filters surfaced on tmdb_settings.php — wired through to the result
// list so the toggles actually do something. cert_cap isn't wired here because
// /trending/* doesn't carry certification data and per-item release_dates calls
// would N+1 the upstream API; surface that the UI as "TMDB-side" if needed.
$block_adult   = (string)(db_one('SELECT value FROM webview_settings WHERE key=?', ['block_adult'])['value']     ?? '1') === '1';
$min_votes     = (int)   (db_one('SELECT value FROM webview_settings WHERE key=?', ['min_vote_count'])['value']  ?? 0);
$block_list_raw= (string)(db_one('SELECT value FROM webview_settings WHERE key=?', ['block_list'])['value']      ?? '');
$audio_langs   = (string)(db_one('SELECT value FROM webview_settings WHERE key=?', ['original_audio_languages'])['value'] ?? '');

$block_terms = array_values(array_filter(array_map('trim',
    preg_split('/\R/', $block_list_raw))));
$audio_set   = array_values(array_filter(array_map(function ($v) {
    return strtolower(trim($v));
}, explode(',', $audio_langs))));

// Resolve layout settings (DB → optional GET overrides when previewing)
$layout = [
    'style'         => (string)(db_one('SELECT value FROM webview_settings WHERE key=?', ['tmdb_layout_style'])['value']         ?? 'banner') ?: 'banner',
    'slide_ms'      => (int)   (db_one('SELECT value FROM webview_settings WHERE key=?', ['tmdb_layout_slide_ms'])['value']      ?? 6000),
    'accent'        => (string)(db_one('SELECT value FROM webview_settings WHERE key=?', ['tmdb_layout_accent'])['value']        ?? '#f9a825') ?: '#f9a825',
    'show_title'    =>  ((db_one('SELECT value FROM webview_settings WHERE key=?', ['tmdb_layout_show_title'])['value']    ?? '1') === '1'),
    'show_year'     =>  ((db_one('SELECT value FROM webview_settings WHERE key=?', ['tmdb_layout_show_year'])['value']     ?? '1') === '1'),
    'show_genre'    =>  ((db_one('SELECT value FROM webview_settings WHERE key=?', ['tmdb_layout_show_genre'])['value']    ?? '0') === '1'),
    'show_vote'     =>  ((db_one('SELECT value FROM webview_settings WHERE key=?', ['tmdb_layout_show_vote'])['value']     ?? '1') === '1'),
    'show_overview' =>  ((db_one('SELECT value FROM webview_settings WHERE key=?', ['tmdb_layout_show_overview'])['value'] ?? '1') === '1'),
];
if ($is_preview) {
    if (isset($_GET['style']))         { $layout['style']    = preg_match('/^(banner|grid|carousel|hero)$/', $_GET['style']) ? $_GET['style'] : $layout['style']; }
    if (isset($_GET['slide_ms']))      { $layout['slide_ms'] = max(1500, min(60000, (int)$_GET['slide_ms'])); }
    if (isset($_GET['accent']))        { $layout['accent']   = preg_match('/^#[0-9a-fA-F]{6}$/', $_GET['accent']) ? $_GET['accent'] : $layout['accent']; }
    foreach (['show_title','show_year','show_genre','show_vote','show_overview'] as $k) {
        if (isset($_GET[$k])) $layout[$k] = $_GET[$k] === '1';
    }
}

// Map feed_type → TMDB endpoint
$endpoint = '/trending/all/week';
if ($feed === 'trending_day') $endpoint = '/trending/all/day';
elseif ($feed === 'popular')   $endpoint = '/movie/popular';
elseif ($feed === 'top_rated') $endpoint = '/movie/top_rated';
elseif ($feed === 'now_playing') $endpoint = '/movie/now_playing';

$items = [];
$err = null;
if ($key === '') {
    $err = 'Movie spotlight is not available right now.';
} else {
    require_once __DIR__ . '/../../../includes/sports/provider_interface.php';
    $cached = sports_cache_get('tmdb', $endpoint . '|' . $region . '|' . $lang, 1800);
    $payload = $cached;
    if ($payload === null) {
        $url = 'https://api.themoviedb.org/3' . $endpoint .
               '?api_key=' . urlencode($key) . '&language=' . urlencode($lang) . '&region=' . urlencode($region);
        $raw = sports_http_get($url);
        if ($raw !== null) {
            $payload = json_decode($raw, true);
            if (is_array($payload)) sports_cache_set('tmdb', $endpoint . '|' . $region . '|' . $lang, $payload);
        }
    }
    if (is_array($payload)) {
        foreach (($payload['results'] ?? []) as $r) {
            // ---- Content filters ----
            if ($block_adult && !empty($r['adult'])) continue;
            if ($min_votes > 0 && (int)($r['vote_count'] ?? 0) < $min_votes) continue;
            if ($audio_set) {
                $orig = strtolower((string)($r['original_language'] ?? ''));
                if ($orig !== '' && !in_array($orig, $audio_set, true)) continue;
            }
            $title_for_match     = strtolower((string)($r['title'] ?? $r['name'] ?? ''));
            $original_for_match  = strtolower((string)($r['original_title'] ?? $r['original_name'] ?? ''));
            $blocked = false;
            foreach ($block_terms as $term) {
                $needle = strtolower($term);
                if ($needle === '') continue;
                if (strpos($title_for_match, $needle) !== false
                    || strpos($original_for_match, $needle) !== false) {
                    $blocked = true; break;
                }
            }
            if ($blocked) continue;
            // ---- end filters ----
            $items[] = [
                'title'    => (string)($r['title'] ?? $r['name'] ?? 'Untitled'),
                'overview' => (string)($r['overview'] ?? ''),
                'backdrop' => $r['backdrop_path'] ? ('https://image.tmdb.org/t/p/w1280' . $r['backdrop_path']) : '',
                'poster'   => $r['poster_path']   ? ('https://image.tmdb.org/t/p/w342'  . $r['poster_path'])   : '',
                'vote'     => (float)($r['vote_average'] ?? 0),
                'year'     => substr((string)($r['release_date'] ?? $r['first_air_date'] ?? ''), 0, 4),
            ];
        }
    } else {
        $err = 'Movie spotlight is not available right now.';
    }
}

$accent = $layout['accent'];
$style  = $layout['style'];
wv_html_head('TMDB', '<style>
:root { --accent: ' . htmlspecialchars($accent, ENT_QUOTES) . '; }
html,body{overflow:hidden;background:#000;color:#fff}
.stage{position:fixed;inset:0;background:#000}
.empty{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:#666;font-size:14px;padding:20px;text-align:center;}

/* ---- BANNER (default) ---- */
.banner .slide{position:absolute;inset:0;background:#000 center/cover no-repeat;opacity:0;transition:opacity 1s ease;}
.banner .slide.on{opacity:1}
.banner .tint{position:absolute;inset:0;background:linear-gradient(180deg,transparent 30%,rgba(0,0,0,.85) 100%);}
.banner .info{position:absolute;left:5%;right:5%;bottom:8%;}
.banner .title{font-size:42px;font-weight:900;line-height:1.05;letter-spacing:-.02em;}
.banner .meta{display:flex;align-items:center;gap:10px;margin-top:8px;color:#ccc;font-size:13px;font-weight:600}
.banner .meta .v{color:var(--accent);}
.banner .overview{margin-top:10px;color:#bbb;font-size:13px;max-width:780px;line-height:1.5;}

/* ---- GRID ---- */
.grid-wrap{position:absolute;inset:0;display:grid;grid-template-columns:repeat(4,1fr);grid-auto-rows:1fr;gap:10px;padding:14px;}
.grid-card{position:relative;border-radius:10px;overflow:hidden;background:#0a0a0a center/cover no-repeat;box-shadow:0 4px 16px rgba(0,0,0,.6);}
.grid-card .tint{position:absolute;inset:0;background:linear-gradient(180deg,transparent 50%,rgba(0,0,0,.92) 100%);}
.grid-card .info{position:absolute;left:8px;right:8px;bottom:6px;}
.grid-card .title{font-size:12px;font-weight:700;line-height:1.1;}
.grid-card .meta{display:flex;gap:6px;color:var(--accent);font-size:10px;font-weight:700;margin-top:2px;}

/* ---- CAROUSEL ---- */
.carousel{position:absolute;inset:0;display:flex;flex-direction:column;}
.carousel .hero{flex:1;position:relative;background:#000 center/cover no-repeat;}
.carousel .hero .tint{position:absolute;inset:0;background:linear-gradient(180deg,transparent 30%,rgba(0,0,0,.85) 100%);}
.carousel .hero .info{position:absolute;left:5%;right:5%;bottom:15%;}
.carousel .hero .title{font-size:38px;font-weight:900;letter-spacing:-.02em;}
.carousel .hero .meta{display:flex;gap:10px;margin-top:6px;color:#ccc;font-size:13px;font-weight:600;}
.carousel .hero .meta .v{color:var(--accent);}
.carousel .hero .overview{margin-top:8px;color:#bbb;font-size:13px;max-width:780px;line-height:1.5;}
.carousel .strip{height:140px;flex-shrink:0;display:flex;gap:8px;padding:10px 14px;overflow-x:auto;background:#0a0a0a;}
.carousel .strip::-webkit-scrollbar{height:6px}
.carousel .strip::-webkit-scrollbar-thumb{background:#2a2a2a;border-radius:3px}
.carousel .strip .poster{flex:0 0 80px;height:120px;border-radius:6px;background:#1a1a1a center/cover no-repeat;cursor:pointer;border:2px solid transparent;transition:border-color .2s;}
.carousel .strip .poster.on{border-color:var(--accent);}

/* ---- HERO ---- */
.hero-wrap{position:absolute;inset:0;display:flex;}
.hero-wrap .featured{flex:2;position:relative;background:#000 center/cover no-repeat;}
.hero-wrap .featured .tint{position:absolute;inset:0;background:linear-gradient(90deg,rgba(0,0,0,.85) 0%,transparent 60%);}
.hero-wrap .featured .info{position:absolute;left:5%;top:50%;transform:translateY(-50%);max-width:60%;}
.hero-wrap .featured .title{font-size:48px;font-weight:900;letter-spacing:-.02em;line-height:1;}
.hero-wrap .featured .meta{display:flex;gap:12px;margin-top:8px;color:#ccc;font-size:14px;font-weight:600;}
.hero-wrap .featured .meta .v{color:var(--accent);}
.hero-wrap .featured .overview{margin-top:12px;color:#bbb;font-size:14px;line-height:1.5;}
.hero-wrap .list{flex:1;display:flex;flex-direction:column;gap:6px;padding:14px;overflow-y:auto;background:#080808;}
.hero-wrap .list .row{display:flex;align-items:center;gap:10px;padding:6px;border-radius:6px;cursor:pointer;}
.hero-wrap .list .row:hover{background:rgba(255,255,255,.04);}
.hero-wrap .list .row.on{background:rgba(243,156,18,.10);}
.hero-wrap .list .thumb{width:42px;height:62px;border-radius:4px;background:#1a1a1a center/cover no-repeat;flex-shrink:0;}
.hero-wrap .list .meta-row .title{font-size:13px;font-weight:600;color:#fff;line-height:1.2;}
.hero-wrap .list .meta-row .meta{font-size:11px;color:var(--accent);font-weight:700;}
</style>');
?>
<div class="stage" id="stage">
<?php if (!$items): ?>
    <div class="empty"><?php echo htmlspecialchars($err ?? 'Nothing to show right now.', ENT_QUOTES, 'UTF-8'); ?></div>

<?php elseif ($style === 'grid'): ?>
    <div class="grid-wrap">
    <?php foreach (array_slice($items, 0, 16) as $it): ?>
        <div class="grid-card" style="background-image:url('<?php echo htmlspecialchars($it['poster'] ?: $it['backdrop'], ENT_QUOTES, 'UTF-8'); ?>')">
            <div class="tint"></div>
            <div class="info">
                <?php if ($layout['show_title']): ?>
                <div class="title"><?php echo htmlspecialchars($it['title'], ENT_QUOTES, 'UTF-8'); ?></div>
                <?php endif; ?>
                <div class="meta">
                    <?php if ($layout['show_year']  && $it['year']): ?><span><?php echo $it['year']; ?></span><?php endif; ?>
                    <?php if ($layout['show_vote']  && $it['vote']): ?><span>★ <?php echo number_format($it['vote'], 1); ?></span><?php endif; ?>
                </div>
            </div>
        </div>
    <?php endforeach; ?>
    </div>

<?php elseif ($style === 'carousel'): ?>
    <div class="carousel">
        <div class="hero" id="car-hero" style="background-image:url('<?php echo htmlspecialchars($items[0]['backdrop'] ?: $items[0]['poster'], ENT_QUOTES, 'UTF-8'); ?>')">
            <div class="tint"></div>
            <div class="info">
                <?php if ($layout['show_title']): ?>
                <div class="title" id="car-title"><?php echo htmlspecialchars($items[0]['title'], ENT_QUOTES, 'UTF-8'); ?></div>
                <?php endif; ?>
                <div class="meta">
                    <?php if ($layout['show_year']  && $items[0]['year']): ?><span id="car-year"><?php echo $items[0]['year']; ?></span><?php endif; ?>
                    <?php if ($layout['show_vote']  && $items[0]['vote']): ?><span class="v" id="car-vote">★ <?php echo number_format($items[0]['vote'], 1); ?></span><?php endif; ?>
                </div>
                <?php if ($layout['show_overview']): ?>
                <div class="overview" id="car-overview"><?php echo htmlspecialchars(substr($items[0]['overview'], 0, 240), ENT_QUOTES, 'UTF-8'); ?></div>
                <?php endif; ?>
            </div>
        </div>
        <div class="strip" id="car-strip">
        <?php foreach ($items as $i => $it): ?>
            <div class="poster<?php echo $i === 0 ? ' on' : ''; ?>" data-idx="<?php echo $i; ?>"
                 style="background-image:url('<?php echo htmlspecialchars($it['poster'] ?: $it['backdrop'], ENT_QUOTES, 'UTF-8'); ?>')"></div>
        <?php endforeach; ?>
        </div>
    </div>

<?php elseif ($style === 'hero'): ?>
    <div class="hero-wrap">
        <div class="featured" id="hero-featured" style="background-image:url('<?php echo htmlspecialchars($items[0]['backdrop'] ?: $items[0]['poster'], ENT_QUOTES, 'UTF-8'); ?>')">
            <div class="tint"></div>
            <div class="info">
                <?php if ($layout['show_title']): ?>
                <div class="title" id="hero-title"><?php echo htmlspecialchars($items[0]['title'], ENT_QUOTES, 'UTF-8'); ?></div>
                <?php endif; ?>
                <div class="meta">
                    <?php if ($layout['show_year']  && $items[0]['year']): ?><span id="hero-year"><?php echo $items[0]['year']; ?></span><?php endif; ?>
                    <?php if ($layout['show_vote']  && $items[0]['vote']): ?><span class="v" id="hero-vote">★ <?php echo number_format($items[0]['vote'], 1); ?></span><?php endif; ?>
                </div>
                <?php if ($layout['show_overview']): ?>
                <div class="overview" id="hero-overview"><?php echo htmlspecialchars(substr($items[0]['overview'], 0, 320), ENT_QUOTES, 'UTF-8'); ?></div>
                <?php endif; ?>
            </div>
        </div>
        <div class="list" id="hero-list">
        <?php foreach (array_slice($items, 0, 10) as $i => $it): ?>
            <div class="row<?php echo $i === 0 ? ' on' : ''; ?>" data-idx="<?php echo $i; ?>">
                <div class="thumb" style="background-image:url('<?php echo htmlspecialchars($it['poster'] ?: $it['backdrop'], ENT_QUOTES, 'UTF-8'); ?>')"></div>
                <div class="meta-row">
                    <div class="title"><?php echo htmlspecialchars($it['title'], ENT_QUOTES, 'UTF-8'); ?></div>
                    <div class="meta">
                        <?php if ($layout['show_year']  && $it['year']): ?><?php echo $it['year']; ?> · <?php endif; ?>
                        <?php if ($layout['show_vote']  && $it['vote']): ?>★ <?php echo number_format($it['vote'], 1); ?><?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
        </div>
    </div>

<?php else: /* banner */ ?>
    <div class="banner">
    <?php foreach ($items as $i => $it): ?>
        <div class="slide<?php echo $i === 0 ? ' on' : ''; ?>" style="background-image:url('<?php echo htmlspecialchars($it['backdrop'] ?: $it['poster'], ENT_QUOTES, 'UTF-8'); ?>')">
            <div class="tint"></div>
            <div class="info">
                <?php if ($layout['show_title']): ?>
                <div class="title"><?php echo htmlspecialchars($it['title'], ENT_QUOTES, 'UTF-8'); ?></div>
                <?php endif; ?>
                <div class="meta">
                    <?php if ($layout['show_year']  && $it['year']): ?><span><?php echo $it['year']; ?></span><?php endif; ?>
                    <?php if ($layout['show_vote']  && $it['vote']): ?><span class="v">★ <?php echo number_format($it['vote'], 1); ?></span><?php endif; ?>
                </div>
                <?php if ($layout['show_overview']): ?>
                <div class="overview"><?php echo htmlspecialchars(substr($it['overview'], 0, 240), ENT_QUOTES, 'UTF-8'); ?><?php echo strlen($it['overview']) > 240 ? '…' : ''; ?></div>
                <?php endif; ?>
            </div>
        </div>
    <?php endforeach; ?>
    </div>
<?php endif; ?>
</div>

<?php if ($items): ?>
<script>
(function () {
    var STYLE  = <?php echo json_encode($style); ?>;
    var SLIDE_MS = <?php echo (int)$layout['slide_ms']; ?>;
    var ITEMS = <?php echo json_encode(array_map(function($it){
        return ['t'=>$it['title'],'y'=>$it['year'],'v'=>$it['vote'],'o'=>substr($it['overview'],0,320),'bg'=>$it['backdrop'] ?: $it['poster']];
    }, $items)); ?>;

    if (STYLE === 'banner') {
        var slides = document.querySelectorAll('.banner .slide');
        if (slides.length < 2) return;
        var i = 0;
        setInterval(function () {
            slides[i].classList.remove('on');
            i = (i + 1) % slides.length;
            slides[i].classList.add('on');
        }, SLIDE_MS);
    } else if (STYLE === 'carousel') {
        var hero = document.getElementById('car-hero');
        var posters = document.querySelectorAll('#car-strip .poster');
        var i = 0;
        function go(idx) {
            posters.forEach(p => p.classList.remove('on'));
            posters[idx] && posters[idx].classList.add('on');
            var d = ITEMS[idx]; if (!d) return;
            hero.style.backgroundImage = "url('" + d.bg + "')";
            var t = document.getElementById('car-title');     if (t) t.textContent = d.t;
            var y = document.getElementById('car-year');      if (y && d.y) y.textContent = d.y;
            var v = document.getElementById('car-vote');      if (v && d.v) v.textContent = '★ ' + d.v.toFixed(1);
            var o = document.getElementById('car-overview');  if (o) o.textContent = d.o;
        }
        posters.forEach(p => p.addEventListener('click', () => go(+p.dataset.idx)));
        setInterval(() => { i = (i+1) % ITEMS.length; go(i); }, SLIDE_MS);
    } else if (STYLE === 'hero') {
        var featured = document.getElementById('hero-featured');
        var rows = document.querySelectorAll('#hero-list .row');
        var i = 0;
        function go(idx) {
            rows.forEach(r => r.classList.remove('on'));
            rows[idx] && rows[idx].classList.add('on');
            var d = ITEMS[idx]; if (!d) return;
            featured.style.backgroundImage = "url('" + d.bg + "')";
            var t = document.getElementById('hero-title');    if (t) t.textContent = d.t;
            var y = document.getElementById('hero-year');     if (y && d.y) y.textContent = d.y;
            var v = document.getElementById('hero-vote');     if (v && d.v) v.textContent = '★ ' + d.v.toFixed(1);
            var o = document.getElementById('hero-overview'); if (o) o.textContent = d.o;
        }
        rows.forEach(r => r.addEventListener('click', () => go(+r.dataset.idx)));
        setInterval(() => { i = (i+1) % Math.min(ITEMS.length, rows.length); go(i); }, SLIDE_MS);
    }
})();
</script>
<?php endif; ?>
<?php wv_html_foot();
