<?php
$page_title        = 'Quick URL Encrypt';
$page_breadcrumb   = ['IBO Ultra', 'Quick URL Encrypt'];
$page_heading      = 'Quick URL Encrypt';
$page_heading_icon = 'ph-magic-wand';
$page_module_pill  = 'IBO Ultra';
$page_active       = 'quick_url_encrypt';
require __DIR__ . '/includes/page_header.php';

$cfg = db_config();

$auto_panel = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://'
            . ($_SERVER['HTTP_HOST'] ?? 'localhost')
            . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
$default_url = !empty($cfg['panel_base_url']) ? (string)$cfg['panel_base_url'] : $auto_panel;

?>

<div class="card mb-6">
    <div class="card-head"><h3><i class="ph ph-link-simple"></i> Panel URL</h3></div>
    <form id="quick-enc-form" class="p-5 space-y-4">
        <div>
            <input class="form-input mono text-base" name="url" required
                   value="<?php echo h($default_url); ?>"
                   placeholder="https://your-panel.example/Ibo_ultra"
                   autocomplete="off"
                   autocapitalize="off"
                   spellcheck="false">
            <p class="text-[11px] text-dark-400 mt-1.5">
                Enter the full URL of your panel (no trailing slash unless it lives at the domain root).
            </p>
        </div>
        <div class="flex justify-end">
            <button class="btn-primary" type="submit">
                <i class="ph ph-magic-wand"></i> Encrypt &amp; Copy
            </button>
        </div>
    </form>
</div>

<div id="quick-enc-result" class="card hidden">
    <div class="card-head">
        <h3><i class="ph ph-check-circle text-emerald-400"></i> Activation Code</h3>
        <button type="button" id="quick-enc-copy" class="btn-primary text-xs">
            <i class="ph ph-copy"></i> Copy entire string
        </button>
    </div>
    <div class="p-5 space-y-4 text-sm">
        <!-- Hidden textarea: holds the canonical copy-target -->
        <textarea id="quick-enc-literal" class="hidden" readonly></textarea>

        <!-- Pretty rendering: highlight the full activation string -->
        <div class="rounded-lg border border-dark-700 bg-dark-900 p-4 mono text-xs leading-relaxed break-all">
            <span id="quick-enc-cipher" class="text-emerald-300"></span><!--
            --><span class="text-primary-400 font-extrabold text-base mx-1 px-1.5 py-0.5 rounded bg-primary-500/20 border border-primary-500/50">|</span><!--
            --><span id="quick-enc-iv" class="text-sky-300"></span>
        </div>

        <div class="rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-xs text-amber-200 flex items-start gap-2">
            <i class="ph ph-warning text-base flex-shrink-0 mt-0.5"></i>
            <p>
                Use the <strong>Copy entire string</strong> button to make sure you grab all of it,
                including the orange <span class="text-primary-400 font-extrabold">|</span> in the middle.
            </p>
        </div>
    </div>
</div>

<!-- =========================================================================
     Literal Verifier — paste a hex|hex string, panel decrypts it locally with
     the reseller constants and reports what URL it decodes to. Confirms in
     one click that a literal was made with THIS panel (or, if garbage, that
     the buyer used a different / stale panel to generate it). Nothing gets
     written server-side — pure diagnostic.
     ======================================================================== -->
<div class="card mb-6">
    <div class="card-head"><h3><i class="ph ph-magnifying-glass text-primary-400"></i> Verify a literal</h3></div>
    <form id="quick-verify-form" class="p-5 space-y-4">
        <div>
            <input class="form-input mono text-xs" name="literal" required
                   placeholder="paste ct_hex|iv_hex from an APK's PanelUrl.smali"
                   autocomplete="off" autocapitalize="off" spellcheck="false">
            <p class="text-[11px] text-dark-400 mt-1.5">
                Paste the string from <code>smali_classes2/com/PanelUrl.smali</code> line 14 to see what URL it will decrypt to on-device.
            </p>
        </div>
        <div class="flex justify-end">
            <button class="btn-primary" type="submit"><i class="ph ph-magnifying-glass"></i> Verify</button>
        </div>
    </form>
    <div id="quick-verify-result" class="p-5 pt-0 hidden">
        <div id="quick-verify-box" class="rounded-lg border p-4 flex items-start gap-3">
            <i id="quick-verify-icon" class="ph text-2xl flex-shrink-0"></i>
            <div class="min-w-0">
                <p id="quick-verify-title" class="font-semibold text-white"></p>
                <p id="quick-verify-detail" class="text-xs text-dark-300 mt-1 mono break-all"></p>
                <p id="quick-verify-hint" class="text-xs text-dark-400 mt-2"></p>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const form    = document.getElementById('quick-enc-form');
    const result  = document.getElementById('quick-enc-result');
    const ta      = document.getElementById('quick-enc-literal');
    const copyBtn = document.getElementById('quick-enc-copy');
    const vform   = document.getElementById('quick-verify-form');
    const vres    = document.getElementById('quick-verify-result');
    const vbox    = document.getElementById('quick-verify-box');
    const vicon   = document.getElementById('quick-verify-icon');
    const vtitle  = document.getElementById('quick-verify-title');
    const vdet    = document.getElementById('quick-verify-detail');
    const vhint   = document.getElementById('quick-verify-hint');

    function verifyRender(state, title, detail, hint) {
        vres.classList.remove('hidden');
        const style = {
            ok:   { box: 'border-emerald-500/40 bg-emerald-500/10', icon: 'ph-check-circle',   iconStyle: 'color:#22c55e' },
            warn: { box: 'border-amber-500/40 bg-amber-500/10',     icon: 'ph-warning-circle', iconStyle: 'color:#f39c12' },
            bad:  { box: 'border-red-500/40 bg-red-500/10',         icon: 'ph-x-circle',        iconStyle: 'color:#ef4444' },
        }[state];
        vbox.className = 'rounded-lg border p-4 flex items-start gap-3 ' + style.box;
        vicon.className = 'ph ' + style.icon + ' text-2xl flex-shrink-0';
        vicon.style.cssText = style.iconStyle;
        vtitle.textContent  = title;
        vdet.textContent    = detail || '';
        vhint.textContent   = hint || '';
    }

    vform.addEventListener('submit', async (e) => {
        e.preventDefault();
        const literal = vform.literal.value.trim();
        if (!literal) return;
        try {
            const r = await api.post('api/quick_url_encrypt.php', { action: 'verify', literal });
            if (r.ok) {
                const hasSlash = r.url.endsWith('/');
                if (!hasSlash) {
                    verifyRender('warn', 'Decrypts, but has no trailing slash',
                        r.url,
                        'The app will fetch broken URLs like ".../slugvpns.php". Re-encrypt the URL with a trailing / and re-bake.');
                } else {
                    verifyRender('ok', 'Decrypts cleanly against this panel\'s constants', r.url,
                        'This literal WAS generated by this panel (or one with the exact same reseller constants). Safe to install.');
                }
            } else {
                verifyRender('bad', 'Decrypts to garbage', r.reason || '',
                    'Almost certainly generated by a different panel (v11–v14, or a stale install without the reseller-variant apksec_constants + crypto). Re-encrypt on THIS panel.');
            }
        } catch (err) {
            verifyRender('bad', 'Verify failed', err.message || '', '');
        }
    });

    async function copyToClipboard(text) {
        if (navigator.clipboard && window.isSecureContext) {
            try { await navigator.clipboard.writeText(text); return true; } catch (_) {}
        }
        // Fallback: select + execCommand
        ta.select();
        ta.setSelectionRange(0, ta.value.length);
        try { return document.execCommand('copy'); } catch (_) { return false; }
    }

    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        const url = form.url.value.trim();
        if (!url) { toast('Enter a URL', 'error'); return; }
        try {
            const r = await api.post('api/quick_url_encrypt.php', { action: 'encrypt', url });
            ta.value = r.literal;
            // Split for the highlighted display
            const parts = (r.literal || '').split('|');
            document.getElementById('quick-enc-cipher').textContent = parts[0] || '';
            document.getElementById('quick-enc-iv').textContent     = parts[1] || '';
            result.classList.remove('hidden');
            const ok = await copyToClipboard(r.literal);
            toast(ok ? 'Encrypted and copied to clipboard' : 'Encrypted — press Copy to grab it', ok ? 'success' : 'info');
        } catch (err) {
            toast(err.message || 'Encrypt failed', 'error');
        }
    });

    copyBtn.addEventListener('click', async () => {
        const ok = await copyToClipboard(ta.value);
        toast(ok ? 'Copied to clipboard' : 'Could not copy — select manually', ok ? 'success' : 'warn');
    });
})();
</script>

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