<?php
// =============================================================================
// /api/webview/slideshow.php — fade-rotation slideshow served to the WebView.
// =============================================================================
require_once __DIR__ . '/_wv_common.php';

$default_ms = (int)(db_one('SELECT value FROM webview_settings WHERE key=?', ['slide_interval_ms'])['value'] ?? 5000);
if ($default_ms < 1000) $default_ms = 5000;
// Fit mode — `contain` (default: whole image visible, letterboxed) or
// `cover` (edge-to-edge, may crop). Operator can flip via slideshow_settings.
$fit_row = db_one('SELECT value FROM webview_settings WHERE key=?', ['slide_fit_mode']);
$fit     = in_array($fit_row['value'] ?? '', ['cover','contain'], true) ? $fit_row['value'] : 'contain';
$slides  = db_all('SELECT image_url, duration_ms FROM webview_slideshows WHERE enabled=1 ORDER BY sort ASC, id ASC');

wv_html_head('Slideshow', '<style>
html,body{overflow:hidden}
.stage{position:fixed;inset:0;background:#000}
.slide{position:absolute;inset:0;background:#000 center/' . $fit . ' no-repeat;opacity:0;transition:opacity .8s ease;}
.slide.on{opacity:1}
.empty{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:#666;font-size:14px;}
</style>');
?>
<div class="stage" id="stage">
    <?php foreach ($slides as $i => $s): ?>
        <div class="slide<?php echo $i === 0 ? ' on' : ''; ?>"
             data-duration="<?php echo (int)($s['duration_ms'] ?: $default_ms); ?>"
             style="background-image:url('<?php echo htmlspecialchars($s['image_url'], ENT_QUOTES, 'UTF-8'); ?>')"></div>
    <?php endforeach; ?>
    <?php if (!$slides): ?><div class="empty">Nothing to show right now.</div><?php endif; ?>
</div>
<script>
(function () {
    var slides = document.querySelectorAll('.slide');
    if (!slides.length) return;
    var i = 0;
    function step() {
        slides[i].classList.remove('on');
        i = (i + 1) % slides.length;
        slides[i].classList.add('on');
        setTimeout(step, parseInt(slides[i].dataset.duration || '5000', 10));
    }
    setTimeout(step, parseInt(slides[0].dataset.duration || '5000', 10));
})();
</script>
<?php wv_html_foot();
