{include file='modules/servers/puqWebHosting/templates/header.tpl'}

{*
   Vanity single-mailbox settings. ONE fixed mailbox (name@provider-domain),
   rendered inside ONE card (matching web_settings.tpl) so the page always has
   a content card even when a section is permission-gated off.
   Sections: change password / forwarding+redirects / auto-responder.
   NO quota (package-fixed), NO create, NO delete. Loads via `vanityMailbox`;
   writes reuse `mailboxChangePassword` + `mailboxUpdate` (the latter preserves
   the package quota server-side for vanity). Sections gate on:
     • allow_change_password   → password section
     • allow_mailbox_settings  → forwarding + auto-responder sections
*}

<style>
.puq-mb-addr { font-size:18px; font-weight:700; color:#2c3e50; word-break:break-all; }
.puq-mb-help { font-size:11px; color:var(--puq-muted); margin:2px 0 0; }
.puq-mb-actions { display:flex; gap:10px; align-items:center; margin-top:10px; }
.puq-mb-section { padding:2px 0; }
.puq-mb-section > h5 { margin:0 0 10px; font-size:14px; font-weight:600; }
.puq-mb-row { display:flex; flex-wrap:wrap; gap:10px; align-items:flex-start; }
.puq-mb-card hr { margin:18px 0; border-top:1px solid var(--puq-border); }
</style>

<div class="puq-dash-header" style="display:flex;align-items:center;gap:10px;margin-bottom:14px;">
    <a class="puq-btn puq-btn-outline puq-btn-sm" href="clientarea.php?action=productdetails&amp;id={$service_id}"><i class="fa fa-arrow-left"></i> {$L.vn_back_to_overview}</a>
    <h2 style="margin:0;font-size:20px;">
        <i class="fa fa-envelope" style="color:var(--puq-success);"></i> {$L.vn_mailbox}
        <small style="color:var(--puq-muted);">— {$vanity_email|escape:'html'}</small>
    </h2>
</div>

<div class="puq-card puq-mb-card" data-puq-lock-zone="mail">
    <div class="puq-card-header" style="display:flex;align-items:center;gap:8px;">
        <i class="fa fa-envelope" style="color:var(--puq-success);"></i> {$L.vn_mailbox_settings}
        <span style="flex:1;"></span>
        {if $permissions.allow_webmail_link eq 'on' and $webmail_url ne ''}
        <a class="puq-btn puq-btn-success puq-btn-sm" href="{$webmail_url|escape:'html'}" target="_blank" rel="noopener"><i class="fa fa-envelope-open-text"></i> {$L.vn_open_webmail}</a>
        {/if}
    </div>
    <div class="puq-card-body">

        <div id="vn-mb-loading" class="puq-loader"><i class="fa fa-circle-notch fa-spin"></i> {$L.vn_loading_mailbox}</div>
        <div id="vn-mb-missing" style="display:none;"><div class="puq-msg puq-msg-info"><i class="fa fa-clock"></i> {$L.vn_mailbox_being_setup}</div></div>

        <div id="vn-mb-wrap" style="display:none;">

            <div id="vn-mb-busy" style="display:none;margin-bottom:12px;"><div class="puq-msg puq-msg-warning"><i class="fa fa-circle-notch fa-spin"></i> {$L.vn_applying_last_change}</div></div>

            {* ---- Address + storage ---- *}
            <div class="puq-mb-section">
                <div class="puq-mb-addr puq-copy" data-copy="{$vanity_email|escape:'html'}" title="{$L.vn_click_to_copy}">{$vanity_email|escape:'html'} <i class="fa fa-copy" style="font-size:12px;color:var(--puq-muted);"></i></div>
                <div class="puq-mb-help">{$L.vn_email_addr_plan_hint}</div>
                <div id="vn-mb-usage" style="margin-top:10px;max-width:420px;"></div>
            </div>

            {* ---- Change password ---- *}
            {if $permissions.allow_change_password eq 'on'}
            <hr>
            <div class="puq-mb-section">
                <h5><i class="fa fa-key" style="color:var(--puq-warning);"></i> {$L.vn_password}</h5>
                <div class="puq-mb-row">
                    <div style="flex:1 1 220px;">
                        <label style="font-weight:600;display:block;margin-bottom:4px;">{$L.vn_new_password}</label>
                        <input type="password" class="form-control" id="vn-mb-pw" autocomplete="new-password" data-puq-lock-role="mail">
                    </div>
                    <div style="flex:1 1 220px;">
                        <label style="font-weight:600;display:block;margin-bottom:4px;">{$L.vn_repeat_password}</label>
                        <input type="password" class="form-control" id="vn-mb-pw2" autocomplete="new-password" data-puq-lock-role="mail">
                    </div>
                </div>
                <p class="puq-mb-help">{$L.vn_password_rule}</p>
                <div class="puq-mb-actions">
                    <button type="button" class="puq-btn puq-btn-primary puq-mb-savepw" data-puq-lock-role="mail"><i class="fa fa-save"></i> {$L.vn_change_password}</button>
                </div>
            </div>
            {/if}

            {* ---- Forwarding / redirects ---- *}
            {if $permissions.allow_mailbox_settings eq 'on'}
            <hr>
            <div class="puq-mb-section">
                <h5><i class="fa fa-share" style="color:var(--puq-primary);"></i> {$L.vn_forwarding_redirects}</h5>
                <label style="font-weight:600;display:block;margin-bottom:4px;">{$L.vn_forward_copy_to}</label>
                <textarea class="form-control" id="vn-mb-fwd" rows="2" spellcheck="false" placeholder="someone@example.com, another@example.com" data-puq-lock-role="mail"></textarea>
                <p class="puq-mb-help">{$L.vn_forward_hint}</p>
                <label class="puq-toggle" style="display:inline-flex;align-items:center;gap:8px;font-weight:normal;margin-top:8px;">
                    <input type="checkbox" id="vn-mb-fwdonly" data-puq-lock-role="mail">
                    <span>{$L.vn_forward_only_label}</span>
                </label>
                <div class="puq-mb-actions">
                    <button type="button" class="puq-btn puq-btn-primary puq-mb-savemail" data-puq-lock-role="mail"><i class="fa fa-save"></i> {$L.vn_save_forwarding}</button>
                </div>
            </div>

            {* ---- Auto-responder ---- *}
            <hr>
            <div class="puq-mb-section">
                <h5><i class="fa fa-reply" style="color:#9b59b6;"></i> {$L.vn_auto_responder}</h5>
                <label style="font-weight:600;display:block;margin-bottom:4px;">{$L.vn_auto_reply_message}</label>
                <textarea class="form-control" id="vn-mb-ar" rows="4" spellcheck="true" placeholder="{$L.vn_auto_reply_placeholder}" data-puq-lock-role="mail"></textarea>
                <p class="puq-mb-help">{$L.vn_auto_reply_hint}</p>
                <div class="puq-mb-actions">
                    <button type="button" class="puq-btn puq-btn-primary puq-mb-savemail" data-puq-lock-role="mail"><i class="fa fa-save"></i> {$L.vn_save_auto_responder}</button>
                </div>
            </div>
            {/if}

            <div id="vn-mb-msg" style="margin-top:10px;"></div>
        </div>
    </div>
</div>

<script>window.puqServiceId = {$service_id}; window.puqPageRoles = ['mail'];</script>
<script>
{literal}
(function(){
    var mb = null;            // current mailbox row (email/forward/autoreply/…)
    var auto = puqAutoRefresh(load);

    function isLocked(st){ return st !== 'active' && st !== 'error'; }

    function fmtMB(mb){ mb=parseFloat(mb)||0; if(mb>=1024){ var g=mb/1024; return (g>=10?g.toFixed(0):g.toFixed(1))+' GB'; } return Math.round(mb)+' MB'; }
    function usageGauge(used,lim){
        used=parseFloat(used)||0; lim=parseFloat(lim)||0;
        var capTxt = lim>0 ? fmtMB(lim) : '∞';
        var pct = lim>0 ? Math.min(100, Math.round(used/lim*100)) : 0;
        var col = pct>=90?'var(--puq-danger)':pct>=75?'var(--puq-warning)':'var(--puq-success)';
        var bar = lim>0 ? '<div class="puq-bar" style="margin-top:5px;"><div class="puq-bar-fill" style="width:'+pct+'%;background:'+col+';"></div></div>' : '';
        return '<div style="font-size:12px;color:var(--puq-muted);">'+puqEsc(puqT('vn_mailbox_storage'))+': <strong style="color:#444;">'+fmtMB(used)+'</strong> '+puqEsc(puqT('vn_of'))+' '+capTxt+(lim>0?(' &nbsp;('+pct+'%)'):'')+'</div>'+bar;
    }

    function fill(d){
        var m = d.mailbox;
        $('#vn-mb-loading').hide();
        if(!m){ $('#vn-mb-missing').show(); $('#vn-mb-wrap').hide(); return; }
        mb = m;
        $('#vn-mb-wrap').show();
        $('#vn-mb-usage').html(usageGauge(m.usage_mb, m.quota_mb));

        var locked = isLocked(m.deploy_status);
        $('#vn-mb-busy').toggle(locked);
        $('#vn-mb-wrap').find('input,textarea,button').prop('disabled', locked);

        // Only repopulate editable fields when NOT mid-edit by the user. We
        // refresh on load + after a save; on the post-save poll the inputs are
        // disabled anyway, so overwriting is safe and keeps them authoritative.
        $('#vn-mb-fwd').val((m.forward_to||'').split(',').filter(Boolean).join(', '));
        $('#vn-mb-fwdonly').prop('checked', String(m.forward_only)==='1');
        $('#vn-mb-ar').val(m.autoreply||'');

        if(locked) auto.schedule(true); else auto.stop();
    }

    function load(){
        puqClientAjax('vanityMailbox', {}, function(r){
            if(r.status==='success' && r.data){ fill(r.data); }
            else { $('#vn-mb-loading').html('<div class="puq-msg puq-msg-error">'+puqEsc(r.msg||puqT('vn_could_not_load'))+'</div>'); }
        }, 'POST');
    }

    // ---- Change password ----
    $(document).on('click', '.puq-mb-savepw', function(){
        var btn=this, pw=$('#vn-mb-pw').val()||'', pw2=$('#vn-mb-pw2').val()||'';
        puqClearInputErrors('#vn-mb-wrap');
        if(!puqValidate.passwordStrong(pw)){ puqShowInputError($('#vn-mb-pw')[0],puqT('vn_err_password_weak')); return; }
        if(pw!==pw2){ puqShowInputError($('#vn-mb-pw2')[0],puqT('vn_err_password_mismatch')); return; }
        if(!mb || !mb.email){ return; }
        puqBtnSpin(btn,puqT('vn_saving'));
        puqClientAjax('mailboxChangePassword', {email:mb.email, password:pw}, function(r){
            puqBtnRestore(btn);
            if(r.status==='success'){ $('#vn-mb-pw').val(''); $('#vn-mb-pw2').val(''); puqToast('success',puqT('vn_password_queued')); load(); }
            else { puqToast('error', r.msg||puqT('vn_err_password_change')); }
        }, 'POST');
    });

    // ---- Save forwarding + auto-responder (one atomic mailboxUpdate) ----
    // Both section buttons submit the full set, so saving one never wipes the
    // other. Quota is intentionally omitted — preserved server-side for vanity.
    $(document).on('click', '.puq-mb-savemail', function(){
        var btn=this;
        var fwd=($('#vn-mb-fwd').val()||'').trim();
        var fwdOnly=$('#vn-mb-fwdonly').is(':checked')?1:0;
        if(fwdOnly===1 && fwd===''){ puqToast('warning',puqT('vn_warn_forward_only_empty')); return; }
        if(!mb || !mb.email){ return; }
        puqBtnSpin(btn,puqT('vn_saving'));
        puqClientAjax('mailboxUpdate', {
            email: mb.email,
            forward_to: fwd,
            forward_only: fwdOnly,
            aliases: (mb && mb.aliases) || '',
            autoreply: ($('#vn-mb-ar').val()||'')
        }, function(r){
            puqBtnRestore(btn);
            if(r.status==='success'){ puqToast('success',puqT('vn_mail_settings_queued')); load(); }
            else { puqToast('error', r.msg||puqT('vn_could_not_save')); }
        }, 'POST');
    });

    load();
})();
{/literal}
</script>
