<?php
$page_title  = 'Media Slideshow';
$page_active = 'slideshow_settings';
require __DIR__ . '/includes/page_header.php';
?>

<div class="-mx-6 -mt-6 px-6 py-5 mb-6 border-b border-dark-700" style="background:#111;">
    <p class="text-xs font-semibold text-primary-400 uppercase tracking-wider mb-1">
        <span class="text-dark-400">Master Panel</span> / WebViews / Media Slideshow
    </p>
    <h2 class="text-2xl font-bold text-white flex items-center gap-3">
        <i class="ph ph-images text-primary-400"></i> Media Slideshow
    </h2>
</div>

<!-- Customize -->
<div class="card mb-6">
    <div class="card-head"><h3><i class="ph ph-monitor text-primary-400"></i> CUSTOMIZE WEBVIEW</h3></div>
    <div class="grid grid-cols-1 lg:grid-cols-[1fr_400px] gap-6 p-5">
        <div class="space-y-4">
            <div>
                <div class="flex items-center justify-between mb-2">
                    <label class="form-label text-xs">Slide Interval</label>
                    <span class="text-primary-400 text-sm font-semibold" id="interval-display">5000ms</span>
                </div>
                <input class="form-input" type="range" id="slide-interval" min="1000" max="20000" step="500" value="5000"
                       oninput="document.getElementById('interval-display').textContent=this.value+'ms'">
            </div>
            <div>
                <label class="form-label text-xs">Image Fit</label>
                <select class="form-input" id="slide-fit">
                    <option value="contain">Fit — whole image visible (may letterbox)</option>
                    <option value="cover">Fill — edge to edge (may crop)</option>
                </select>
                <p class="text-[11px] text-dark-500 mt-1">Portrait or square photos zoom-crop when Fill is on. Choose Fit for mixed aspect ratios.</p>
            </div>
            <div class="flex items-center gap-3">
                <button id="save-slide-interval" class="btn-primary"><i class="ph ph-floppy-disk"></i> Save</button>
                <a href="#" onclick="event.preventDefault(); openSlideFullscreen()" class="text-primary-400 text-sm hover:text-primary-300 flex items-center gap-1">
                    <i class="ph ph-arrows-out"></i> View Fullscreen
                </a>
            </div>
        </div>
        <div class="rounded-lg bg-black border border-dark-700 overflow-hidden" style="aspect-ratio:16/9;">
            <iframe id="slide-preview" src="api/webview/slideshow.php"
                    style="width:100%;height:100%;border:0;background:#000"></iframe>
        </div>
    </div>
</div>

<!-- Slideshow Images -->
<div class="card">
    <div class="card-head"><h3><i class="ph ph-images-square text-primary-400"></i> SLIDESHOW IMAGES</h3></div>
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 p-5">
        <div>
            <p class="text-sm font-semibold text-white mb-3">Upload Media</p>
            <div class="rounded-lg border-2 border-dashed border-dark-600 p-8 text-center hover:border-primary-500 transition-colors cursor-pointer"
                 onclick="document.getElementById('slideshow-file-input').click()">
                <button type="button" class="btn-primary mb-3"><i class="ph ph-plus"></i> Add images…</button>
                <p class="text-xs text-dark-400">Accepted: JPEG, PNG, GIF, WebP</p>
                <input type="file" id="slideshow-file-input" multiple accept="image/*" class="hidden">
            </div>
        </div>
        <div>
            <p class="text-sm font-semibold text-white mb-3">Current Images</p>
            <div id="slideshow-list" class="text-sm text-dark-500 p-4 border border-dark-700 rounded-lg text-center">
                No images added yet.
            </div>
        </div>
    </div>
</div>

<script>
function refreshSlidePreview() {
    const f = document.getElementById('slide-preview');
    if (!f) return;
    f.src = 'api/webview/slideshow.php?v=' + Date.now();
}

async function loadSlides() {
    try {
        const r = await api.get('api/webview/slideshows.php?action=list');
        document.getElementById('interval-display').textContent = (r.slide_interval_ms || 5000) + 'ms';
        document.getElementById('slide-interval').value = r.slide_interval_ms || 5000;
        document.getElementById('slide-fit').value = (r.slide_fit_mode === 'cover') ? 'cover' : 'contain';
        const host = document.getElementById('slideshow-list');
        const imgs = r.images || [];
        if (!imgs.length) { host.innerHTML = 'No images added yet.'; return; }
        host.innerHTML = '<div class="grid grid-cols-2 sm:grid-cols-3 gap-3">' + imgs.map(im => `
            <div class="relative group rounded-lg overflow-hidden border border-dark-700 bg-dark-900">
                <img src="${escapeHtml(im.image_url)}" alt="" class="w-full h-24 object-cover" loading="lazy">
                <button class="absolute top-1 right-1 bg-red-500/90 text-white rounded-full w-6 h-6 flex items-center justify-center text-xs opacity-0 group-hover:opacity-100"
                        onclick="deleteSlide(${im.id})"><i class="ph ph-trash"></i></button>
            </div>`).join('') + '</div>';
    } catch (e) { toast(e.message, 'error'); }
}
async function deleteSlide(id) {
    if (!(await confirmDanger('Delete this slide?'))) return;
    try { await api.post('api/webview/slideshows.php', { action: 'delete', id }); toast('Deleted', 'success'); loadSlides(); refreshSlidePreview(); }
    catch (e) { toast(e.message, 'error'); }
}
document.getElementById('slideshow-file-input').addEventListener('change', async (e) => {
    const files = Array.from(e.target.files);
    if (!files.length) return;
    let ok = 0, fail = 0;
    for (const f of files) {
        const fd = new FormData();
        fd.append('action', 'upload');
        fd.append('file', f);
        try {
            const r = await fetch('api/webview/slideshows.php', {
                method: 'POST', credentials: 'same-origin',
                headers: { 'X-CSRF-Token': document.querySelector('meta[name=csrf-token]').content,
                           'X-Requested-With': 'XMLHttpRequest' },
                body: fd,
            });
            const out = await r.json();
            if (out.ok) ok++; else { fail++; console.warn('slide upload failed:', out); }
        } catch (_) { fail++; }
    }
    toast(`Uploaded ${ok} image${ok===1?'':'s'}${fail ? ` (${fail} failed)` : ''}`, fail ? 'warn' : 'success');
    e.target.value = '';
    loadSlides();
    refreshSlidePreview();
});

document.getElementById('save-slide-interval').addEventListener('click', async () => {
    const ms  = parseInt(document.getElementById('slide-interval').value, 10) || 5000;
    const fit = document.getElementById('slide-fit').value;
    try {
        await api.post('api/webview/slideshows.php', { action: 'set_interval', ms });
        await api.post('api/webview/slideshows.php', { action: 'set_fit_mode', fit });
        toast('Slideshow settings saved', 'success');
        refreshSlidePreview();
    } catch (err) { toast(err.message, 'error'); }
});

document.getElementById('slide-fit').addEventListener('change', () => refreshSlidePreview());

function openSlideFullscreen() { wvFullscreen('api/webview/slideshow.php'); }

loadSlides();
</script>

<?php require __DIR__ . '/includes/page_footer.php'; ?>
