<?php
$page_title  = 'Services & Clients';
$page_active = 'services_clients';
require __DIR__ . '/includes/page_header.php';
?>

<!-- Header band (IBO GLASS style) -->
<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> / IBO ULTRA / Services &amp; Clients
    </p>
    <h2 class="text-2xl font-bold text-white flex items-center gap-3">
        <i class="ph ph-storefront text-primary-400"></i> Services &amp; Clients
    </h2>
</div>

<div class="card" x-data="{ tab: 'services' }">
    <!-- Tab nav -->
    <div class="border-b border-dark-700 flex items-center gap-1 px-4">
        <button @click="tab='services'" :class="tab==='services' ? 'tab-active' : ''" class="tab-btn">
            <i class="ph ph-globe text-base"></i> Services
            <span class="tab-badge" id="sc-count-services">0</span>
        </button>
        <button @click="tab='users'" :class="tab==='users' ? 'tab-active' : ''" class="tab-btn">
            <i class="ph ph-user-list text-base"></i> Users / Playlists
            <span class="tab-badge" id="sc-count-users">0</span>
        </button>
        <button @click="tab='trials'" :class="tab==='trials' ? 'tab-active' : ''" class="tab-btn">
            <i class="ph ph-hourglass text-base"></i> Trials / Expiry
            <span class="tab-badge" id="sc-count-trials">0</span>
        </button>
    </div>

    <!-- ================ Services tab (portals) ================ -->
    <div x-show="tab==='services'" x-cloak>
        <div class="flex items-center justify-between p-5 border-b border-dark-700">
            <div class="flex items-center gap-2 text-sm text-dark-300">
                <i class="ph ph-globe text-primary-400"></i>
                Manage portals available to your IBO Ultra users.
            </div>
            <div class="flex gap-2">
                <button onclick="openModal('portal-modal-new')" class="btn-primary text-xs">
                    <i class="ph ph-plus"></i> Add Portal
                </button>
                <button onclick="deleteAllPortals()" class="btn-danger text-xs">
                    <i class="ph ph-trash"></i> Delete All
                </button>
            </div>
        </div>
        <div class="flex items-center justify-between px-5 py-3 border-b border-dark-700 bg-dark-900/50">
            <div class="search">
                <i class="ph ph-magnifying-glass"></i>
                <input type="text" id="portal-search" placeholder="Search name or URL…">
            </div>
            <span id="portal-meta" class="text-xs text-dark-400">0 portals</span>
        </div>
        <div class="overflow-x-auto">
            <table class="compact">
                <thead>
                    <tr>
                        <th class="w-10"><input type="checkbox" class="row-check-all" data-target="portal-rows"></th>
                        <th>Name</th>
                        <th>URL</th>
                        <th class="text-right">Actions</th>
                    </tr>
                </thead>
                <tbody id="portal-rows">
                    <tr><td colspan="4" class="text-center text-xs text-dark-500 py-8">Loading…</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- ================ Users / Playlists tab (devices + playlists) ================ -->
    <div x-show="tab==='users'" x-cloak>
        <div class="flex flex-wrap items-center justify-between p-5 gap-3 border-b border-dark-700">
            <div class="flex flex-wrap items-center gap-2">
                <span class="stat-chip"><i class="ph ph-device-mobile"></i> MACs <span id="up-stat-macs" class="font-bold ml-1">0</span></span>
                <span class="stat-chip"><i class="ph ph-playlist"></i> Playlists <span id="up-stat-playlists" class="font-bold ml-1">0</span></span>
                <span class="stat-chip"><i class="ph ph-divide"></i> Avg / MAC <span id="up-stat-avg" class="font-bold ml-1">0</span></span>
            </div>
            <div class="flex gap-2">
                <a href="api/backup.php?action=download" class="btn-outline text-xs">
                    <i class="ph ph-download-simple"></i> Backup
                </a>
                <button onclick="document.getElementById('sc-restore-file').click()" class="btn-outline text-xs">
                    <i class="ph ph-upload-simple"></i> Restore
                </button>
                <input type="file" id="sc-restore-file" accept=".zip" class="hidden">
                <button onclick="openModal('device-modal-new')" class="btn-primary text-xs">
                    <i class="ph ph-plus"></i> Add Device
                </button>
            </div>
        </div>
        <div class="flex items-center justify-between px-5 py-3 border-b border-dark-700 bg-dark-900/50">
            <div class="flex items-center gap-2">
                <div class="search">
                    <i class="ph ph-magnifying-glass"></i>
                    <input type="text" id="up-search" placeholder="Search MAC, user, title…">
                </div>
                <select id="up-page-size" class="form-input text-xs" style="width:auto;">
                    <option value="50">50 / page</option>
                    <option value="100">100 / page</option>
                    <option value="200">200 / page</option>
                </select>
                <button onclick="findDuplicateMacs()" class="btn-secondary text-xs">
                    <i class="ph ph-magnifying-glass-plus"></i> Find Duplicates <span id="up-dup-count" class="badge ml-1">0</span>
                </button>
            </div>
        </div>
        <div class="overflow-x-auto">
            <table class="compact">
                <thead>
                    <tr>
                        <th class="w-10"><input type="checkbox" class="row-check-all" data-target="up-rows"></th>
                        <th>MAC</th>
                        <th>Title</th>
                        <th>Username</th>
                        <th>Portal URL</th>
                        <th>Type</th>
                        <th>Expiry</th>
                        <th class="text-right">Actions</th>
                    </tr>
                </thead>
                <tbody id="up-rows">
                    <tr><td colspan="8" class="text-center text-xs text-dark-500 py-8">Loading…</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- ================ Trials / Expiry tab ================ -->
    <div x-show="tab==='trials'" x-cloak>
        <div class="flex items-center justify-between p-5 border-b border-dark-700">
            <div class="flex items-center gap-2 text-sm text-dark-300">
                <i class="ph ph-clock text-primary-400"></i>
                Set a trial expiry date for a specific device.
            </div>
            <button onclick="openModal('trial-modal-new')" class="btn-primary text-xs">
                <i class="ph ph-plus"></i> Set Expiry
            </button>
        </div>
        <div class="overflow-x-auto">
            <table class="compact">
                <thead>
                    <tr>
                        <th class="w-10"><input type="checkbox" class="row-check-all" data-target="trial-rows"></th>
                        <th>MAC</th>
                        <th>Expiry</th>
                        <th>Status</th>
                        <th class="text-right">Actions</th>
                    </tr>
                </thead>
                <tbody id="trial-rows">
                    <tr>
                        <td colspan="5" class="py-16">
                            <div class="flex flex-col items-center justify-center text-dark-500 text-sm">
                                <i class="ph ph-clock text-4xl mb-2 opacity-50"></i>
                                <p>No trials set. Click <strong>Set Expiry</strong> to add one for a specific device.</p>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- ============================ MODALS ============================ -->

<!-- Add Portal modal -->
<div id="portal-modal-new" class="panel-modal" style="display:none">
    <div class="panel-modal-card">
        <div class="panel-modal-head">
            <h3><i class="ph ph-plus-circle text-primary-400 mr-1"></i> Add Portal</h3>
            <button onclick="closeModal('portal-modal-new')" class="icon-btn"><i class="ph ph-x"></i></button>
        </div>
        <form id="portal-form-new" class="panel-modal-body space-y-3">
            <div><label class="form-label text-xs">Name</label>
                 <input class="form-input" name="name" placeholder="Portal name" required></div>
            <div><label class="form-label text-xs">URL</label>
                 <input class="form-input mono" name="url" placeholder="http://example.tv:8080/" required></div>
            <div class="grid grid-cols-2 gap-3">
                <div><label class="form-label text-xs">Type</label>
                     <select class="form-input" name="type">
                         <option value="xtream">Xtream</option>
                         <option value="m3u">M3U</option>
                         <option value="stalker">Stalker</option>
                     </select></div>
                <div><label class="form-label text-xs">Sort order</label>
                     <input class="form-input" name="sort_order" type="number" value="0"></div>
            </div>
            <label class="flex items-center gap-2 text-xs text-dark-200">
                <input type="checkbox" name="enabled" value="1" checked
                       class="rounded border-dark-500 text-primary-500 focus:ring-primary-500 bg-dark-700">
                Enabled
            </label>
            <div class="flex justify-end gap-2 pt-2">
                <button type="button" onclick="closeModal('portal-modal-new')" class="px-4 py-2 text-xs text-dark-400 hover:text-dark-200">Cancel</button>
                <button type="submit" class="btn-primary text-xs"><i class="ph ph-floppy-disk"></i> Create</button>
            </div>
        </form>
    </div>
</div>

<!-- Add Device modal -->
<div id="device-modal-new" class="panel-modal" style="display:none">
    <div class="panel-modal-card">
        <div class="panel-modal-head">
            <h3><i class="ph ph-plus-circle text-primary-400 mr-1"></i> Add Device</h3>
            <button onclick="closeModal('device-modal-new')" class="icon-btn"><i class="ph ph-x"></i></button>
        </div>
        <form id="device-form-new" class="panel-modal-body space-y-3">
            <div><label class="form-label text-xs">MAC address</label>
                 <input class="form-input" name="mac_address" placeholder="df:61:22:45:5d:1e" required></div>
            <div class="grid grid-cols-2 gap-3">
                <div><label class="form-label text-xs">Device type</label>
                     <select class="form-input" name="app_type">
                         <option value="phone">Phone</option>
                         <option value="tv">TV</option>
                         <option value="tablet">Tablet</option>
                     </select></div>
                <div><label class="form-label text-xs">App version</label>
                     <input class="form-input" name="app_version" value="4.3"></div>
            </div>
            <p class="text-xs text-dark-500">A unique device ID is created automatically.</p>
            <div class="flex justify-end gap-2 pt-2">
                <button type="button" onclick="closeModal('device-modal-new')" class="px-4 py-2 text-xs text-dark-400 hover:text-dark-200">Cancel</button>
                <button type="submit" class="btn-primary text-xs"><i class="ph ph-floppy-disk"></i> Create</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Playlist modal (opened by the row's Edit button) -->
<div id="up-edit-modal" class="panel-modal" style="display:none">
    <div class="panel-modal-card">
        <div class="panel-modal-head">
            <h3><i class="ph ph-pencil-simple text-primary-400 mr-1"></i> Edit playlist</h3>
            <button onclick="closeModal('up-edit-modal')" class="icon-btn"><i class="ph ph-x"></i></button>
        </div>
        <form id="up-edit-form" class="panel-modal-body space-y-3">
            <input type="hidden" name="id">
            <div><label class="form-label text-xs">Name</label>
                 <input class="form-input" name="name" required></div>
            <div><label class="form-label text-xs">URL</label>
                 <input class="form-input mono" name="url" required></div>
            <div class="grid grid-cols-2 gap-3">
                <div><label class="form-label text-xs">Username</label>
                     <input class="form-input mono" name="username"></div>
                <div><label class="form-label text-xs">Password</label>
                     <input class="form-input mono" name="password"></div>
            </div>
            <div class="flex justify-end gap-2 pt-2">
                <button type="button" onclick="closeModal('up-edit-modal')" class="px-4 py-2 text-xs text-dark-400 hover:text-dark-200">Cancel</button>
                <button type="submit" class="btn-primary text-xs"><i class="ph ph-floppy-disk"></i> Save</button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Portal modal -->
<div id="portal-modal-edit" class="panel-modal" style="display:none">
    <div class="panel-modal-card">
        <div class="panel-modal-head">
            <h3><i class="ph ph-pencil-simple text-primary-400 mr-1"></i> Edit Portal</h3>
            <button onclick="closeModal('portal-modal-edit')" class="icon-btn"><i class="ph ph-x"></i></button>
        </div>
        <form id="portal-form-edit" class="panel-modal-body space-y-3">
            <input type="hidden" name="id">
            <div><label class="form-label text-xs">Name</label>
                 <input class="form-input" name="name" required></div>
            <div><label class="form-label text-xs">URL</label>
                 <input class="form-input mono" name="url" required></div>
            <div class="grid grid-cols-2 gap-3">
                <div><label class="form-label text-xs">Type</label>
                     <select class="form-input" name="type">
                         <option value="xtream">Xtream</option>
                         <option value="m3u">M3U</option>
                         <option value="stalker">Stalker</option>
                     </select></div>
                <div><label class="form-label text-xs">Sort order</label>
                     <input class="form-input" name="sort_order" type="number"></div>
            </div>
            <label class="flex items-center gap-2 text-xs text-dark-200">
                <input type="checkbox" name="enabled" value="1" class="form-check"> Enabled
            </label>
            <div class="flex justify-end gap-2 pt-2">
                <button type="button" onclick="closeModal('portal-modal-edit')" class="px-4 py-2 text-xs text-dark-400 hover:text-dark-200">Cancel</button>
                <button type="submit" class="btn-primary text-xs"><i class="ph ph-floppy-disk"></i> Save</button>
            </div>
        </form>
    </div>
</div>

<!-- Duplicate report modal -->
<div id="dup-modal" class="panel-modal" style="display:none">
    <div class="panel-modal-card lg">
        <div class="panel-modal-head">
            <h3><i class="ph ph-magnifying-glass-plus text-primary-400 mr-1"></i> Duplicate Detection</h3>
            <button onclick="closeModal('dup-modal')" class="icon-btn"><i class="ph ph-x"></i></button>
        </div>
        <div id="dup-modal-body" class="panel-modal-body"></div>
    </div>
</div>

<!-- Set Trial Expiry modal -->
<div id="trial-modal-new" class="panel-modal" style="display:none">
    <div class="panel-modal-card">
        <div class="panel-modal-head">
            <h3><i class="ph ph-clock text-primary-400 mr-1"></i> Set Trial Expiry</h3>
            <button onclick="closeModal('trial-modal-new')" class="icon-btn"><i class="ph ph-x"></i></button>
        </div>
        <form id="trial-form-new" class="panel-modal-body space-y-3">
            <div><label class="form-label text-xs">MAC address</label>
                 <input class="form-input mono" name="mac_address" required></div>
            <div><label class="form-label text-xs">Expiry date (YYYY-MM-DD)</label>
                 <input class="form-input" name="expired_date" type="date" required></div>
            <div class="flex justify-end gap-2 pt-2">
                <button type="button" onclick="closeModal('trial-modal-new')" class="px-4 py-2 text-xs text-dark-400 hover:text-dark-200">Cancel</button>
                <button type="submit" class="btn-primary text-xs"><i class="ph ph-floppy-disk"></i> Save</button>
            </div>
        </form>
    </div>
</div>

<style>
.tab-btn { padding: 14px 18px; display: inline-flex; align-items: center; gap: 8px;
    color: #999; font-size: 13px; border-bottom: 2px solid transparent; cursor: pointer;
    background: transparent; transition: color 0.15s, border-color 0.15s; }
.tab-btn:hover { color: #ccc; }
.tab-active { color: #f39c12; border-bottom-color: #f39c12; }
.tab-badge { display: inline-flex; align-items: center; justify-content: center; min-width: 22px;
    height: 18px; padding: 0 6px; background: #2a2a2a; color: #aaa; border-radius: 10px;
    font-size: 10px; font-weight: 600; }
.tab-active .tab-badge { background: rgba(243,156,18,0.18); color: #f39c12; }
.stat-chip { display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; font-size: 12px;
    background: #1a1a1a; border: 1px solid #2a2a2a; border-radius: 6px; color: #ccc; }
.stat-chip i { color: #f39c12; }
.btn-danger { background: rgba(239,68,68,0.15); color: #f87171; border: 1px solid rgba(239,68,68,0.3);
    padding: 6px 12px; border-radius: 6px; display: inline-flex; align-items: center; gap: 6px; font-size: 12px; }
.btn-danger:hover { background: rgba(239,68,68,0.25); }
.btn-secondary { background: #2a2a2a; color: #ccc; border: 1px solid #3a3a3a; padding: 6px 12px;
    border-radius: 6px; display: inline-flex; align-items: center; gap: 6px; font-size: 12px; }
.btn-secondary:hover { background: #3a3a3a; color: white; }
.badge { display: inline-flex; align-items: center; justify-content: center; min-width: 20px; height: 16px;
    padding: 0 5px; background: rgba(243,156,18,0.15); color: #f39c12; border-radius: 8px;
    font-size: 10px; font-weight: 700; }
[x-cloak] { display: none !important; }
</style>

<script>
// ---------------------------------------------------------------------------
// Services tab (portals)
// ---------------------------------------------------------------------------
let portalsCache = [];

async function loadPortals() {
    try {
        const r = await api.get('api/portals.php');
        portalsCache = r.portals || [];
        document.getElementById('sc-count-services').textContent = portalsCache.length;
        document.getElementById('portal-meta').textContent = portalsCache.length + ' portal' + (portalsCache.length === 1 ? '' : 's');
        renderPortals();
    } catch (e) { toast('portals: ' + e.message, 'error'); }
}
function renderPortals() {
    const q = (document.getElementById('portal-search').value || '').toLowerCase();
    const tbody = document.getElementById('portal-rows');
    const rows = portalsCache.filter(p =>
        !q || (p.name||'').toLowerCase().includes(q) || (p.url||'').toLowerCase().includes(q));
    if (!rows.length) {
        tbody.innerHTML = '<tr><td colspan="4" class="text-center text-xs text-dark-500 py-8">No portals.</td></tr>';
        return;
    }
    tbody.innerHTML = rows.map(p => `
        <tr>
            <td><input type="checkbox" class="row-check" data-id="${p.id}"></td>
            <td class="text-primary-400 font-semibold">${escapeHtml(p.name||'')}</td>
            <td class="mono text-dark-300">${escapeHtml(p.url||'')}</td>
            <td class="text-right">
                <button class="icon-btn" onclick="editPortal(${p.id})" title="Edit"><i class="ph ph-pencil-simple text-primary-400"></i></button>
                <button class="icon-btn danger" onclick="deletePortal(${p.id})" title="Delete"><i class="ph ph-trash text-red-400"></i></button>
            </td>
        </tr>`).join('');
}
async function deletePortal(id) {
    if (!(await confirmDanger('Delete this portal?'))) return;
    try { await api.post('api/portals.php', { action: 'delete', id }); toast('Deleted', 'success'); loadPortals(); }
    catch (e) { toast(e.message, 'error'); }
}
async function deleteAllPortals() {
    if (!(await confirmDanger('Delete ALL portals? This cannot be undone.'))) return;
    for (const p of portalsCache) {
        try { await api.post('api/portals.php', { action: 'delete', id: p.id }); } catch (_) {}
    }
    toast('Cleared', 'success'); loadPortals();
}
function editPortal(id) {
    const p = portalsCache.find(x => +x.id === +id);
    if (!p) return;
    const f = document.getElementById('portal-form-edit');
    f.id.value         = p.id;
    f.name.value       = p.name || '';
    f.url.value        = p.url || '';
    f.type.value       = p.type || 'xtream';
    f.sort_order.value = p.sort_order || 0;
    f.enabled.checked  = +p.enabled === 1;
    openModal('portal-modal-edit');
}
document.getElementById('portal-search').addEventListener('input', renderPortals);
document.getElementById('portal-form-new').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        await api.post('api/portals.php', Object.assign({ action: 'create' }, formObject(e.target)));
        toast('Portal created', 'success'); closeModal('portal-modal-new'); e.target.reset(); loadPortals();
    } catch (err) { toast(err.message, 'error'); }
});
document.getElementById('portal-form-edit').addEventListener('submit', async (e) => {
    e.preventDefault();
    const body = Object.assign({ action: 'update' }, formObject(e.target));
    body.enabled = e.target.enabled.checked ? 1 : 0;
    try {
        await api.post('api/portals.php', body);
        toast('Portal updated', 'success'); closeModal('portal-modal-edit'); loadPortals();
    } catch (err) { toast(err.message, 'error'); }
});

// ---------------------------------------------------------------------------
// Users / Playlists tab
// ---------------------------------------------------------------------------
let upCache = { devices: [], playlists: [] };

async function loadUsersPlaylists() {
    try {
        const [d, p] = await Promise.all([
            api.get('api/devices.php'),
            api.get('api/playlists.php?list=all').catch(() => ({ playlists: [] }))
        ]);
        upCache.devices   = d.devices || [];
        upCache.playlists = p.playlists || [];
        const macs = upCache.devices.length;
        const pls  = upCache.playlists.length;
        document.getElementById('up-stat-macs').textContent      = macs;
        document.getElementById('up-stat-playlists').textContent = pls;
        document.getElementById('up-stat-avg').textContent       = macs > 0 ? (pls / macs).toFixed(1) : '0';
        document.getElementById('sc-count-users').textContent    = pls;
        renderUsersPlaylists();
    } catch (e) { toast('users: ' + e.message, 'error'); }
}
function renderUsersPlaylists() {
    const q = (document.getElementById('up-search').value || '').toLowerCase();
    const tbody = document.getElementById('up-rows');
    const macById = {};
    upCache.devices.forEach(d => { macById[d.id] = d.mac_address; });
    let rows = upCache.playlists.length ? upCache.playlists.map(pl => ({
        id: pl.device_id,               // Row.id = DEVICE id (Delete/Lock target the
                                        // device row; cascade deletes the playlists).
        playlistId: pl.id,              // Edit needs the playlist row id since name/
                                        // URL/username/password live on `playlists`.
        mac:      macById[pl.device_id] || '—',
        title:    pl.name || '',
        username: pl.username || '',
        password: pl.password || '',
        portalUrl:pl.url || '',
        type:     pl.type || 'Direct',
        expiry:   pl.expired_date || '—',
        locked:   0,                    // Populated below from subscriptions.lock.
    })) : upCache.devices.map(d => ({
        id: d.id, playlistId: 0, mac: d.mac_address, title: '', username: '', password: '',
        portalUrl: '', type: 'Direct', expiry: '—', locked: 0
    }));
    // Fold in per-device subscription.lock so the Lock button reflects the
    // current state on first render (avoids an extra round-trip per row).
    const lockById = {};
    upCache.devices.forEach(d => { if (typeof d.lock !== 'undefined') lockById[d.id] = +d.lock; });
    rows.forEach(r => { r.locked = lockById[r.id] || 0; });
    if (q) rows = rows.filter(r =>
        (r.mac||'').toLowerCase().includes(q) || (r.title||'').toLowerCase().includes(q) ||
        (r.username||'').toLowerCase().includes(q) || (r.portalUrl||'').toLowerCase().includes(q));
    if (!rows.length) {
        tbody.innerHTML = '<tr><td colspan="8" class="text-center text-xs text-dark-500 py-8">No MACs yet.</td></tr>';
        return;
    }
    tbody.innerHTML = rows.map(r => `
        <tr>
            <td><input type="checkbox" class="row-check" data-id="${r.id}"></td>
            <td class="mono text-primary-400">${escapeHtml(r.mac)}</td>
            <td class="text-white">${escapeHtml(r.title)}</td>
            <td class="text-dark-300">${escapeHtml(r.username)}</td>
            <td class="mono text-dark-400 text-xs">${escapeHtml(r.portalUrl)}</td>
            <td><span class="pill pill-on text-xs"><i class="ph ph-shield-check"></i> ${escapeHtml(r.type)}</span></td>
            <td class="text-xs text-dark-400">${escapeHtml(r.expiry)}</td>
            <td class="text-right">
                ${r.playlistId ? `<button class="icon-btn" title="Edit playlist" onclick="editUpRow(${r.playlistId})"><i class="ph ph-pencil-simple text-primary-400"></i></button>` : ''}
                <button class="icon-btn" title="${r.locked ? 'Unlock device' : 'Lock device'}" onclick="toggleLockUpRow(${r.id}, ${r.locked ? 0 : 1})"><i class="ph ${r.locked ? 'ph-lock-key text-red-400' : 'ph-lock-key-open text-amber-400'}"></i></button>
                <button class="icon-btn danger" title="Delete this playlist + its MAC" onclick="deleteUpRow(${r.id}, ${r.playlistId || 0})"><i class="ph ph-trash text-red-400"></i></button>
            </td>
        </tr>`).join('');
}
async function deleteUpRow(deviceId, playlistId) {
    // Row-level delete = "delete this playlist + its MAC, but leave other
    // playlists on the same MAC alone". Server does it atomically: removes the
    // playlist, then removes the device ONLY if it has no remaining playlists.
    if (!(await confirmDanger('Delete this user? Removes this playlist and, if it was the only one on this MAC, the MAC too.'))) return;
    try {
        await api.post('api/devices.php', { action: 'delete_user_row', device_id: deviceId, playlist_id: playlistId });
        toast('Deleted', 'success');
        loadUsersPlaylists();
    } catch (e) { toast(e.message, 'error'); }
}
async function editUpRow(playlistId) {
    const pl = upCache.playlists.find(p => p.id === playlistId);
    if (!pl) { toast('Playlist not found', 'error'); return; }
    const f = document.getElementById('up-edit-form');
    f.id.value = pl.id;
    f.name.value = pl.name || '';
    f.url.value = pl.url || '';
    f.username.value = pl.username || '';
    f.password.value = pl.password || '';
    openModal('up-edit-modal');
}
async function toggleLockUpRow(deviceId, lock) {
    try {
        await api.post('api/subscriptions.php', { action: 'update', device_id: deviceId, lock });
        toast(lock ? 'Device locked' : 'Device unlocked', 'success');
        loadUsersPlaylists();
    } catch (e) { toast(e.message, 'error'); }
}
async function findDuplicateMacs() {
    try {
        const [byUrl, byAndroid] = await Promise.all([
            api.get('api/find_duplicates.php?scope=playlist_url'),
            api.get('api/find_duplicates.php?scope=mac'),
        ]);
        const total = (byUrl.total_groups || 0) + (byAndroid.total_groups || 0);
        document.getElementById('up-dup-count').textContent = total;
        if (!total) { toast('No duplicates found', 'success'); return; }

        // Render a modal with the duplicate groups
        let html = '';
        if (byUrl.total_groups) {
            html += '<p class="text-xs uppercase text-primary-400 font-semibold mt-3 mb-2">Same playlist URL</p>';
            byUrl.groups.slice(0, 10).forEach(g => {
                html += `<div class="p-3 mb-2 rounded-lg border border-dark-700 bg-dark-900">
                    <p class="text-xs mono text-dark-300 truncate" title="${escapeHtml(g.key)}">${escapeHtml(g.key)}</p>
                    <p class="text-[11px] text-dark-500 mt-1">${g.count} entries · MACs: ${g.macs.slice(0,6).map(escapeHtml).join(', ')}${g.macs.length > 6 ? '…' : ''}</p>
                </div>`;
            });
        }
        if (byAndroid.total_groups) {
            html += '<p class="text-xs uppercase text-primary-400 font-semibold mt-3 mb-2">Same device (different MAC)</p>';
            byAndroid.groups.slice(0, 10).forEach(g => {
                html += `<div class="p-3 mb-2 rounded-lg border border-dark-700 bg-dark-900">
                    <p class="text-xs mono text-dark-300 truncate">${escapeHtml(g.key)}</p>
                    <p class="text-[11px] text-dark-500 mt-1">${g.count} devices · MACs: ${g.macs.slice(0,6).map(escapeHtml).join(', ')}</p>
                </div>`;
            });
        }
        document.getElementById('dup-modal-body').innerHTML = html;
        openModal('dup-modal');
    } catch (e) { toast(e.message, 'error'); }
}
document.getElementById('up-search').addEventListener('input', renderUsersPlaylists);
document.getElementById('device-form-new').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        await api.post('api/devices.php', Object.assign({ action: 'create' }, formObject(e.target)));
        toast('Device added', 'success'); closeModal('device-modal-new'); e.target.reset(); loadUsersPlaylists();
    } catch (err) { toast(err.message, 'error'); }
});
document.getElementById('up-edit-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        await api.post('api/playlists.php', Object.assign({ action: 'update' }, formObject(e.target)));
        toast('Playlist saved', 'success'); closeModal('up-edit-modal'); loadUsersPlaylists();
    } catch (err) { toast(err.message, 'error'); }
});

// ---------------------------------------------------------------------------
// Trials / Expiry tab
// ---------------------------------------------------------------------------
async function loadTrials() {
    try {
        const r = await api.get('api/trial_expiry.php');
        const trials = r.trials || [];
        document.getElementById('sc-count-trials').textContent = trials.length;
        const tbody = document.getElementById('trial-rows');
        if (!tbody) return;
        if (!trials.length) {
            tbody.innerHTML = '<tr><td colspan="4" class="text-center text-xs text-dark-500 py-8">No trials yet. Click <strong>Set Trial Expiry</strong> above to create one.</td></tr>';
            return;
        }
        tbody.innerHTML = trials.map(t => `
            <tr>
                <td class="mono text-primary-400">${escapeHtml(t.mac_address || '')}</td>
                <td class="text-white">${escapeHtml(t.expired_date || '—')}</td>
                <td><span class="pill pill-${(+t.is_trial === 1) ? 'on' : 'off'} text-xs">${(+t.is_trial === 1) ? 'TRIAL' : 'EXPIRED'}</span></td>
                <td class="text-right">
                    <button class="icon-btn danger" title="Delete" onclick="deleteTrial('${escapeHtml(t.mac_address)}')"><i class="ph ph-trash text-red-400"></i></button>
                </td>
            </tr>`).join('');
    } catch (e) {
        document.getElementById('sc-count-trials').textContent = 0;
    }
}

async function deleteTrial(mac) {
    if (!(await confirmDanger('Remove trial for ' + mac + '?'))) return;
    try {
        await api.post('api/trial_expiry.php', { action: 'delete', mac_address: mac });
        toast('Trial removed', 'success');
        loadTrials();
    } catch (e) { toast(e.message, 'error'); }
}
document.getElementById('trial-form-new').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        await api.post('api/trial_expiry.php', Object.assign({ action: 'set' }, formObject(e.target)));
        toast('Trial expiry saved', 'success');
        closeModal('trial-modal-new');
        loadTrials();
    } catch (err) { toast(err.message, 'error'); }
});

// Restore handler — same as downloads.php but rendered here for the Backup/Restore buttons.
document.getElementById('sc-restore-file').addEventListener('change', async (e) => {
    const f = e.target.files[0];
    if (!f) return;
    if (!(await confirmDanger('This will replace all panel data with the contents of the backup. A safety copy of the current data is saved first. Continue?'))) return;
    const fd = new FormData();
    fd.append('file', f); fd.append('confirm', 'YES'); fd.append('action', 'restore');
    try {
        const r = await fetch('api/restore.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();
        toast(out.ok ? 'Backup restored — please reload the page.' : ('Restore failed: ' + (out.error || r.status)),
              out.ok ? 'success' : 'error');
    } catch (err) { toast(err.message, 'error'); }
});

// ---------------------------------------------------------------------------
loadPortals();
loadUsersPlaylists();
loadTrials();
</script>

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