<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title"><i class="fa fa-store"></i> Vanity widget — "claim your name" landing</h3>
    </div>
    <div class="panel-body">
        <p class="text-muted" style="margin-bottom:18px;">
            A standalone 2-file landing you drop on any marketing domain (hundreds of them). It pulls your sellable
            vanity domains from WHMCS, live-checks <code>name.domain</code> / <code>name@domain</code>, and sends the
            visitor to the cart with the name + domain pre-filled. The browser talks only to the widget's own
            <code>proxy.php</code> (which holds the key &amp; caches answers) — the key never reaches the visitor.
        </p>

        {* ---- 1. API key ---- *}
        <h4><i class="fa fa-key text-warning"></i> 1. Shared API key</h4>
        <div class="row" style="margin-bottom:6px;">
            <div class="col-md-8">
                <div class="input-group">
                    <input type="text" class="form-control" id="vw-key" value="{$vanity_api_key|escape}" readonly style="font-family:monospace;">
                    <span class="input-group-btn">
                        <button class="btn btn-default puq-copy" data-copy="{$vanity_api_key|escape}" title="Copy"><i class="fa fa-copy"></i></button>
                        <button class="btn btn-warning" id="vw-regen" title="Generate a new key (you must then update proxy.php on every domain)"><i class="fa fa-sync"></i> Regenerate</button>
                    </span>
                </div>
            </div>
        </div>
        <p class="help-block">Used by <code>proxy.php</code> to authenticate to your WHMCS. Regenerating invalidates all deployed widgets until you update them.</p>

        <hr>

        {* ---- 2. Product id + config ---- *}
        <h4><i class="fa fa-cube text-primary"></i> 2. Your vanity product</h4>
        <div class="row">
            <div class="col-md-6">
                <label>Vanity product</label>
                <select class="form-control" id="vw-pid"><option value="">Loading products…</option></select>
                <p class="help-block" id="vw-pid-help">Pick the vanity product to sell — grouped by product group (only this module's vanity products are listed).</p>
            </div>
        </div>

        <p style="margin-top:10px;"><strong>Paste this into the top of <code>proxy.php</code></strong> (identical on every domain):</p>
        <pre id="vw-config" style="background:#1e1e1e;color:#dcdcdc;border-radius:6px;padding:14px;">const WHMCS_URL  = '{$vanity_whmcs_url|escape}';
const API_KEY    = '{$vanity_api_key|escape}';
const PRODUCT_ID = 0;</pre>
        <button class="btn btn-default btn-sm puq-copy" id="vw-copy-config" data-copy=""><i class="fa fa-copy"></i> Copy config</button>

        <hr>

        {* ---- Cart behaviour ---- *}
        <h4><i class="fa fa-shopping-cart text-info"></i> Cart behaviour <span id="vw-cart-saved" class="text-success" style="display:none;font-size:13px;"><i class="fa fa-check"></i> saved</span></h4>
        <p class="text-muted">What the widget's <strong>Get it</strong> button does (applies to all deployed widgets — no re-upload needed).</p>
        <label style="display:block;font-weight:normal;margin-bottom:6px;">
            <input type="radio" name="vw-cart-mode" value="config" {if $vanity_cart_mode neq 'checkout'}checked{/if}>
            <strong>Product config page</strong> — open the order page with name + domain pre-filled; the customer reviews and continues. <em>(default, as now)</em>
        </label>
        <label style="display:block;font-weight:normal;">
            <input type="radio" name="vw-cart-mode" value="checkout" {if $vanity_cart_mode eq 'checkout'}checked{/if}>
            <strong>Skip configuration</strong> — add to cart with everything pre-filled and land straight on the cart (review &amp; pay), skipping the product-config page.
        </label>

        <hr>

        {* ---- 3. Download files ---- *}
        <h4><i class="fa fa-download text-success"></i> 3. Download the 2 files</h4>
        <p class="text-muted">Upload <strong>both</strong> to the web root of each domain. <code>proxy.php</code> is downloaded with your WHMCS URL + key (and pid, if set) already filled in.</p>
        <p>
            <a class="btn btn-success" id="vw-dl-proxy" href="#"><i class="fa fa-file-code"></i> Download proxy.php</a>
            <a class="btn btn-default" id="vw-dl-index" href="{$meta.admin_module_url}&amp;ajax=vanityWidgetFile&amp;file=index"><i class="fa fa-file"></i> Download index.html</a>
        </p>
        <p class="help-block">Source also lives in the module package: <code>vanity-shop/</code> (proxy.php, index.html, README.md).</p>

        <hr>

        {* ---- 4. Steps ---- *}
        <h4><i class="fa fa-list-ol"></i> 4. How it works</h4>
        <ol class="text-muted" style="max-width:760px;">
            <li>The product must be a <strong>Vanity</strong> product and its group must have <em>Vanity domains</em> configured.</li>
            <li>Make sure the product has the <code>vanity_domain</code> Configurable Option and the <code>vanity_name</code> Custom Field (the product's <em>Config options</em> tab creates them).</li>
            <li>Set the pid above, download both files, edit nothing else, upload them to a domain root.</li>
            <li>The landing checks availability via <code>proxy.php</code> → your API endpoint, then on <em>Get it</em> redirects to
                <code>cart.php?a=add&amp;pid=…&amp;customfield[…]=name&amp;configoption[…]=domain</code> with everything pre-filled.</li>
        </ol>
        <p class="help-block">API endpoint (for reference): <code>{$vanity_api_url|escape}</code></p>
    </div>
</div>

{literal}
<script>
(function(){
    var baseUrl = '{/literal}{$meta.admin_module_url}&ajax={literal}';
    var $key = document.getElementById('vw-key');
    var $pid = document.getElementById('vw-pid');
    var $cfg = document.getElementById('vw-config');
    var $dlProxy = document.getElementById('vw-dl-proxy');
    var $copyCfg = document.getElementById('vw-copy-config');

    function buildConfig(){
        var pid = parseInt($pid.value, 10) || 0;
        var txt = "const WHMCS_URL  = '" + (window._vwUrl || '') + "';\n" +
                  "const API_KEY    = '" + ($key.value || '') + "';\n" +
                  "const PRODUCT_ID = " + pid + ";";
        $cfg.textContent = txt;
        $copyCfg.setAttribute('data-copy', txt);
        $dlProxy.href = baseUrl + 'vanityWidgetFile&file=proxy' + (pid > 0 ? '&pid=' + pid : '');
    }
    // Stash the WHMCS URL from the rendered config (first line).
    window._vwUrl = ($cfg.textContent.match(/WHMCS_URL\s*=\s*'([^']*)'/) || [,''])[1];

    $pid.addEventListener('change', buildConfig);

    function loadProducts(){
        jQuery.ajax({ url: baseUrl + 'getVanityProducts', dataType: 'json',
            success: function(r){
                if (!r || r.status !== 'success' || !r.data || !r.data.length){
                    $pid.innerHTML = '<option value="">— no vanity products found —</option>';
                    document.getElementById('vw-pid-help').innerHTML = 'No vanity products found. Create a product on this module with Deployment mode = Vanity.';
                    buildConfig();
                    return;
                }
                $pid.innerHTML = '<option value="">— select a product —</option>';
                var total = 0, lastPid = 0;
                r.data.forEach(function(g){
                    var og = document.createElement('optgroup');
                    og.label = g.group_name || 'Ungrouped';
                    (g.products || []).forEach(function(p){
                        var o = document.createElement('option');
                        o.value = p.pid; o.textContent = p.name + '  (#' + p.pid + ')';
                        og.appendChild(o); total++; lastPid = p.pid;
                    });
                    $pid.appendChild(og);
                });
                if (total === 1) $pid.value = lastPid;   // single product → preselect
                buildConfig();
            },
            error: function(){ $pid.innerHTML = '<option value="">— failed to load —</option>'; buildConfig(); }
        });
    }
    loadProducts();

    Array.prototype.forEach.call(document.querySelectorAll('input[name="vw-cart-mode"]'), function(r){
        r.addEventListener('change', function(){
            jQuery.ajax({ url: baseUrl + 'vanityWidgetSetCartMode', type: 'POST', data: { mode: this.value }, dataType: 'json',
                success: function(rr){
                    if (rr.status === 'success'){
                        var s = document.getElementById('vw-cart-saved'); s.style.display = 'inline';
                        setTimeout(function(){ s.style.display = 'none'; }, 1800);
                    } else if (window.showNotification) showNotification(rr.msg || 'Failed', 'error');
                },
                error: function(){ if (window.showNotification) showNotification('Request failed.', 'error'); }
            });
        });
    });

    document.getElementById('vw-regen').addEventListener('click', function(){
        var btn = this;
        if (!confirm('Generate a new key? Every deployed proxy.php must be updated with the new key afterwards.')) return;
        if (window.btnSpinner) btnSpinner(btn, 'Generating…');
        jQuery.ajax({ url: baseUrl + 'vanityWidgetRegenerateKey', type: 'POST', dataType: 'json',
            success: function(r){
                if (r.status === 'success' && r.data && r.data.key) {
                    $key.value = r.data.key;
                    document.querySelector('.puq-copy[title="Copy"]').setAttribute('data-copy', r.data.key);
                    buildConfig();
                    if (window.showNotification) showNotification('New key generated. Update proxy.php on your domains.', 'success');
                } else if (window.showNotification) showNotification(r.msg || 'Failed', 'error');
            },
            error: function(){ if (window.showNotification) showNotification('Request failed.', 'error'); },
            complete: function(){ if (window.btnRestore) btnRestore(btn, 'sync', 'Regenerate'); }
        });
    });
})();
</script>
{/literal}
