<?php
/* ============================================================================
   Admin → Notifications
   Send notifications (with a link) and delete them.
   ============================================================================ */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/notify.php';
require_once __DIR__ . '/../includes/admin_list.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }
if (!hasPermission('manage_users')) { die("Access Denied: You do not have permission to manage notifications."); }

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id = $_SESSION['user_id'];
$conn = $db->getConnection();

notify_ensure_schema($db);

$can_users = hasPermission('manage_users');
$can_sellers = hasPermission('manage_sellers');
$can_staff = hasPermission('manage_staff_roles');
$can_services = hasPermission('manage_services');
$can_orders = hasPermission('manage_orders');
$can_transactions = hasPermission('manage_transactions');
$can_tickets = hasPermission('manage_tickets');
$can_settings = hasPermission('manage_settings');

$success_msg = ''; $error_msg = '';
if (isset($_SESSION['flash_success'])) { $success_msg = $_SESSION['flash_success']; unset($_SESSION['flash_success']); }
if (isset($_SESSION['flash_error']))   { $error_msg   = $_SESSION['flash_error'];   unset($_SESSION['flash_error']); }

$types = notify_types();

/* ---------------- POST ---------------- */
if (isset($_POST['send_notification'])) {
    $title   = trim(sanitize($_POST['n_title'] ?? ''));
    $message = trim(sanitize($_POST['n_message'] ?? ''));
    $type    = isset($types[$_POST['n_type'] ?? '']) ? $_POST['n_type'] : 'general';
    $link    = trim(sanitize($_POST['n_link'] ?? ''));
    $aud     = $_POST['n_audience'] ?? 'all';

    if ($title === '' || $message === '') {
        $_SESSION['flash_error'] = "Title and message are both required.";
    } else {
        if ($aud === 'single') {
            $tid = intval($_POST['n_user_id'] ?? 0);
            if ($tid <= 0) { $_SESSION['flash_error'] = "Pick a user to send it to."; redirect('notifications.php#send'); }
            notify_send($db, $tid, $title, $message, $type, $link, $user_id);
            $_SESSION['flash_success'] = "Notification sent.";
        } else {
            $ids = notify_audience_ids($db, in_array($aud, ['all','customer','seller','admin'], true) ? $aud : 'all');
            $n = notify_send_bulk($db, $ids, $title, $message, $type, $link, $user_id);
            $_SESSION['flash_success'] = "Notification sent to $n user(s).";
        }
    }
    redirect('notifications.php#sent');
}

if (isset($_POST['delete_one'])) {
    $db->insert("DELETE FROM notifications WHERE id = ?", [intval($_POST['notif_id'])]);
    $_SESSION['flash_success'] = "Notification deleted.";
    redirect('notifications.php#sent');
}

if (isset($_POST['bulk_delete'])) {
    $ids = (isset($_POST['nids']) && is_array($_POST['nids'])) ? array_map('intval', $_POST['nids']) : [];
    $n = 0;
    foreach ($ids as $i) { if ($i > 0) { $db->insert("DELETE FROM notifications WHERE id = ?", [$i]); $n++; } }
    $_SESSION['flash_success'] = "$n notification(s) deleted.";
    redirect('notifications.php#sent');
}

if (isset($_POST['delete_filtered'])) {
    $ft = trim($_POST['del_type'] ?? '');
    $fr = trim($_POST['del_read'] ?? '');
    $sql = "DELETE FROM notifications WHERE 1=1"; $p = [];
    if ($ft !== '' && isset($types[$ft])) { $sql .= " AND type = ?"; $p[] = $ft; }
    if ($fr === 'read')   { $sql .= " AND is_read = 1"; }
    if ($fr === 'unread') { $sql .= " AND is_read = 0"; }
    if ($fr === 'old')    { $sql .= " AND created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)"; }
    try { $db->insert($sql, $p); $_SESSION['flash_success'] = "Matching notifications deleted."; }
    catch (\Throwable $e) { $_SESSION['flash_error'] = "Could not delete."; }
    redirect('notifications.php#sent');
}

/* ---------------- FILTERS (sticky) ---------------- */
$defaults = ['q' => '', 'type' => '', 'read' => '', 'uid' => ''];
$F = alist_filters('notifications', $defaults);

$where = "1=1"; $params = [];
if ($F['q'] !== '')    { $where .= " AND (n.title LIKE ? OR n.message LIKE ? OR u.name LIKE ?)"; $l = "%{$F['q']}%"; array_push($params, $l, $l, $l); }
if ($F['type'] !== '' && isset($types[$F['type']])) { $where .= " AND n.type = ?"; $params[] = $F['type']; }
if ($F['read'] === 'read')   { $where .= " AND n.is_read = 1"; }
if ($F['read'] === 'unread') { $where .= " AND n.is_read = 0"; }
if ($F['uid'] !== '')  { $where .= " AND n.user_id = ?"; $params[] = (int)$F['uid']; }

/* ---------------- EXPORT ---------------- */
if (isset($_GET['export'])) {
    $rows = $db->select("SELECT n.*, u.name AS user_name, u.mobile FROM notifications n
                         LEFT JOIN users u ON n.user_id = u.id WHERE $where ORDER BY n.created_at DESC LIMIT 5000", $params);
    alist_export_csv('notifications', [
        'ID' => 'id', 'User' => 'user_name', 'Mobile' => 'mobile',
        'Type' => function ($r) { $m = notify_meta($r['type'] ?? 'general'); return $m[0]; },
        'Title' => 'title', 'Message' => 'message', 'Link' => 'link',
        'Read' => function ($r) { return $r['is_read'] ? 'Yes' : 'No'; },
        'Sent On' => 'created_at',
    ], $rows);
}

$rows = $db->select("SELECT n.*, u.name AS user_name, u.mobile, u.user_type FROM notifications n
                     LEFT JOIN users u ON n.user_id = u.id WHERE $where ORDER BY n.created_at DESC LIMIT 500", $params);

/* ---------------- STATS ---------------- */
$st = ['total' => 0, 'unread' => 0, 'today' => 0, 'week' => 0];
try {
    $r = $db->select("SELECT COUNT(*) t, SUM(is_read = 0) u,
                             SUM(DATE(created_at) = CURDATE()) d,
                             SUM(created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)) w FROM notifications");
    if (!empty($r)) { $st = ['total'=>(int)$r[0]['t'],'unread'=>(int)$r[0]['u'],'today'=>(int)$r[0]['d'],'week'=>(int)$r[0]['w']]; }
} catch (\Throwable $e) {}

$all_users = $db->select("SELECT id, name, mobile, user_type FROM users ORDER BY name ASC LIMIT 2000");

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;
$company_logo = getSetting('company_logo', '../assets/images/logo.png');
$company_name = getSetting('company_name', 'WBMCZ');
$profile_image_url = !empty($user['profile_pic']) ? '../uploads/profiles/' . $user['profile_pic'] : null;
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notifications - Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; } .hide-scrollbar::-webkit-scrollbar { display: none; } </style>
</head>
<body class="bg-gray-50" x-data="{ sidebarOpen: window.innerWidth >= 768, profileOpen: false, tab: (window.location.hash ? window.location.hash.substring(1) : 'sent') }">

    <div class="flex h-screen overflow-hidden">
        
        <?php include __DIR__ . '/includes/sidebar.php'; ?>
        <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">
            
            <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative">
                <div class="flex items-center">
                    <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 focus:outline-none rounded-lg hover:bg-gray-100 transition-colors">
                        <i class="fas fa-bars text-xl"></i>
                    </button>
                    <h2 class="text-xl font-bold hidden md:block text-slate-800">Notifications</h2>
                </div>

                <div class="flex items-center space-x-3 sm:space-x-5 ml-auto">
                    <div class="relative">
                        <button @click="profileOpen = !profileOpen" @click.away="profileOpen = false" class="flex items-center focus:outline-none">
                            <?php if(!empty($profile_image_url) && file_exists($profile_image_url)): ?>
                                <img src="<?php echo $profile_image_url; ?>" class="w-10 h-10 rounded-full border-2 border-emerald-100 shadow-sm object-cover">
                            <?php else: ?>
                                <div class="w-10 h-10 rounded-full bg-emerald-100 border-2 border-emerald-200 text-emerald-600 flex items-center justify-center text-lg font-bold shadow-sm">
                                    <?php echo strtoupper(substr($user['name'], 0, 1)); ?>
                                </div>
                            <?php endif; ?>
                            <i class="fas fa-chevron-down text-xs ml-2 text-slate-400 hidden sm:block"></i>
                        </button>
                        
                        <div x-show="profileOpen" x-transition class="absolute right-0 mt-3 w-56 bg-white rounded-xl shadow-2xl py-2 border border-gray-100 z-50" style="display: none;">
                            <div class="px-4 py-3 border-b border-gray-100">
                                <p class="text-sm text-gray-500">Signed in as Admin</p>
                                <p class="text-sm font-bold text-gray-900 truncate"><?php echo htmlspecialchars($user['name'], ENT_QUOTES, 'UTF-8', false); ?></p>
                            </div>
                            <a href="profile.php" class="block px-4 py-2 text-sm text-gray-700 hover:bg-emerald-50 hover:text-emerald-600 transition-colors"><i class="fas fa-user mr-2 w-4"></i> My Profile</a>
                            <div class="border-t border-gray-100 mt-2 pt-2">
                                <a href="../logout.php" onclick="return confirm('Are you sure you want to logout?');" class="block px-4 py-2 text-sm text-rose-600 hover:bg-rose-50 transition-colors"><i class="fas fa-sign-out-alt mr-2 w-4"></i> Logout</a>
                            </div>
                        </div>
                    </div>
                </div>
            </header>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8"
                  @hashchange.window="tab = window.location.hash.substring(1) || 'sent'"
                  x-data="{ sel: [], allIds: <?php echo json_encode(array_map(function($r){return (int)$r['id'];}, $rows)); ?>, aud: 'all' }">

                <?php if ($success_msg): ?>
                <div class="mb-5 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                    <i class="fas fa-check-circle text-xl mr-3"></i><span class="font-medium"><?php echo $success_msg; ?></span></div>
                <?php endif; ?>
                <?php if ($error_msg): ?>
                <div class="mb-5 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl flex items-center shadow-sm">
                    <i class="fas fa-exclamation-circle text-xl mr-3"></i><span class="font-medium"><?php echo $error_msg; ?></span></div>
                <?php endif; ?>

                <div class="mb-5">
                    <h2 class="text-xl sm:text-2xl font-bold text-slate-800 mb-1">Notifications</h2>
                    <p class="text-gray-500 text-xs sm:text-sm">Send notifications with a clickable link, and clean up old ones.</p>
                </div>

                <?php echo alist_stats([
                    ['label'=>'Total Sent','value'=>number_format($st['total']),'colour'=>'slate','icon'=>'fa-bell'],
                    ['label'=>'Unread','value'=>number_format($st['unread']),'colour'=>'amber','icon'=>'fa-envelope'],
                    ['label'=>'Today','value'=>number_format($st['today']),'colour'=>'emerald','icon'=>'fa-calendar-day'],
                    ['label'=>'Last 7 Days','value'=>number_format($st['week']),'colour'=>'blue','icon'=>'fa-calendar-week'],
                    ['label'=>'Read Rate','value'=>($st['total']>0 ? round((($st['total']-$st['unread'])/$st['total'])*100).'%' : '—'),'colour'=>'violet','icon'=>'fa-check-double'],
                    ['label'=>'Recipients','value'=>number_format(count($all_users)),'colour'=>'indigo','icon'=>'fa-users'],
                ]); ?>

                <div class="flex gap-1 mb-5 border-b border-gray-200 overflow-x-auto hide-scrollbar">
                    <a href="notifications.php#sent" @click="tab='sent'" :class="tab==='sent' ? 'border-emerald-600 text-emerald-700' : 'border-transparent text-slate-500'" class="px-4 py-3 text-xs sm:text-sm font-bold border-b-2 whitespace-nowrap"><i class="fas fa-list mr-1.5"></i>All Notifications</a>
                    <a href="notifications.php#send" @click="tab='send'" :class="tab==='send' ? 'border-emerald-600 text-emerald-700' : 'border-transparent text-slate-500'" class="px-4 py-3 text-xs sm:text-sm font-bold border-b-2 whitespace-nowrap"><i class="fas fa-paper-plane mr-1.5"></i>Send New</a>
                    <a href="notifications.php#cleanup" @click="tab='cleanup'" :class="tab==='cleanup' ? 'border-emerald-600 text-emerald-700' : 'border-transparent text-slate-500'" class="px-4 py-3 text-xs sm:text-sm font-bold border-b-2 whitespace-nowrap"><i class="fas fa-broom mr-1.5"></i>Bulk Delete</a>
                </div>

                <!-- ============ ALL NOTIFICATIONS ============ -->
                <div x-show="tab==='sent'" x-cloak>
                    <?php echo alist_banner('notifications.php', 'notifications', $F, $defaults, ['q'=>'Search','type'=>'Type','read'=>'Status','uid'=>'User ID']); ?>

                    <form method="GET" class="al-panel p-3 mb-4 grid grid-cols-2 lg:grid-cols-6 gap-2 items-end">
                        <input type="hidden" name="f" value="notifications">
                        <div class="col-span-2"><label class="al-l">Search</label>
                            <input name="q" value="<?php echo htmlspecialchars($F['q']); ?>" placeholder="Title, message or user" class="al-f"></div>
                        <div><label class="al-l">Type</label>
                            <select name="type" class="al-f"><option value="">All</option>
                                <?php foreach ($types as $tk => $tv): ?><option value="<?php echo $tk; ?>" <?php echo $F['type']===$tk?'selected':''; ?>><?php echo $tv[0]; ?></option><?php endforeach; ?>
                            </select></div>
                        <div><label class="al-l">Status</label>
                            <select name="read" class="al-f"><option value="">All</option>
                                <option value="unread" <?php echo $F['read']==='unread'?'selected':''; ?>>Unread</option>
                                <option value="read" <?php echo $F['read']==='read'?'selected':''; ?>>Read</option>
                            </select></div>
                        <div><label class="al-l">User ID</label>
                            <input name="uid" value="<?php echo htmlspecialchars($F['uid']); ?>" placeholder="e.g. 32" class="al-f"></div>
                        <div class="flex gap-2">
                            <button class="al-btn al-btn-apply flex-1">Apply</button>
                            <a href="<?php echo alist_url('notifications.php','notifications',$F,['export'=>1]); ?>" class="al-btn al-btn-csv"><i class="fas fa-file-csv"></i></a>
                        </div>
                    </form>

                    <div x-show="sel.length > 0" x-cloak class="mb-3 bg-slate-800 text-white rounded-xl px-4 py-2.5 flex flex-wrap items-center gap-3">
                        <span class="text-xs font-bold"><span x-text="sel.length"></span> selected</span>
                        <button type="button" @click="sel = [...allIds]" class="text-[11px] font-bold underline">Select all</button>
                        <button type="button" @click="sel = []" class="text-[11px] font-bold underline">Clear</button>
                        <form method="POST" class="ml-auto" onsubmit="return confirm('Delete the selected notifications?');">
                            <template x-for="i in sel" :key="i"><input type="hidden" name="nids[]" :value="i"></template>
                            <button type="submit" name="bulk_delete" class="al-btn al-btn-csv" style="background:#e11d48"><i class="fas fa-trash-alt"></i> Delete Selected</button>
                        </form>
                    </div>

                    <div class="al-panel overflow-hidden">
                        <div class="px-4 py-3 border-b border-slate-100 bg-slate-50/70 flex items-center justify-between">
                            <p class="text-sm font-bold text-slate-700">Notifications</p>
                            <span class="text-[11px] font-bold text-slate-400"><?php echo count($rows); ?> row(s)</span>
                        </div>
                        <?php if (empty($rows)): ?>
                            <div class="p-14 text-center text-slate-400"><i class="fas fa-bell-slash text-3xl mb-3 block text-slate-300"></i>
                            <p class="text-sm font-semibold text-slate-500">Nothing matches this filter</p></div>
                        <?php else: ?>
                        <div class="divide-y divide-slate-100">
                        <?php foreach ($rows as $n): $m = notify_meta($n['type'] ?? 'general'); ?>
                            <div class="p-3.5 flex items-start gap-3 hover:bg-slate-50/60">
                                <input type="checkbox" :value="<?php echo (int)$n['id']; ?>" x-model.number="sel" class="w-4 h-4 mt-1 rounded border-slate-300 text-indigo-600 flex-shrink-0">
                                <span class="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 bg-<?php echo $m[1]; ?>-50 text-<?php echo $m[1]; ?>-600 text-sm"><i class="fas <?php echo $m[2]; ?>"></i></span>
                                <div class="min-w-0 flex-1">
                                    <div class="flex flex-wrap items-center gap-2">
                                        <p class="text-xs font-extrabold text-slate-800 truncate"><?php echo htmlspecialchars($n['title']); ?></p>
                                        <span class="text-[9px] font-black px-1.5 py-0.5 rounded bg-<?php echo $m[1]; ?>-50 text-<?php echo $m[1]; ?>-600 uppercase"><?php echo $m[0]; ?></span>
                                        <?php if (empty($n['is_read'])): ?><span class="text-[9px] font-black px-1.5 py-0.5 rounded bg-amber-100 text-amber-700 uppercase">Unread</span><?php endif; ?>
                                    </div>
                                    <p class="text-[11px] text-slate-500 mt-0.5 break-words"><?php echo htmlspecialchars($n['message']); ?></p>
                                    <p class="text-[10px] text-slate-400 mt-1">
                                        <i class="fas fa-user mr-1"></i><?php echo htmlspecialchars($n['user_name'] ?: '—'); ?> (ID <?php echo (int)$n['user_id']; ?>)
                                        · <i class="far fa-clock mr-1"></i><?php echo date('d M Y, h:i A', strtotime($n['created_at'])); ?>
                                        <?php if (!empty($n['link'])): ?> · <i class="fas fa-link mr-1"></i><span class="font-mono"><?php echo htmlspecialchars($n['link']); ?></span><?php endif; ?>
                                    </p>
                                </div>
                                <form method="POST" onsubmit="return confirm('Delete this notification?');" class="flex-shrink-0">
                                    <input type="hidden" name="notif_id" value="<?php echo (int)$n['id']; ?>">
                                    <button type="submit" name="delete_one" class="w-8 h-8 rounded-lg bg-rose-50 hover:bg-rose-100 text-rose-600 text-xs"><i class="fas fa-trash-alt"></i></button>
                                </form>
                            </div>
                        <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- ============ SEND NEW ============ -->
                <div x-show="tab==='send'" x-cloak>
                    <form method="POST" class="al-panel p-5 max-w-2xl space-y-4">
                        <p class="text-sm font-bold text-slate-800"><i class="fas fa-paper-plane mr-2 text-emerald-600"></i>Send a notification</p>

                        <div>
                            <label class="al-l">Send to</label>
                            <div class="grid grid-cols-2 sm:grid-cols-5 gap-2">
                                <?php foreach ([['all','Everyone','fa-globe'],['customer','Customers','fa-users'],['seller','Sellers','fa-store'],['admin','Staff','fa-user-shield'],['single','One user','fa-user']] as $a): ?>
                                <label class="cursor-pointer">
                                    <input type="radio" name="n_audience" value="<?php echo $a[0]; ?>" x-model="aud" <?php echo $a[0]==='all'?'checked':''; ?> class="sr-only peer">
                                    <div class="p-2.5 rounded-xl border-2 text-center text-[11px] font-bold transition-all peer-checked:border-emerald-500 peer-checked:bg-emerald-50 peer-checked:text-emerald-700 border-slate-200 text-slate-500">
                                        <i class="fas <?php echo $a[2]; ?> block text-base mb-1"></i><?php echo $a[1]; ?>
                                    </div>
                                </label>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div x-show="aud === 'single'" x-cloak>
                            <label class="al-l">Pick the user</label>
                            <select name="n_user_id" class="al-f">
                                <option value="">— select —</option>
                                <?php foreach ($all_users as $u): ?>
                                    <option value="<?php echo (int)$u['id']; ?>"><?php echo htmlspecialchars($u['name']); ?> · <?php echo htmlspecialchars($u['mobile']); ?> · <?php echo ucfirst($u['user_type']); ?> (ID <?php echo (int)$u['id']; ?>)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="grid sm:grid-cols-2 gap-3">
                            <div><label class="al-l">Type</label>
                                <select name="n_type" class="al-f">
                                    <?php foreach ($types as $tk => $tv): ?><option value="<?php echo $tk; ?>"><?php echo $tv[0]; ?></option><?php endforeach; ?>
                                </select>
                                <p class="text-[10px] text-slate-400 mt-1">Sets the icon, colour and default link.</p></div>
                            <div><label class="al-l">Link <span class="text-slate-400 font-normal normal-case">(optional)</span></label>
                                <input name="n_link" placeholder="wallet.php#to_bank" class="al-f font-mono">
                                <p class="text-[10px] text-slate-400 mt-1">Leave blank to use the type's default page.</p></div>
                        </div>

                        <div><label class="al-l">Title <span class="text-rose-500">*</span></label>
                            <input name="n_title" required maxlength="255" placeholder="e.g. New offer on Government Portals" class="al-f"></div>
                        <div><label class="al-l">Message <span class="text-rose-500">*</span></label>
                            <textarea name="n_message" required rows="4" placeholder="Write the message the user will see..." class="al-f resize-y"></textarea></div>

                        <div class="bg-slate-50 border border-slate-200 rounded-xl p-3 text-[11px] text-slate-600">
                            <b>Link examples:</b> <code>wallet.php#to_bank</code> · <code>earning_report.php</code> ·
                            <code>subscription.php</code> · <code>profile.php#kyc</code> · <code>category.php?id=1</code> ·
                            or a full <code>https://…</code> address.
                        </div>

                        <button type="submit" name="send_notification" class="al-btn al-btn-apply px-8 py-3 w-full sm:w-auto"><i class="fas fa-paper-plane"></i> Send Notification</button>
                    </form>
                </div>

                <!-- ============ BULK DELETE ============ -->
                <div x-show="tab==='cleanup'" x-cloak>
                    <form method="POST" class="al-panel p-5 max-w-xl space-y-4" onsubmit="return confirm('Delete every notification matching these rules? This cannot be undone.');">
                        <p class="text-sm font-bold text-slate-800"><i class="fas fa-broom mr-2 text-rose-600"></i>Bulk delete</p>
                        <p class="text-xs text-slate-500">Clear out old or read notifications to keep the table small.</p>
                        <div class="grid sm:grid-cols-2 gap-3">
                            <div><label class="al-l">Type</label>
                                <select name="del_type" class="al-f"><option value="">Any type</option>
                                    <?php foreach ($types as $tk => $tv): ?><option value="<?php echo $tk; ?>"><?php echo $tv[0]; ?></option><?php endforeach; ?>
                                </select></div>
                            <div><label class="al-l">Which ones</label>
                                <select name="del_read" class="al-f">
                                    <option value="read">Only read</option>
                                    <option value="old">Older than 30 days</option>
                                    <option value="unread">Only unread</option>
                                    <option value="">Everything</option>
                                </select></div>
                        </div>
                        <button type="submit" name="delete_filtered" class="al-btn px-8 py-3 w-full sm:w-auto" style="background:#e11d48;color:#fff"><i class="fas fa-trash-alt"></i> Delete Matching</button>
                    </form>
                </div>

                <?php echo alist_styles(); ?>
                <style>[x-cloak]{display:none!important}</style>
            </main>
        </div>
    </div>
</body>
</html>
