{include file='modules/servers/puqWebHosting/templates/header.tpl'}
{assign var='page_icon'  value='envelope'}
{assign var='page_title' value=$L.mc_mailboxes_title}
{include file='modules/servers/puqWebHosting/templates/_page_header.tpl'}

<div class="puq-card">
    <div class="puq-card-header">
        <i class="fa fa-server"></i> {$L.mc_mail_server_settings}
        <span class="puq-header-spacer"></span>
        {if $webmail_url}
            <a class="puq-btn puq-btn-outline puq-btn-sm" href="{$webmail_url|escape:'html'}" target="_blank" rel="noopener noreferrer">
                <i class="fa fa-external-link-alt"></i> {$L.mc_open_webmail}
            </a>
        {/if}
    </div>
    <div class="puq-card-body">
        <div class="puq-msg puq-msg-info" style="font-size:13px;margin-bottom:12px;">
            <i class="fa fa-info-circle"></i>
            <strong>{$L.mc_server}:</strong> <code>{$mail_hostname|default:$L.mc_unassigned|escape:'html'}</code> &nbsp;·&nbsp;
            <strong>{$L.mc_domain}:</strong> <code>{$domain|escape:'html'}</code> &nbsp;·&nbsp;
            <strong>{$L.mc_auth}:</strong> {$L.mc_normal_password} &nbsp;·&nbsp;
            <strong>{$L.mc_username}:</strong> {$L.mc_full_email_address}
        </div>
        <div class="puq-row" style="gap:12px;">
            <div class="puq-col" style="min-width:240px;">
                <div style="font-weight:600;font-size:13px;margin-bottom:6px;"><i class="fa fa-inbox" style="color:var(--puq-primary);"></i> IMAP <small style="color:var(--puq-muted);">— {$L.mc_imap_hint}</small></div>
                <table class="table table-condensed" style="margin-bottom:0;font-size:12px;">
                    <tbody>
                        <tr><td>SSL/TLS</td><td style="text-align:right;"><code>993</code></td></tr>
                        <tr><td>STARTTLS</td><td style="text-align:right;"><code>143</code></td></tr>
                        <tr><td>{$L.mc_no_encryption}</td><td style="text-align:right;"><code>143</code></td></tr>
                    </tbody>
                </table>
            </div>
            <div class="puq-col" style="min-width:240px;">
                <div style="font-weight:600;font-size:13px;margin-bottom:6px;"><i class="fa fa-download" style="color:var(--puq-primary);"></i> POP3 <small style="color:var(--puq-muted);">— {$L.mc_pop3_hint}</small></div>
                <table class="table table-condensed" style="margin-bottom:0;font-size:12px;">
                    <tbody>
                        <tr><td>SSL/TLS</td><td style="text-align:right;"><code>995</code></td></tr>
                        <tr><td>STARTTLS</td><td style="text-align:right;"><code>110</code></td></tr>
                        <tr><td>{$L.mc_no_encryption}</td><td style="text-align:right;"><code>110</code></td></tr>
                    </tbody>
                </table>
            </div>
            <div class="puq-col" style="min-width:240px;">
                <div style="font-weight:600;font-size:13px;margin-bottom:6px;"><i class="fa fa-paper-plane" style="color:var(--puq-primary);"></i> SMTP <small style="color:var(--puq-muted);">— {$L.mc_smtp_hint}</small></div>
                <table class="table table-condensed" style="margin-bottom:0;font-size:12px;">
                    <tbody>
                        <tr><td>SSL/TLS</td><td style="text-align:right;"><code>465</code></td></tr>
                        <tr><td>STARTTLS</td><td style="text-align:right;"><code>587</code></td></tr>
                        <tr><td>{$L.mc_no_encryption}</td><td style="text-align:right;"><code>25</code></td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="puq-card" data-puq-lock-zone="mail">
    <div class="puq-card-header">
        <i class="fa fa-list"></i> {$L.mc_email_accounts}
        <i class="fas fa-circle-notch fa-spin" id="puq-mb-spinner" style="display:none;color:var(--puq-muted);margin-left:6px;font-size:12px;" title="{$L.mc_refreshing}"></i>
        <span class="puq-header-spacer"></span>
        <span class="puq-sync-toolbar" data-role="mail" style="margin-right:8px;"></span>
        <span id="puq-mb-usage" class="puq-badge puq-badge-muted" title="{$L.mc_used_limit}">…</span>
        {if ($deployment_mode|default:'') ne 'vanity'}
        <button type="button" class="puq-btn puq-btn-primary puq-btn-sm" id="puq-mb-add"><i class="fa fa-plus"></i> {$L.mc_add_mailbox}</button>
        {/if}
    </div>
    <div class="puq-card-body">
        <div id="puq-mb-create" class="puq-msg puq-msg-info" style="display:none;">
            <form id="puq-mb-form" autocomplete="off">
                <div class="puq-row" style="gap:8px;">
                    <div class="puq-col" style="min-width:240px;">
                        <label style="font-size:11px;color:var(--puq-muted);">{$L.mc_email_address}</label>
                        <div style="display:flex;align-items:center;gap:4px;">
                            <input type="text" name="local_part" class="form-control" required maxlength="64" placeholder="info" style="flex:1;">
                            <span style="color:var(--puq-muted);font-family:monospace;font-size:13px;">@{$domain|escape:'html'}</span>
                        </div>
                        <small class="text-muted">{$L.mc_local_part_hint}</small>
                    </div>
                    <div class="puq-col" style="min-width:240px;">
                        <label style="font-size:11px;color:var(--puq-muted);">{$L.mc_password}</label>
                        <input type="password" name="password" class="form-control" minlength="8" required autocomplete="new-password">
                        <small class="text-muted">{$L.mc_password_hint}</small>
                    </div>
                </div>
                <div style="margin-top:10px;display:flex;gap:6px;">
                    <button type="submit" class="puq-btn puq-btn-success puq-btn-sm"><i class="fa fa-check"></i> {$L.mc_create}</button>
                    <button type="button" class="puq-btn puq-btn-outline puq-btn-sm" id="puq-mb-cancel">{$L.mc_cancel}</button>
                </div>
                <small class="text-muted" style="display:block;margin-top:6px;">{$L.mc_create_after_hint_before}<i class="fa fa-edit"></i>{$L.mc_create_after_hint_after}</small>
            </form>
        </div>

        <table class="table table-striped table-hover" id="puq-mb-table" style="width:100%;">
            <thead><tr><th>{$L.mc_email}</th><th style="width:1%;text-align:right;white-space:nowrap;">{$L.mc_used_quota}</th><th style="width:160px;">{$L.mc_status}</th><th style="width:240px;">{$L.mc_actions}</th></tr></thead>
            <tbody><tr><td colspan="4" class="puq-loader"><i class="fas fa-circle-notch fa-spin"></i><span class="puq-loader-caption">{$L.mc_loading_mailboxes}</span></td></tr></tbody>
        </table>
    </div>
</div>

{* Edit modal — opened only AFTER mailboxGet returns; the trigger button
   shows a spinner in-place during the AJAX so the click is visible. *}
<div id="puq-mb-edit-overlay" class="puq-confirm-overlay" style="display:none;">
    <div class="puq-confirm-box" style="max-width:560px;">
        <div class="puq-confirm-icon" style="color:var(--puq-primary);"><i class="fas fa-edit"></i></div>
        <div class="puq-confirm-title" id="puq-mb-edit-title">{$L.mc_edit_mailbox}</div>
        <div style="padding:0 24px 8px;">
            <form id="puq-mb-edit-form" autocomplete="off">
                <input type="hidden" name="email" id="puq-mb-edit-email">
                <div style="margin-bottom:10px;">
                    <label style="font-size:11px;color:var(--puq-muted);">{$L.mc_aliases} <small>— {$L.mc_aliases_hint_before}<code>@domain</code>{$L.mc_aliases_hint_after}</small></label>
                    <textarea name="aliases" id="puq-mb-edit-aliases" class="form-control" rows="3" placeholder="support&#10;sales&#10;hello" style="font-family:monospace;font-size:12px;"></textarea>
                </div>
                <div style="margin-bottom:10px;">
                    <label style="font-size:11px;color:var(--puq-muted);">{$L.mc_quota_mb} <small>0 = ∞</small></label>
                    <input type="number" name="quota_mb" id="puq-mb-edit-quota" class="form-control" min="0" value="0">
                </div>
                <div style="margin-bottom:10px;">
                    <label style="font-size:11px;color:var(--puq-muted);">{$L.mc_forward_to} <small>— {$L.mc_forward_to_hint}</small></label>
                    <textarea name="forward_to" id="puq-mb-edit-forward" class="form-control" rows="3" placeholder="admin@elsewhere.com&#10;backup@another.com" style="font-family:monospace;font-size:12px;"></textarea>
                    <label style="font-size:12px;margin-top:6px;display:block;">
                        <input type="checkbox" name="forward_only" id="puq-mb-edit-forward-only" value="1">
                        {$L.mc_forward_only}
                        <small style="color:var(--puq-muted);">— {$L.mc_forward_only_hint}</small>
                    </label>
                </div>
                <div style="margin-bottom:10px;">
                    <label style="font-size:12px;display:block;margin-bottom:4px;">
                        <input type="checkbox" name="autoreply_enabled" id="puq-mb-edit-autoreply-on" value="1">
                        <strong>{$L.mc_enable_autoreply}</strong>
                    </label>
                    <textarea name="autoreply" id="puq-mb-edit-autoreply" class="form-control" rows="4" placeholder="{$L.mc_autoreply_placeholder}" disabled></textarea>
                </div>
                <div class="puq-mb-edit-err text-danger" style="font-size:12px;min-height:14px;margin-top:4px;"></div>
            </form>
        </div>
        <div class="puq-confirm-btns">
            <button type="button" class="puq-confirm-btn-cancel" id="puq-mb-edit-cancel">{$L.mc_cancel}</button>
            <button type="button" class="puq-confirm-btn-ok" id="puq-mb-edit-save" style="background:var(--puq-success);">{$L.mc_save}</button>
        </div>
    </div>
</div>

<script>
window.puqServiceId  = {$service_id};
window.puqPageRoles  = ['mail'];
window.puqMailDomain = {literal}'{/literal}{$domain|escape:'javascript'}{literal}'{/literal};
window.puqMailLimit  = {if isset($limits.mail_accounts)}{$limits.mail_accounts|intval}{else}0{/if};
</script>
{literal}
<script>
(function(){
    var $form = $('#puq-mb-form');
    var $createBox = $('#puq-mb-create');
    var TRANSIENT = ['queued','deploying','pending_delete','deleting'];
    var auto = puqAutoRefresh(load);

    function fmtSize(mb){
        var n = parseFloat(mb || 0);
        if (n >= 1024) return (n / 1024).toFixed(2) + ' GB';
        return n.toFixed(2) + ' MB';
    }

    function load(){
        puqInitialTableLoader('#puq-mb-table tbody', 'data-email', 4, puqT('mc_loading_mailboxes'));
        puqSetSpinner('#puq-mb-spinner', true);
        puqClientAjax('mailboxesList', {}, function(r){
            puqSetSpinner('#puq-mb-spinner', false);
            var $t = $('#puq-mb-table tbody');
            if (r.status !== 'success') {
                if (!$t.children('tr[data-email]').length) {
                    $t.html('<tr><td colspan="4" class="text-danger text-center" style="padding:18px;">' + puqEsc(r.msg||puqT('mc_error')) + '</td></tr>');
                } else if (window.puqToast) puqToast('error', r.msg || puqT('mc_refresh_failed'));
                auto.schedule(false);
                return;
            }
            var rows = r.data || [];
            var aliveCount = rows.filter(function(d){ return d.deploy_status !== 'pending_delete' && d.deploy_status !== 'deleting'; }).length;
            puqUpdateQuotaBadge('#puq-mb-usage', '#puq-mb-add', aliveCount, window.puqMailLimit || 0, puqT('mc_add_mailbox'));

            var html = '';
            if (!rows.length) {
                html = '<tr><td colspan="4" class="text-muted text-center" style="padding:24px;">' + puqEsc(puqT('mc_no_mailboxes')) + '</td></tr>';
            } else {
                rows.forEach(function(m){
                    var ed = puqIsEditable(m.deploy_status);
                    var op = m.remote_id ? 'update' : 'create';
                    var used = parseFloat(m.u_disk_mb || 0);
                    var quota = parseInt(m.quota_mb, 10) || 0;
                    var quotaTxt = quota > 0 ? fmtSize(quota) : '<span style="color:var(--puq-muted);">∞</span>';
                    var usedTxt = (!ed && !m.remote_id)
                        ? '<span style="color:var(--puq-muted);">—</span>'
                        : (fmtSize(used) + ' <small style="color:var(--puq-muted);">/</small> ' + quotaTxt);
                    html += '<tr data-email="' + puqEscAttr(m.email) + '">' +
                        '<td><code>' + puqEsc(m.email) + '</code></td>' +
                        '<td style="text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap;">' + usedTxt + '</td>' +
                        '<td>' + puqDeployBadge(m.deploy_status, m.deploy_error, op) + '</td>' +
                        '<td>' +
                            (ed ? '<button type="button" class="puq-btn puq-btn-outline puq-btn-sm puq-edit" title="' + puqEscAttr(puqT('mc_edit_tooltip')) + '"><i class="fa fa-edit"></i></button> ' : '') +
                            (ed ? '<button type="button" class="puq-btn puq-btn-outline puq-btn-sm puq-pw" title="' + puqEscAttr(puqT('mc_change_password')) + '"><i class="fa fa-key"></i></button> ' : '') +
                            (ed ? '<button type="button" class="puq-btn puq-btn-danger puq-btn-sm puq-del" title="' + puqEscAttr(puqT('mc_delete')) + '"><i class="fa fa-trash"></i></button>' : '') +
                        '</td></tr>';
                });
            }
            $t.html(html);
            var anyPending = rows.some(function(d){ return TRANSIENT.indexOf(d.deploy_status) >= 0; });
            if (window.puqClientNotifyTransitions) puqClientNotifyTransitions('mb', rows, 'email', 'deploy_status', 'mailbox', 'email');
            auto.schedule(anyPending);
        });
    }

    function atLimit(){
        var lim = window.puqMailLimit || 0;
        if (lim <= 0) return false;
        return $('#puq-mb-table tbody tr[data-email]').length >= lim;
    }

    $('#puq-mb-add').on('click', function(e){
        e.preventDefault();
        if (atLimit()) {
            puqConfirm({
                type:'warning', icon:'fa-ban', title:puqT('mc_mailbox_limit_reached'),
                text:puqT('mc_limit_text_before')+'<strong>'+(window.puqMailLimit||0)+'</strong>'+puqT('mc_mailbox_limit_text_after'),
                ok:puqT('mc_got_it'), cancel:puqT('mc_close')
            });
            return;
        }
        $form[0].reset(); puqClearInputErrors($form); $createBox.show();
        $form.find('[name=local_part]').focus();
    });
    $('#puq-mb-cancel').on('click', function(e){ e.preventDefault(); $createBox.hide(); });

    $(document).on('click', '#puq-mb-table .puq-del', function(e){
        e.preventDefault();
        var email = $(this).closest('tr').data('email');
        puqConfirm({
            type:'danger', icon:'fa-trash-alt', title:puqT('mc_delete_mailbox_q'),
            text:puqT('mc_delete_mailbox_text_before') + '<code>' + puqEsc(email) + '</code>' + puqT('mc_delete_mailbox_text_after'),
            ok:puqT('mc_delete'), cancel:puqT('mc_keep'),
            onConfirm: function(){
                return new Promise(function(resolve, reject){
                    puqClientAjax('mailboxDelete', { email: email }, function(r){
                        if (r.status === 'success') { puqToast('success', puqT('mc_mailbox_queued_delete')); load(); resolve(); }
                        else reject(new Error(r.msg || puqT('mc_delete_failed')));
                    }, 'POST');
                });
            }
        });
    });

    $(document).on('click', '#puq-mb-table .puq-pw', function(e){
        e.preventDefault();
        var email = $(this).closest('tr').data('email');
        puqPrompt({
            type:'info', icon:'fa-key', title:puqT('mc_change_mailbox_password'),
            text:puqT('mc_new_password_for') + '<code>' + puqEsc(email) + '</code>.<br>' + puqT('mc_password_hint'),
            inputType:'password', placeholder:puqT('mc_new_password'), ok:puqT('mc_update'),
            validator: function(v){ return puqValidate.passwordStrong(v); },
            validatorMsg: puqValidate.passwordStrongMsg,
            onSubmit: function(pw){
                return new Promise(function(resolve, reject){
                    puqClientAjax('mailboxChangePassword', { email: email, password: pw }, function(r){
                        if (r.status === 'success') { puqToast('success', puqT('mc_password_change_queued')); load(); resolve(); }
                        else reject(new Error(r.msg || puqT('mc_change_failed')));
                    }, 'POST');
                });
            }
        });
    });

    function csvToLines(s){ return String(s || '').split(',').map(function(x){ return x.trim(); }).filter(Boolean).join('\n'); }
    function linesToCsv(s){ return String(s || '').split(/[\r\n,]+/).map(function(x){ return x.trim(); }).filter(Boolean).join(','); }
    function setAutoreplyEnabled(on){
        $('#puq-mb-edit-autoreply').prop('disabled', !on);
        if (!on) $('#puq-mb-edit-autoreply').val('');
    }
    $('#puq-mb-edit-autoreply-on').on('change', function(){
        setAutoreplyEnabled(this.checked);
        if (this.checked) $('#puq-mb-edit-autoreply').focus();
    });

    $(document).on('click', '#puq-mb-table .puq-edit', function(e){
        e.preventDefault();
        var $btn = $(this);
        var email = $btn.closest('tr').data('email');
        puqBtnSpin($btn);
        puqClientAjax('mailboxGet', { email: email }, function(r){
            puqBtnRestore($btn);
            if (r.status !== 'success') { if (window.puqToast) puqToast('error', r.msg || puqT('mc_failed_load_mailbox')); return; }
            var d = r.data;
            $('#puq-mb-edit-email').val(email);
            $('#puq-mb-edit-title').text(puqT('mc_edit') + ' ' + email);
            $('#puq-mb-edit-aliases').val(csvToLines(d.aliases));
            $('#puq-mb-edit-quota').val(parseInt(d.quota_mb, 10) || 0);
            $('#puq-mb-edit-forward').val(csvToLines(d.forward_to));
            $('#puq-mb-edit-forward-only').prop('checked', parseInt(d.forward_only, 10) === 1);
            var hasAutoreply = !!(d.autoreply && d.autoreply.length);
            $('#puq-mb-edit-autoreply-on').prop('checked', hasAutoreply);
            $('#puq-mb-edit-autoreply').val(d.autoreply || '');
            setAutoreplyEnabled(hasAutoreply);
            $('.puq-mb-edit-err').text('');

            var $ov = $('#puq-mb-edit-overlay');
            $ov.show();
            requestAnimationFrame(function(){ requestAnimationFrame(function(){ $ov.addClass('puq-confirm-show'); }); });
        });
    });

    function closeEditModal(){
        var $ov = $('#puq-mb-edit-overlay');
        $ov.removeClass('puq-confirm-show');
        setTimeout(function(){ $ov.hide(); }, 200);
    }
    $('#puq-mb-edit-cancel').on('click', closeEditModal);
    $('#puq-mb-edit-overlay').on('click', function(e){ if (e.target === this) closeEditModal(); });
    $(document).on('keydown.puqMbEdit', function(e){
        if (e.key === 'Escape' && $('#puq-mb-edit-overlay').is(':visible')) closeEditModal();
    });

    $('#puq-mb-edit-save').on('click', function(e){
        e.preventDefault();
        var $btn = $(this);
        var $err = $('.puq-mb-edit-err').text('');
        var autoreplyOn = $('#puq-mb-edit-autoreply-on').is(':checked');
        var data = {
            email:        $('#puq-mb-edit-email').val(),
            aliases:      linesToCsv($('#puq-mb-edit-aliases').val()),
            quota_mb:     parseInt($('#puq-mb-edit-quota').val(), 10) || 0,
            forward_to:   linesToCsv($('#puq-mb-edit-forward').val()),
            forward_only: $('#puq-mb-edit-forward-only').is(':checked') ? 1 : 0,
            autoreply:    autoreplyOn ? ($('#puq-mb-edit-autoreply').val() || '') : ''
        };
        puqBtnSpin($btn, puqT('mc_saving'));
        puqClientAjax('mailboxUpdate', data, function(r){
            puqBtnRestore($btn);
            if (r.status === 'success') { puqToast('success', puqT('mc_settings_update_queued')); closeEditModal(); load(); }
            else { $err.text(r.msg || puqT('mc_save_failed')); if (window.puqToast) puqToast('error', r.msg || puqT('mc_save_failed')); }
        }, 'POST');
    });

    $form.on('submit', function(e){
        e.preventDefault();
        puqClearInputErrors($form);
        var $local = $form.find('[name=local_part]');
        var $pw    = $form.find('[name=password]');
        var local  = ($local.val() || '').trim();
        var pw     = $pw.val() || '';
        var ok = true;
        if (!/^[a-zA-Z0-9._\-+]{1,64}$/.test(local)) { puqShowInputError($local, puqT('mc_local_part_error')); ok = false; }
        if (!puqValidate.passwordStrong(pw)) { puqShowInputError($pw, puqValidate.passwordStrongMsg); ok = false; }
        if (!ok) return;
        var $btn = $form.find('button[type=submit]'); puqBtnSpin($btn, puqT('mc_creating'));
        puqClientAjax('mailboxCreate', $form.serialize(), function(r){
            puqBtnRestore($btn);
            if (r.status === 'success') {
                puqToast('success', puqT('mc_mailbox_creation_queued') + ' — ' + local + '@' + window.puqMailDomain);
                $createBox.hide(); load();
            } else {
                puqToast('error', r.msg || puqT('mc_create_failed'));
            }
        }, 'POST');
    });

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