<!DOCTYPE html>
<?php
/* Owner-only plans/packages console (master-detail).
   Vars: $baseUrl, $assetsUrl, $user, $plans, $capabilities, $iconChoices, $colorChoices, $token */
if (!isset($baseUrl)) $baseUrl = '';
if (!isset($assetsUrl)) $assetsUrl = rtrim($baseUrl, '/') . '/assets';
$b = rtrim($baseUrl, '/');
$plans = $plans ?? [];
$capabilities = $capabilities ?? [];
$iconChoices = $iconChoices ?? ['box-seam'];
$colorChoices = $colorChoices ?? ['#64748b'];
$groups = [];
foreach ($capabilities as $key => $meta) { $groups[$meta['group'] ?? 'Capabilities'][$key] = $meta; }
/** A small tier badge (gradient derived from the plan colour). */
$badge = static function (string $icon, string $color, string $size = 'md'): string {
    $cls = $size === 'sm' ? 'pl-badge sm' : 'pl-badge';
    return '<span class="' . $cls . '" style="--c:' . htmlspecialchars($color) . '"><i class="bi bi-'
        . htmlspecialchars($icon) . '"></i></span>';
};
$hint = static fn (string $t): string =>
    '<span class="pl-hint" tabindex="0" title="' . htmlspecialchars($t, ENT_QUOTES) . '">?</span>';
?>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars(\PpPhp\Core\Brand::name()) ?> · Plans &amp; packages</title>
    <?php include constant('BASE_PATH') . '/core/views/favicon.php'; ?>
    <link href="<?= $assetsUrl ?>/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="<?= $assetsUrl ?>/icons/bootstrap-icons.css" rel="stylesheet">
    <?php include constant('BASE_PATH') . '/core/views/theme-head.php'; ?>
    <link href="<?= $assetsUrl ?>/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <script src="<?= $assetsUrl ?>/sweetalert2/sweetalert2.min.js"></script>
    <style>
        body { background: var(--pp-app-bg, #f5f6fa); color: var(--pp-text, #172033); }
        .pl-topbar { background: var(--pp-surface, #fff); border-bottom: 1px solid var(--pp-border, #e6e9f0);
            padding: .7rem 1rem; display: flex; align-items: center; gap: .8rem; position: sticky; top: 0; z-index: 1030; }
        .pl-topbar .brand { font-weight: 800; display: flex; align-items: center; gap: .5rem; color: var(--pp-text); text-decoration: none; }
        .pl-topbar .brand .bi { color: var(--pp-accent, #4f46e5); }
        .pl-wrap { max-width: 1180px; margin: 1.2rem auto 3rem; padding: 0 1.1rem;
            display: grid; grid-template-columns: 300px 1fr; gap: 1.1rem; align-items: start; }
        @media (max-width: 860px) { .pl-wrap { grid-template-columns: 1fr; } }
        .pl-card { background: var(--pp-surface, #fff); border: 1px solid var(--pp-border, #e6e9f0);
            border-radius: 16px; padding: 1.1rem 1.15rem; }
        .pl-hero { background: linear-gradient(135deg, color-mix(in srgb, var(--pp-accent) 12%, var(--pp-surface)), color-mix(in srgb, var(--pp-accent) 3%, var(--pp-surface)));
            border: 1px solid color-mix(in srgb, var(--pp-accent) 20%, transparent); border-radius: 14px; padding: .9rem 1.15rem; margin: 1.1rem auto 0; max-width: 1180px; }
        .pl-hero h1 { font-size: 1.1rem; font-weight: 800; margin: 0 0 .15rem; display: flex; align-items: center; gap: .5rem; }
        .pl-hero p { margin: 0; color: var(--pp-text-muted, #64748b); font-size: .84rem; }
        .pl-hint { display: inline-flex; align-items: center; justify-content: center; width: 15px; height: 15px;
            margin-left: .2rem; border-radius: 50%; background: var(--pp-surface-soft, #f1f5f9);
            color: var(--pp-text-muted, #94a3b8); font-size: .62rem; font-weight: 800; cursor: help; vertical-align: middle; }
        .pl-hint:hover, .pl-hint:focus-visible { background: color-mix(in srgb, var(--pp-accent, #4f46e5) 16%, transparent); color: var(--pp-accent, #4f46e5); outline: none; }

        /* ── Tier badge ── */
        .pl-badge { flex: 0 0 auto; width: 40px; height: 40px; border-radius: 12px; display: inline-flex; align-items: center;
            justify-content: center; color: #fff; font-size: 18px;
            background: linear-gradient(140deg, var(--c, #64748b), color-mix(in srgb, var(--c, #64748b) 55%, #000));
            box-shadow: 0 4px 12px color-mix(in srgb, var(--c, #64748b) 40%, transparent); }
        .pl-badge.sm { width: 30px; height: 30px; border-radius: 9px; font-size: 14px; box-shadow: none; }
        .pl-badge.xl { width: 56px; height: 56px; border-radius: 16px; font-size: 26px; }

        /* ── Left: plan list (the tabs) ── */
        .pl-side { position: sticky; top: 5rem; display: flex; flex-direction: column; }
        .pl-side-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: .7rem; }
        .pl-side-head .t { font-size: .72rem; font-weight: 800; letter-spacing: .06em; text-transform: uppercase; color: var(--pp-text-muted, #94a3b8); }
        .pl-new { border: 0; background: var(--pp-accent, #4f46e5); color: #fff; border-radius: 9px; font-size: .78rem; font-weight: 700;
            padding: .32rem .7rem; cursor: pointer; display: inline-flex; align-items: center; gap: .35rem; }
        .pl-new:hover { filter: brightness(1.06); }
        .pl-list { display: flex; flex-direction: column; gap: .5rem; }
        .pl-tab { width: 100%; text-align: left; border: 1px solid var(--pp-border, #e6e9f0); background: var(--pp-surface, #fff);
            border-radius: 13px; padding: .7rem .8rem; cursor: pointer; display: flex; align-items: center; gap: .7rem; transition: border-color .12s, box-shadow .12s, transform .06s; }
        .pl-tab:hover { border-color: color-mix(in srgb, var(--pp-accent, #4f46e5) 40%, var(--pp-border)); }
        .pl-tab.active { border-color: var(--pp-accent, #4f46e5); box-shadow: 0 0 0 3px color-mix(in srgb, var(--pp-accent, #4f46e5) 14%, transparent); }
        .pl-tab .meta { flex: 1; min-width: 0; }
        .pl-tab .meta .nm { font-weight: 800; font-size: .92rem; display: flex; align-items: center; gap: .4rem; }
        .pl-tab .meta .nm code { font-size: .68rem; color: var(--pp-text-muted, #94a3b8); font-weight: 600; }
        .pl-tab .meta .ct { font-size: .74rem; color: var(--pp-text-muted, #64748b); margin-top: 1px; }
        .pl-tab .chev { color: var(--pp-text-muted, #cbd5e1); }
        .pl-side-foot { margin-top: .9rem; padding-top: .8rem; border-top: 1px dashed var(--pp-border, #e6e9f0); text-align: center; }
        .pl-reset { border: 1px solid var(--pp-border, #e2e8f0); background: var(--pp-surface, #fff); color: var(--pp-text-muted, #64748b);
            border-radius: 8px; font-size: .74rem; font-weight: 700; padding: .3rem .7rem; cursor: pointer; display: inline-flex; align-items: center; gap: .35rem; }
        .pl-reset:hover { border-color: #f43f5e; color: #e11d48; }

        /* ── Right: editor ── */
        .pl-ed-head { display: flex; align-items: center; gap: .8rem; margin-bottom: 1rem; }
        .pl-ed-head .t { font-size: 1.05rem; font-weight: 800; }
        .pl-ed-head .s { font-size: .8rem; color: var(--pp-text-muted, #64748b); }
        .pl-field { margin-bottom: .9rem; }
        .pl-field label { display: block; font-weight: 700; font-size: .8rem; margin-bottom: .3rem; }
        .pl-icon-grid { display: flex; flex-wrap: wrap; gap: .4rem; }
        .pl-icon-grid button { width: 40px; height: 40px; border-radius: 10px; border: 1px solid var(--pp-border, #e2e8f0);
            background: var(--pp-surface, #fff); color: var(--pp-text-muted, #64748b); font-size: 16px; cursor: pointer; transition: all .12s; }
        .pl-icon-grid button:hover { border-color: var(--pp-accent, #4f46e5); color: var(--pp-accent, #4f46e5); }
        .pl-icon-grid button.sel { border-color: var(--pp-accent, #4f46e5); color: #fff; background: var(--pp-accent, #4f46e5); box-shadow: 0 0 0 3px color-mix(in srgb, var(--pp-accent) 15%, transparent); }
        .pl-color-grid { display: flex; flex-wrap: wrap; gap: .45rem; }
        .pl-color-grid button { width: 30px; height: 30px; border-radius: 50%; border: 2px solid transparent; cursor: pointer; position: relative; }
        .pl-color-grid button.sel { border-color: var(--pp-text, #172033); box-shadow: 0 0 0 3px var(--pp-surface), 0 0 0 4px color-mix(in srgb, var(--pp-text) 20%, transparent); }
        .pl-capgroup { border: 1px solid var(--pp-border, #e2e8f0); border-radius: 12px; padding: .75rem .9rem; margin-bottom: .7rem; }
        .pl-capgroup > .g { font-size: .7rem; font-weight: 800; text-transform: uppercase; letter-spacing: .05em; color: var(--pp-text-muted, #94a3b8); margin-bottom: .5rem; }
        .pl-cap { display: flex; align-items: center; gap: .65rem; padding: .38rem 0; }
        .pl-cap .ic { flex: 0 0 32px; width: 32px; height: 32px; border-radius: 9px; display: flex; align-items: center; justify-content: center;
            background: color-mix(in srgb, var(--pp-accent, #4f46e5) 12%, var(--pp-surface)); color: var(--pp-accent, #4f46e5); }
        .pl-cap .t { flex: 1; min-width: 0; }
        .pl-cap .t strong { display: block; font-size: .85rem; }
        .pl-cap .t small { color: var(--pp-text-muted, #64748b); font-size: .76rem; }
        .pl-switch { position: relative; flex: 0 0 auto; width: 42px; height: 24px; }
        .pl-switch input { position: absolute; opacity: 0; width: 0; height: 0; }
        .pl-switch .tr { position: absolute; inset: 0; border-radius: 999px; background: var(--pp-border-strong, #cbd5e1); transition: background .16s; cursor: pointer; }
        .pl-switch .tr::after { content: ''; position: absolute; top: 3px; left: 3px; width: 18px; height: 18px; border-radius: 50%; background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,.28); transition: transform .16s; }
        .pl-switch input:checked + .tr { background: #10b981; }
        .pl-switch input:checked + .tr::after { transform: translateX(18px); }
        .pl-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
        @media (max-width: 560px) { .pl-grid-2 { grid-template-columns: 1fr; } }
        .pl-del { border: 1px solid color-mix(in srgb, #f43f5e 40%, transparent); background: transparent; color: #e11d48;
            border-radius: 9px; font-size: .82rem; font-weight: 700; padding: .5rem .9rem; cursor: pointer; }
        .pl-del:hover { background: color-mix(in srgb, #f43f5e 10%, transparent); }
    </style>
</head>
<body>
<div class="pl-topbar">
    <a href="<?= $b ?>/licensing/server" class="brand"><i class="bi bi-arrow-left-short"></i> Licence server</a>
    <span style="color:var(--pp-text-muted);font-size:.85rem">/ Plans &amp; packages</span>
    <div class="ms-auto d-flex align-items-center gap-2" style="margin-left:auto">
        <a href="<?= $b ?>/help/licensing" target="_blank" rel="noopener" class="btn btn-sm btn-outline-secondary" data-tip="The licence-server guide"><i class="bi bi-question-circle"></i> Guide</a>
        <?php include constant('BASE_PATH') . '/core/views/theme-toggle.php'; ?>
    </div>
</div>

<div class="pl-hero">
    <h1><i class="bi bi-box-seam"></i> Plans &amp; packages</h1>
    <p>Pick a plan on the left to edit it, or add a new one. Each plan's capabilities travel to the client in its signed lease — <strong>Premium</strong> is where the server AI, Email and SMS live.</p>
</div>

<div class="pl-wrap">
    <!-- Left: plan list = the tabs -->
    <aside class="pl-side pl-card">
        <div class="pl-side-head">
            <span class="t">Plans (<?= count($plans) ?>)</span>
            <button type="button" class="pl-new" id="plNew" data-tip="Start a brand-new plan"><i class="bi bi-plus-lg"></i> New</button>
        </div>
        <div class="pl-list" id="plList">
            <?php foreach ($plans as $p): $__on = count(array_filter($p['capabilities'])); ?>
            <button type="button" class="pl-tab" data-plan='<?= htmlspecialchars(json_encode($p), ENT_QUOTES) ?>'>
                <?= $badge($p['icon'], $p['color']) ?>
                <span class="meta">
                    <span class="nm"><?= htmlspecialchars($p['name']) ?> <code><?= htmlspecialchars($p['slug']) ?></code></span>
                    <span class="ct"><?= $__on ?> capabilit<?= $__on === 1 ? 'y' : 'ies' ?> · #<?= (int) $p['order'] ?></span>
                </span>
                <i class="bi bi-chevron-right chev"></i>
            </button>
            <?php endforeach; ?>
        </div>
        <div class="pl-side-foot">
            <button type="button" class="pl-reset" id="btnReset" data-tip="Restore the shipped Standard / Pro / Premium plans (with confirmation)">
                <i class="bi bi-arrow-counterclockwise"></i> Reset to defaults
            </button>
        </div>
    </aside>

    <!-- Right: editor -->
    <section class="pl-card">
        <div class="pl-ed-head">
            <span id="edBadge"><?= $badge('rocket-takeoff-fill', '#4f46e5', '') ?></span>
            <div>
                <div class="t" id="edTitle">New plan</div>
                <div class="s">Name it, choose a badge, and switch on what it grants.</div>
            </div>
        </div>
        <form id="plForm">
            <input type="hidden" name="slug" id="plSlug" value="">
            <input type="hidden" name="icon" id="plIcon" value="rocket-takeoff-fill">
            <input type="hidden" name="color" id="plColor" value="#4f46e5">

            <div class="pl-grid-2">
                <div class="pl-field">
                    <label for="plName">Plan name <?= $hint('What the plan is called (Standard, Pro, Premium…). Shown to customers on their licence; the internal id is derived from it.') ?></label>
                    <input class="form-control" id="plName" name="name" maxlength="40" placeholder="e.g. Premium" required>
                </div>
                <div class="pl-field">
                    <label for="plOrder">Sort order <?= $hint('Lower numbers list first (1 = top). Controls display order only.') ?></label>
                    <input class="form-control" id="plOrder" name="order" type="number" min="1" value="99">
                </div>
            </div>

            <div class="pl-field">
                <label for="plDesc">Description <?= $hint('A short line describing the plan — for your own reference here and, later, on customer-facing pages.') ?></label>
                <input class="form-control" id="plDesc" name="description" maxlength="160" placeholder="Everything, including the server AI, Email and SMS.">
            </div>

            <div class="pl-grid-2">
                <div class="pl-field">
                    <label>Badge icon <?= $hint('The icon that identifies this plan everywhere it appears. Pick one that signals the tier — a gem or trophy reads as premium.') ?></label>
                    <div class="pl-icon-grid" id="plIconGrid">
                        <?php foreach ($iconChoices as $ic): ?>
                        <button type="button" data-icon="<?= htmlspecialchars($ic) ?>" title="<?= htmlspecialchars($ic) ?>"><i class="bi bi-<?= htmlspecialchars($ic) ?>"></i></button>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="pl-field">
                    <label>Badge colour <?= $hint('The accent colour of the plan badge. A gradient is derived from it automatically.') ?></label>
                    <div class="pl-color-grid" id="plColorGrid">
                        <?php foreach ($colorChoices as $cc): ?>
                        <button type="button" data-color="<?= htmlspecialchars($cc) ?>" style="background:<?= htmlspecialchars($cc) ?>" title="<?= htmlspecialchars($cc) ?>"></button>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <label class="fw-bold" style="font-size:.82rem">Capabilities <?= $hint('Server-side features a licence on this plan may use. Each is enforced by its own feature over time; turning it on here grants the entitlement, carried in the signed lease.') ?></label>
            <?php foreach ($groups as $gname => $caps): ?>
            <div class="pl-capgroup">
                <div class="g"><?= htmlspecialchars($gname) ?></div>
                <?php foreach ($caps as $key => $meta): ?>
                <div class="pl-cap">
                    <span class="ic"><i class="bi bi-<?= htmlspecialchars($meta['icon']) ?>"></i></span>
                    <span class="t"><strong><?= htmlspecialchars($meta['label']) ?> <?= $hint($meta['desc']) ?></strong><small><?= htmlspecialchars($meta['desc']) ?></small></span>
                    <label class="pl-switch" title="<?= htmlspecialchars($meta['desc']) ?>">
                        <input type="checkbox" class="plCap" data-cap="<?= htmlspecialchars($key) ?>">
                        <span class="tr"></span>
                    </label>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endforeach; ?>

            <label class="fw-bold mt-3" style="font-size:.82rem">Build limits <?= $hint('How many server-side builds a licence on this plan may run per window. Blank = inherit the global default; 0 = unlimited; a number = the cap. All four are enforced together, so a build is allowed only if every set window still has room.') ?></label>
            <div class="row g-2">
                <div class="col-6 col-md-3">
                    <label for="plBLHour" class="small text-muted">Per hour</label>
                    <input class="form-control plBL" id="plBLHour" data-window="hour" type="number" min="0" placeholder="—">
                </div>
                <div class="col-6 col-md-3">
                    <label for="plBLDay" class="small text-muted">Per day</label>
                    <input class="form-control plBL" id="plBLDay" data-window="day" type="number" min="0" placeholder="—">
                </div>
                <div class="col-6 col-md-3">
                    <label for="plBLWeek" class="small text-muted">Per week</label>
                    <input class="form-control plBL" id="plBLWeek" data-window="week" type="number" min="0" placeholder="—">
                </div>
                <div class="col-6 col-md-3">
                    <label for="plBLMonth" class="small text-muted">Per month</label>
                    <input class="form-control plBL" id="plBLMonth" data-window="month" type="number" min="0" placeholder="—">
                </div>
            </div>
            <div class="small text-muted mt-1">Blank inherits the global default · 0 = unlimited · a number caps that window.</div>

            <label class="fw-bold mt-3" style="font-size:.82rem">Virtual Database size <?= $hint('The maximum size of ONE Virtual Database on this plan, in MB. Hard-enforced by the engine (SQLite max_page_count) — writes past it are refused, reads still work, and raising the plan lifts the limit instantly. Blank = the shipped tier default (Standard 5 · Pro 15 · Premium 25); 0 = unlimited.') ?></label>
            <div class="row g-2">
                <div class="col-6 col-md-4">
                    <label for="plMaxDbMb" class="small text-muted">Max size per database (MB)</label>
                    <input class="form-control" id="plMaxDbMb" type="number" min="0" placeholder="—">
                </div>
            </div>
            <div class="small text-muted mt-1">Blank = tier default · 0 = unlimited · a number caps each database at that many MB.</div>

            <div class="d-flex align-items-center gap-2 mt-3">
                <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Save plan</button>
                <button type="button" class="btn btn-link text-muted" id="plClear">Clear</button>
                <button type="button" class="pl-del ms-auto" id="plDelete" style="display:none"><i class="bi bi-trash"></i> Delete plan</button>
            </div>
        </form>
    </section>
</div>

<script>
(function () {
    var b = <?= json_encode($b) ?>, token = <?= json_encode($token) ?>;
    var ICONS = <?= json_encode(array_values($iconChoices)) ?>;
    var form = document.getElementById('plForm');
    var $ = function (id) { return document.getElementById(id); };
    function esc(s) { return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) { return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]; }); }
    function post(path, body) {
        return fetch(b + path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin',
            body: JSON.stringify(Object.assign({ _token: token }, body)) }).then(function (r) { return r.json(); });
    }
    function toast(icon, title) { Swal.fire({ toast: true, position: 'top-end', icon: icon, title: title, showConfirmButton: false, timer: 2400, timerProgressBar: true }); }

    function paintBadge() {
        var el = $('edBadge');
        el.innerHTML = '<span class="pl-badge xl" style="--c:' + esc($('plColor').value) + '"><i class="bi bi-' + esc($('plIcon').value) + '"></i></span>';
    }
    function selectIcon(icon) {
        $('plIcon').value = icon;
        Array.prototype.forEach.call($('plIconGrid').children, function (btn) { btn.classList.toggle('sel', btn.dataset.icon === icon); });
        paintBadge();
    }
    function selectColor(color) {
        $('plColor').value = color;
        Array.prototype.forEach.call($('plColorGrid').children, function (btn) { btn.classList.toggle('sel', btn.dataset.color === color); });
        paintBadge();
    }
    $('plIconGrid').addEventListener('click', function (e) { var btn = e.target.closest('button[data-icon]'); if (btn) selectIcon(btn.dataset.icon); });
    $('plColorGrid').addEventListener('click', function (e) { var btn = e.target.closest('button[data-color]'); if (btn) selectColor(btn.dataset.color); });

    function loadPlan(p) {
        $('plSlug').value = p.slug;
        $('plName').value = p.name;
        $('plDesc').value = p.description || '';
        $('plOrder').value = p.order || 99;
        selectIcon(p.icon || 'rocket-takeoff-fill');
        selectColor(p.color || '#4f46e5');
        Array.prototype.forEach.call(document.querySelectorAll('.plCap'), function (c) { c.checked = !!(p.capabilities && p.capabilities[c.dataset.cap]); });
        Array.prototype.forEach.call(document.querySelectorAll('.plBL'), function (c) {
            var v = p.build_limits ? p.build_limits[c.dataset.window] : null;
            c.value = (v === null || v === undefined) ? '' : v;
        });
        $('plMaxDbMb').value = (p.max_db_mb === null || p.max_db_mb === undefined) ? '' : p.max_db_mb;
        $('edTitle').textContent = 'Edit plan — ' + p.name;
        $('plDelete').style.display = '';
        setActive(p.slug);
    }
    function newPlan() {
        form.reset(); $('plSlug').value = '';
        selectIcon('rocket-takeoff-fill'); selectColor('#4f46e5');
        Array.prototype.forEach.call(document.querySelectorAll('.plCap'), function (c) { c.checked = false; });
        Array.prototype.forEach.call(document.querySelectorAll('.plBL'), function (c) { c.value = ''; });
        $('plMaxDbMb').value = '';
        $('edTitle').textContent = 'New plan';
        $('plDelete').style.display = 'none';
        setActive(null);
        $('plName').focus();
    }
    function setActive(slug) {
        Array.prototype.forEach.call(document.querySelectorAll('.pl-tab'), function (t) {
            var p = JSON.parse(t.getAttribute('data-plan'));
            t.classList.toggle('active', slug != null && p.slug === slug);
        });
    }

    document.getElementById('plList').addEventListener('click', function (e) {
        var t = e.target.closest('.pl-tab'); if (!t) return;
        loadPlan(JSON.parse(t.getAttribute('data-plan')));
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });
    $('plNew').addEventListener('click', newPlan);
    $('plClear').addEventListener('click', newPlan);

    form.addEventListener('submit', function (e) {
        e.preventDefault();
        var caps = {}; Array.prototype.forEach.call(document.querySelectorAll('.plCap'), function (c) { caps[c.dataset.cap] = c.checked; });
        var buildLimits = {}; Array.prototype.forEach.call(document.querySelectorAll('.plBL'), function (c) {
            buildLimits[c.dataset.window] = c.value === '' ? null : (parseInt(c.value, 10) || 0);
        });
        var body = { slug: $('plSlug').value, name: $('plName').value, description: $('plDesc').value,
            order: parseInt($('plOrder').value, 10) || 99, icon: $('plIcon').value, color: $('plColor').value,
            capabilities: caps, build_limits: buildLimits,
            max_db_mb: $('plMaxDbMb').value === '' ? '' : (parseInt($('plMaxDbMb').value, 10) || 0) };
        if (!body.name.trim()) { toast('error', 'A plan name is required.'); return; }
        post('/licensing/plans/save', body).then(function (j) {
            if (j && j.success) { toast('success', 'Plan saved.'); setTimeout(function () { location.reload(); }, 700); }
            else { Swal.fire({ icon: 'error', title: 'Could not save', text: (j && j.message) || 'Unknown error' }); }
        });
    });

    $('plDelete').addEventListener('click', function () {
        var slug = $('plSlug').value; if (!slug) return;
        Swal.fire({ icon: 'warning', title: 'Delete “' + $('plName').value + '”?', text: 'Licences already on this plan keep their name until reissued.',
            showCancelButton: true, confirmButtonText: 'Delete', confirmButtonColor: '#ef4444' }).then(function (r) {
            if (!r.isConfirmed) return;
            post('/licensing/plans/delete', { slug: slug }).then(function (j) {
                if (j && j.success) { toast('success', 'Deleted.'); setTimeout(function () { location.reload(); }, 500); }
                else { Swal.fire({ icon: 'error', title: 'Could not delete', text: (j && j.message) || '' }); }
            });
        });
    });

    document.getElementById('btnReset').addEventListener('click', function () {
        Swal.fire({ icon: 'warning', title: 'Reset to default plans?', html: 'Restores <b>Standard</b>, <b>Pro</b> and <b>Premium</b> with their badges. Any custom plans are removed.',
            showCancelButton: true, confirmButtonText: 'Reset', confirmButtonColor: '#e11d48' }).then(function (r) {
            if (!r.isConfirmed) return;
            post('/licensing/plans/reset', {}).then(function (j) { if (j && j.success) { toast('success', 'Reset.'); setTimeout(function () { location.reload(); }, 600); } });
        });
    });

    // Open the first plan by default (or the New-plan form when there are none).
    var first = document.querySelector('.pl-tab');
    if (first) loadPlan(JSON.parse(first.getAttribute('data-plan'))); else newPlan();
}());
</script>
</body>
</html>
