{include file='modules/servers/puqWebHosting/templates/header.tpl'}
{assign var='page_icon'  value='folder-open'}
{assign var='page_title' value=$L.wf_ftp_accounts}
{include file='modules/servers/puqWebHosting/templates/_page_header.tpl'}

<div class="puq-msg puq-msg-info" style="font-size:13px;">
    <i class="fa fa-server"></i> <strong>{$L.wf_ftp_server}:</strong> <code>{$web_hostname|default:'(unassigned)'|escape:'html'}</code> &nbsp;·&nbsp;
    <strong>{$L.wf_port}:</strong> <code>21</code>
</div>

<div class="puq-card" data-puq-lock-zone="web">
    <div class="puq-card-header">
        <i class="fa fa-list"></i> {$L.wf_your_ftp_accounts}
        <i class="fas fa-circle-notch fa-spin" id="puq-ftp-spinner" style="display:none;color:var(--puq-muted);margin-left:6px;font-size:12px;" title="{$L.wf_refreshing}"></i>
        <span class="puq-header-spacer"></span>
        <span class="puq-sync-toolbar" data-role="web" style="margin-right:8px;"></span>
        <span id="puq-ftp-usage" class="puq-badge puq-badge-muted" title="{$L.wf_used_limit}">…</span>
        <button type="button" class="puq-btn puq-btn-primary puq-btn-sm" id="puq-ftp-add"><i class="fa fa-plus"></i> {$L.wf_add_ftp_account}</button>
    </div>
    <div class="puq-card-body">
        <div id="puq-ftp-create" class="puq-msg puq-msg-info" style="display:none;">
            <form id="puq-ftp-form" autocomplete="off">
                <div class="puq-row" style="gap:8px;">
                    <div class="puq-col" style="min-width:220px;">
                        <label style="font-size:11px;color:var(--puq-muted);">{$L.wf_username}</label>
                        <div style="display:flex;align-items:center;gap:4px;">
                            <span style="color:var(--puq-muted);font-family:monospace;font-size:13px;">{$web_username|escape:'html'}_</span>
                            <input type="text" name="username" class="form-control" pattern="[a-zA-Z0-9._\-]+" required minlength="1" maxlength="16" placeholder="ftp1" style="flex:1;">
                        </div>
                        <small class="text-muted">{$L.wf_prefix} <code>{$web_username|escape:'html'}_</code> {$L.wf_added_automatically}</small>
                    </div>
                    <div class="puq-col" style="min-width:220px;">
                        <label style="font-size:11px;color:var(--puq-muted);">{$L.wf_password}</label>
                        <input type="password" name="password" class="form-control" required minlength="8" autocomplete="new-password">
                        <small class="text-muted">{$L.wf_password_rule}</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.wf_create}</button>
                    <button type="button" class="puq-btn puq-btn-outline puq-btn-sm" id="puq-ftp-cancel">{$L.wf_cancel}</button>
                </div>
            </form>
        </div>

        <table class="table table-striped table-hover" id="puq-ftp-table" style="width:100%;">
            <thead><tr><th>{$L.wf_username}</th><th>{$L.wf_status}</th><th style="width:180px;">{$L.wf_actions}</th></tr></thead>
            <tbody><tr><td colspan="3" class="puq-loader"><i class="fas fa-circle-notch fa-spin"></i><span class="puq-loader-caption">{$L.wf_loading_ftp_accounts}</span></td></tr></tbody>
        </table>
    </div>
</div>

<script>
window.puqServiceId   = {$service_id};
window.puqPageRoles   = ['web'];
window.puqWebUsername = {literal}'{/literal}{$web_username|escape:'javascript'}{literal}'{/literal};
window.puqFtpLimit    = {if isset($limits.web_ftp_accounts)}{$limits.web_ftp_accounts|intval}{else}0{/if};
</script>
{literal}
<script>
(function(){
    var $form = $('#puq-ftp-form');
    var $createBox = $('#puq-ftp-create');
    var TRANSIENT = ['queued','deploying','pending_delete','deleting'];
    var fullName = window.puqFullName;

    var auto = puqAutoRefresh(load);

    function load(){
        puqInitialTableLoader('#puq-ftp-table tbody', 'data-user', 3, puqT('wf_loading_ftp_accounts'));
        puqSetSpinner('#puq-ftp-spinner', true);
        puqClientAjax('ftpList', {}, function(r){
            puqSetSpinner('#puq-ftp-spinner', false);
            var $t = $('#puq-ftp-table tbody');
            if (r.status !== 'success') {
                if (!$t.children('tr[data-user]').length) {
                    $t.html('<tr><td colspan="3" class="text-danger text-center" style="padding:18px;">' + puqEsc(r.msg||puqT('wf_error')) + '</td></tr>');
                } else if (window.puqToast) puqToast('error', r.msg || puqT('wf_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-ftp-usage', '#puq-ftp-add', aliveCount, window.puqFtpLimit || 0, puqT('wf_add_ftp_account'));
            var html = '';
            if (!rows.length) {
                html = '<tr><td colspan="3" class="text-muted text-center" style="padding:24px;">' + puqT('wf_no_ftp_accounts') + '</td></tr>';
            } else {
                rows.forEach(function(d){
                    var ed = puqIsEditable(d.deploy_status);
                    var op = d.remote_id ? 'update' : 'create';
                    html += '<tr data-user="' + puqEscAttr(d.username) + '">' +
                        '<td><code>' + puqEsc(fullName(d.username)) + '</code></td>' +
                        '<td>' + puqDeployBadge(d.deploy_status, d.deploy_error, op) + '</td>' +
                        '<td>' +
                            (ed ? '<button type="button" class="puq-btn puq-btn-outline puq-btn-sm puq-pw" title="' + puqT('wf_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="' + puqT('wf_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('ftp', rows, 'username', 'deploy_status', 'FTP account', 'username');
            auto.schedule(anyPending);
        });
    }

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

    $('#puq-ftp-add').on('click', function(e){
        e.preventDefault();
        if (atLimit()) {
            puqConfirm({
                type: 'warning', icon: 'fa-ban',
                title: puqT('wf_ftp_limit_reached'),
                text: puqT('wf_ftp_limit_text_a') + ' <strong>' + (window.puqFtpLimit || 0) + '</strong> ' + puqT('wf_ftp_limit_text_b'),
                ok: puqT('wf_got_it'), cancel: puqT('wf_close')
            });
            return;
        }
        $form[0].reset(); puqClearInputErrors($form); $createBox.show();
        $form.find('input[name="username"]').focus();
    });
    $('#puq-ftp-cancel').on('click', function(e){ e.preventDefault(); $createBox.hide(); });

    $(document).on('click', '#puq-ftp-table .puq-del', function(e){
        e.preventDefault();
        var shortUser = $(this).closest('tr').data('user');
        var fullUser = fullName(shortUser);
        puqConfirm({
            type: 'danger', icon: 'fa-trash-alt',
            title: puqT('wf_delete_ftp_account_q'),
            text: puqT('wf_account') + ' <code>' + puqEsc(fullUser) + '</code> ' + puqT('wf_ftp_delete_text'),
            ok: puqT('wf_delete'), cancel: puqT('wf_keep'),
            onConfirm: function(){
                return new Promise(function(resolve, reject){
                    puqClientAjax('ftpDelete', { username: shortUser }, function(r){
                        if (r.status === 'success') { puqToast('success', puqT('wf_ftp_queued_deletion')); load(); resolve(); }
                        else reject(new Error(r.msg || puqT('wf_delete_failed')));
                    }, 'POST');
                });
            }
        });
    });

    $(document).on('click', '#puq-ftp-table .puq-pw', function(e){
        e.preventDefault();
        var shortUser = $(this).closest('tr').data('user');
        var fullUser = fullName(shortUser);
        puqPrompt({
            type: 'info', icon: 'fa-key',
            title: puqT('wf_change_ftp_password'),
            text: puqT('wf_new_password_for') + ' <code>' + puqEsc(fullUser) + '</code>.<br>' + puqT('wf_password_rule'),
            inputType: 'password', placeholder: puqT('wf_new_password'), ok: puqT('wf_update'),
            validator: function(v){ return puqValidate.passwordStrong(v); },
            validatorMsg: puqValidate.passwordStrongMsg,
            onSubmit: function(pw){
                return new Promise(function(resolve, reject){
                    puqClientAjax('ftpChangePassword', { username: shortUser, password: pw }, function(r){
                        if (r.status === 'success') { puqToast('success', puqT('wf_password_change_queued')); load(); resolve(); }
                        else reject(new Error(r.msg || puqT('wf_change_failed')));
                    }, 'POST');
                });
            }
        });
    });

    $form.on('submit', function(e){
        e.preventDefault();
        puqClearInputErrors($form);
        var $u = $form.find('[name=username]');
        var $p = $form.find('[name=password]');
        var u = ($u.val() || '').trim();
        var p = $p.val() || '';
        var ok = true;
        if (!/^[a-zA-Z0-9._\-]{1,16}$/.test(u)) { puqShowInputError($u, puqT('wf_ftp_username_rule')); ok = false; }
        if (!puqValidate.passwordStrong(p)) { puqShowInputError($p, puqValidate.passwordStrongMsg); ok = false; }
        if (!ok) return;
        var $btn = $form.find('button[type=submit]'); puqBtnSpin($btn, puqT('wf_creating'));
        puqClientAjax('ftpCreate', $form.serialize(), function(r){
            puqBtnRestore($btn);
            if (r.status === 'success') {
                puqToast('success', puqT('wf_ftp_create_queued') + ' ' + fullName(u));
                $createBox.hide(); load();
            } else {
                puqToast('error', r.msg || puqT('wf_create_failed'));
            }
        }, 'POST');
    });

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