<div class="space-y-4">

    
    <div class="flex items-start gap-3 p-4 bg-amber-50 border border-amber-200 rounded-lg">
        <svg class="w-5 h-5 text-amber-600 flex-shrink-0 mt-0.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>
        </svg>
        <div>
            <p class="text-sm font-semibold text-amber-800">Danger zone</p>
            <p class="text-xs text-amber-700 mt-0.5">Select what you want to delete. These actions are permanent, cannot be undone, and handle large datasets efficiently.</p>
        </div>
    </div>

    
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
        <table class="w-full">
            <thead>
                <tr class="bg-gray-50 border-b border-gray-200">
                    <th class="w-10 px-3 py-2.5">
                        <input type="checkbox" id="purgeSelectAll" class="rounded border-gray-300 text-red-600 focus:ring-red-500" onchange="toggleAllPurge(this.checked)">
                    </th>
                    <th class="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500">Data</th>
                    <th class="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500">Count</th>
                    <th class="px-3 py-2.5 text-left text-[11px] font-semibold uppercase tracking-wider text-gray-500 hidden sm:table-cell">What gets deleted</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
                <?php
                $entities = [
                    ['key' => 'videos',      'label' => 'Videos',      'desc' => 'All videos + associations, comments, likes, favorites, history', 'color' => 'blue'],
                    ['key' => 'categories',  'label' => 'Categories',  'desc' => 'All categories + video associations', 'color' => 'purple'],
                    ['key' => 'tags',        'label' => 'Tags',        'desc' => 'All tags + video associations', 'color' => 'teal'],
                    ['key' => 'performers',  'label' => 'Pornstars',   'desc' => 'All pornstars + video associations', 'color' => 'pink'],
                    ['key' => 'channels',     'label' => 'Channels',     'desc' => 'All channels + video associations', 'color' => 'indigo'],
                    ['key' => 'albums',            'label' => 'Albums',            'desc' => 'All galleries + associations, comments, likes, favorites, reports', 'color' => 'rose'],
                    ['key' => 'album_categories',  'label' => 'Album Categories',  'desc' => 'All album categories + gallery associations', 'color' => 'purple'],
                    ['key' => 'album_tags',        'label' => 'Album Tags',        'desc' => 'All album tags + gallery associations', 'color' => 'teal'],
                    ['key' => 'album_performers',  'label' => 'Album Pornstars',   'desc' => 'All album pornstars + gallery associations', 'color' => 'pink'],
                    ['key' => 'album_channels',    'label' => 'Album Channels',    'desc' => 'All album channels + gallery associations', 'color' => 'indigo'],
                    ['key' => 'comments',    'label' => 'Comments',    'desc' => 'All comments (pending + approved)', 'color' => 'yellow'],
                    ['key' => 'pages',       'label' => 'Pages',       'desc' => 'All static pages', 'color' => 'gray'],
                    ['key' => 'users',       'label' => 'Users',       'desc' => 'All non-admin users + their data (admin accounts preserved)', 'color' => 'orange'],
                    ['key' => 'imports',     'label' => 'Import Jobs', 'desc' => 'All import job records (imported videos kept)', 'color' => 'cyan'],
                ];
                foreach ($entities as $entity):
                    $count = $counts[$entity['key']] ?? 0;
                    $disabled = $count === 0;
                ?>
                <tr class="hover:bg-gray-50 transition-colors <?= $disabled ? 'opacity-50' : '' ?>">
                    <td class="px-3 py-2.5">
                        <input type="checkbox" data-purge-type="<?= $entity['key'] ?>" data-purge-label="<?= $entity['label'] ?>"
                               class="purge-cb rounded border-gray-300 text-red-600 focus:ring-red-500"
                               <?= $disabled ? 'disabled' : '' ?> onchange="updatePurgeBar()">
                    </td>
                    <td class="px-3 py-2.5">
                        <span class="text-xs font-semibold text-gray-900"><?= $entity['label'] ?></span>
                    </td>
                    <td class="px-3 py-2.5">
                        <span id="count-<?= $entity['key'] ?>" class="inline-flex items-center px-2 py-0.5 rounded-full text-[11px] font-medium <?= $count > 0 ? 'bg-' . $entity['color'] . '-50 text-' . $entity['color'] . '-700' : 'bg-gray-100 text-gray-400' ?>">
                            <?= number_format($count) ?>
                        </span>
                    </td>
                    <td class="px-3 py-2.5 text-xs text-gray-500 hidden sm:table-cell"><?= $entity['desc'] ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        
        <div id="purgeBar" class="hidden border-t border-gray-200 px-4 py-3 bg-red-50 flex items-center justify-between gap-3">
            <span class="text-xs text-red-700 font-medium"><span id="purgeSelectedCount">0</span> type(s) selected for deletion</span>
            <button type="button" id="purgeBtn" onclick="openPurgeModal()"
                    class="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors">
                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                Delete selected
            </button>
        </div>
    </div>
</div>


<div id="purgeModal" style="display:none;position:fixed;inset:0;z-index:50;align-items:center;justify-content:center;background:rgba(0,0,0,.5)">
    <div style="background:#fff;border-radius:12px;box-shadow:0 20px 60px rgba(0,0,0,.25);width:100%;max-width:480px;margin:16px;overflow:hidden">
        <div style="padding:24px 24px 0">
            <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px">
                <div style="width:40px;height:40px;border-radius:50%;background:#fef2f2;display:flex;align-items:center;justify-content:center;flex-shrink:0">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#dc2626" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
                </div>
                <div>
                    <h3 style="font-size:15px;font-weight:600;color:#111;margin:0">Confirm deletion</h3>
                    <p id="purgeModalDesc" style="font-size:12px;color:#666;margin:2px 0 0"></p>
                </div>
            </div>

            
            <div id="purgeProgress" style="display:none;margin-bottom:12px">
                <div style="display:flex;justify-content:space-between;margin-bottom:6px">
                    <span id="purgeProgressLabel" style="font-size:12px;color:#666">Deleting...</span>
                    <span id="purgeProgressStep" style="font-size:12px;font-weight:600;color:#111"></span>
                </div>
                <div style="width:100%;height:6px;background:#e5e7eb;border-radius:3px;overflow:hidden">
                    <div id="purgeProgressBar" style="width:0%;height:100%;background:#dc2626;border-radius:3px;transition:width .3s"></div>
                </div>
            </div>

            
            <div id="purgeConfirmArea">
                <p style="font-size:13px;color:#444;margin:0 0 12px">This action <strong>cannot be undone</strong>. Type <code style="padding:2px 6px;background:#f3f4f6;border-radius:4px;font-size:12px;font-weight:600">DELETE</code> to confirm.</p>
                <input type="text" id="purgeConfirmInput" autocomplete="off" spellcheck="false"
                       placeholder="Type DELETE here"
                       style="width:100%;padding:10px 14px;border:2px solid #e5e7eb;border-radius:8px;font-size:14px;font-family:monospace;letter-spacing:2px;text-transform:uppercase;outline:none;box-sizing:border-box;transition:border-color .15s"
                       oninput="document.getElementById('purgeConfirmBtn').disabled=this.value.toUpperCase()!=='DELETE'"
                       onkeydown="if(event.key==='Enter'&&this.value.toUpperCase()==='DELETE')executePurge()"
                       onfocus="this.style.borderColor='#dc2626'"
                       onblur="this.style.borderColor='#e5e7eb'">
            </div>
        </div>
        <div style="padding:16px 24px;margin-top:16px;border-top:1px solid #e5e7eb;display:flex;gap:12px;justify-content:flex-end">
            <button type="button" id="purgeCancelBtn" onclick="closePurgeModal()"
                    style="padding:8px 16px;font-size:13px;font-weight:500;color:#374151;background:#fff;border:1px solid #d1d5db;border-radius:8px;cursor:pointer;transition:background .15s"
                    onmouseover="this.style.background='#f9fafb'" onmouseout="this.style.background='#fff'">
                Cancel
            </button>
            <button type="button" id="purgeConfirmBtn" onclick="executePurge()" disabled
                    style="padding:8px 16px;font-size:13px;font-weight:600;color:#fff;background:#dc2626;border:none;border-radius:8px;cursor:pointer;transition:opacity .15s;opacity:.5"
                    onmouseover="if(!this.disabled)this.style.background='#b91c1c'" onmouseout="this.style.background='#dc2626'">
                Delete permanently
            </button>
        </div>
    </div>
</div>
<style>
    #purgeModal.open{display:flex!important}
    #purgeConfirmBtn:not(:disabled){opacity:1!important;cursor:pointer!important}
</style>

<script>
var _purgeQueue = [];
var _purgeIndex = 0;
var _purgeTotalDeleted = 0;

function getSelectedTypes() {
    var types = [];
    document.querySelectorAll('.purge-cb:checked').forEach(function(cb) {
        types.push({ type: cb.getAttribute('data-purge-type'), label: cb.getAttribute('data-purge-label') });
    });
    return types;
}

function toggleAllPurge(checked) {
    document.querySelectorAll('.purge-cb:not(:disabled)').forEach(function(cb) { cb.checked = checked; });
    updatePurgeBar();
}

function updatePurgeBar() {
    var sel = getSelectedTypes();
    var bar = document.getElementById('purgeBar');
    var countEl = document.getElementById('purgeSelectedCount');
    if (sel.length > 0) {
        bar.classList.remove('hidden');
        countEl.textContent = sel.length;
    } else {
        bar.classList.add('hidden');
    }
    
    var all = document.querySelectorAll('.purge-cb:not(:disabled)');
    var checked = document.querySelectorAll('.purge-cb:checked');
    var selectAll = document.getElementById('purgeSelectAll');
    selectAll.checked = all.length > 0 && checked.length === all.length;
    selectAll.indeterminate = checked.length > 0 && checked.length < all.length;
}

function openPurgeModal() {
    var sel = getSelectedTypes();
    if (sel.length === 0) return;
    var labels = sel.map(function(s) { return s.label; });
    document.getElementById('purgeModalDesc').textContent = 'You are about to delete: ' + labels.join(', ') + '.';
    document.getElementById('purgeConfirmInput').value = '';
    document.getElementById('purgeConfirmBtn').disabled = true;
    document.getElementById('purgeConfirmBtn').style.display = '';
    document.getElementById('purgeConfirmArea').style.display = '';
    document.getElementById('purgeProgress').style.display = 'none';
    document.getElementById('purgeCancelBtn').textContent = 'Cancel';
    document.getElementById('purgeModal').classList.add('open');
    setTimeout(function() { document.getElementById('purgeConfirmInput').focus(); }, 100);
}

function closePurgeModal() {
    document.getElementById('purgeModal').classList.remove('open');
    _purgeQueue = [];
    _purgeIndex = 0;
}

function executePurge() {
    _purgeQueue = getSelectedTypes();
    _purgeIndex = 0;
    _purgeTotalDeleted = 0;

    
    document.getElementById('purgeConfirmArea').style.display = 'none';
    document.getElementById('purgeConfirmBtn').style.display = 'none';
    document.getElementById('purgeProgress').style.display = '';
    document.getElementById('purgeCancelBtn').textContent = 'Close';
    document.getElementById('purgeCancelBtn').disabled = true;

    purgeNext();
}

function purgeNext() {
    if (_purgeIndex >= _purgeQueue.length) {
        
        document.getElementById('purgeProgressLabel').textContent = 'All done!';
        document.getElementById('purgeProgressBar').style.width = '100%';
        document.getElementById('purgeProgressBar').style.background = '#059669';
        document.getElementById('purgeCancelBtn').disabled = false;
        document.getElementById('purgeCancelBtn').textContent = 'Close';

        
        document.querySelectorAll('.purge-cb:checked').forEach(function(cb) {
            var type = cb.getAttribute('data-purge-type');
            var countEl = document.getElementById('count-' + type);
            if (countEl) countEl.textContent = '0';
            cb.checked = false;
            cb.disabled = true;
            cb.closest('tr').classList.add('opacity-50');
        });
        updatePurgeBar();
        document.getElementById('purgeSelectAll').checked = false;
        document.getElementById('purgeSelectAll').indeterminate = false;

        showToast(_purgeTotalDeleted.toLocaleString() + ' records deleted across ' + _purgeQueue.length + ' type(s).');
        return;
    }

    var item = _purgeQueue[_purgeIndex];
    document.getElementById('purgeProgressLabel').textContent = 'Deleting ' + item.label + '...';
    document.getElementById('purgeProgressStep').textContent = (_purgeIndex + 1) + ' / ' + _purgeQueue.length;
    purgeChunk(item);
}





function purgeChunk(item) {
    fetch('/admin/settings/purge', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'type=' + encodeURIComponent(item.type) + '&csrf_token=' + encodeURIComponent('<?= Router::csrfToken() ?>')
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (!data.success) {
            document.getElementById('purgeProgressLabel').textContent = 'Error deleting ' + item.label + ': ' + (data.error || 'Unknown error');
            document.getElementById('purgeProgressBar').style.background = '#dc2626';
            document.getElementById('purgeCancelBtn').disabled = false;
            return;
        }
        _purgeTotalDeleted += (data.deleted || 0);
        if (data.busy) { setTimeout(function() { purgeChunk(item); }, 800); return; }

        var remaining = data.remaining || 0;
        var countEl = document.getElementById('count-' + item.type);
        if (countEl) countEl.textContent = remaining.toLocaleString();

        var frac = (_purgeIndex + (data.done ? 1 : 0.5)) / _purgeQueue.length;
        document.getElementById('purgeProgressBar').style.width = Math.round(frac * 100) + '%';
        document.getElementById('purgeProgressLabel').textContent = data.done
            ? ('Deleted ' + item.label)
            : ('Deleting ' + item.label + '… ' + remaining.toLocaleString() + ' left');

        if (data.done) { _purgeIndex++; purgeNext(); }
        else { purgeChunk(item); }
    })
    .catch(function() {
        document.getElementById('purgeProgressLabel').textContent = 'Network error while deleting ' + item.label;
        document.getElementById('purgeCancelBtn').disabled = false;
    });
}

function showToast(message) {
    var toast = document.createElement('div');
    toast.style.cssText = 'position:fixed;bottom:24px;right:24px;z-index:100;padding:12px 20px;background:#059669;color:#fff;border-radius:8px;font-size:13px;font-weight:500;box-shadow:0 4px 12px rgba(0,0,0,.15);transition:opacity .3s;display:flex;align-items:center;gap:8px';
    toast.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 6L9 17l-5-5"/></svg>' + message;
    document.body.appendChild(toast);
    setTimeout(function() {
        toast.style.opacity = '0';
        setTimeout(function() { toast.remove(); }, 300);
    }, 4000);
}
</script>
