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

<div class="puq-msg puq-msg-info" style="font-size:13px;display:flex;align-items:center;gap:14px;flex-wrap:wrap;">
    <span><i class="fa fa-database"></i> <strong>{$L.wf_engine}:</strong> <code>MySQL</code></span>
    <span>·</span>
    <span><i class="fa fa-server"></i> <strong>{$L.wf_host}:</strong> <code>localhost</code></span>
    <span>·</span>
    <span><i class="fa fa-plug"></i> <strong>{$L.wf_port}:</strong> <code>3306</code></span>
    {if $pma_url}
        <span style="flex:1;"></span>
        <a class="puq-btn puq-btn-outline puq-btn-sm" href="{$pma_url|escape:'html'}" target="_blank" rel="noopener noreferrer">
            <i class="fa fa-external-link-alt"></i> {$L.wf_open_phpmyadmin}
        </a>
    {/if}
</div>

<div class="puq-card" data-puq-lock-zone="web">
    <div class="puq-card-header">
        <i class="fa fa-list"></i> {$L.wf_your_databases}
        <i class="fas fa-circle-notch fa-spin" id="puq-db-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-db-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-db-add"><i class="fa fa-plus"></i> {$L.wf_add_database}</button>
    </div>
    <div class="puq-card-body">
        <div id="puq-db-create" class="puq-msg puq-msg-info" style="display:none;">
            <form id="puq-db-form" autocomplete="off">
                <div class="puq-row" style="gap:8px;">
                    <div class="puq-col" style="min-width:260px;">
                        <label style="font-size:11px;color:var(--puq-muted);">{$L.wf_database_name} <small>{$L.wf_also_db_user}</small></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="db_name" class="form-control" pattern="[a-zA-Z][a-zA-Z0-9_]*" required minlength="1" maxlength="20" placeholder="mysite" style="flex:1;">
                        </div>
                        <small class="text-muted">{$L.wf_db_name_letters} {$L.wf_prefix} <code>{$web_username|escape:'html'}_</code> {$L.wf_db_name_combined}</small>
                    </div>
                    <div class="puq-col" style="min-width:260px;">
                        <label style="font-size:11px;color:var(--puq-muted);">{$L.wf_password}</label>
                        <input type="password" name="db_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-db-cancel">{$L.wf_cancel}</button>
                </div>
            </form>
        </div>

        <table class="table table-striped table-hover" id="puq-db-table" style="width:100%;">
            <thead><tr><th>{$L.wf_name_user}</th><th style="width:1%;text-align:right;white-space:nowrap;">{$L.wf_disk}</th><th>{$L.wf_status}</th><th style="width:240px;">{$L.wf_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.wf_loading_databases}</span></td></tr></tbody>
        </table>
    </div>
</div>

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

    var auto = puqAutoRefresh(load);

    function load(){
        puqInitialTableLoader('#puq-db-table tbody', 'data-name', 4, puqT('wf_loading_databases'));
        puqSetSpinner('#puq-db-spinner', true);
        puqClientAjax('databasesList', {}, function(r){
            puqSetSpinner('#puq-db-spinner', false);
            var $t = $('#puq-db-table tbody');
            if (r.status !== 'success') {
                if (!$t.children('tr[data-name]').length) {
                    $t.html('<tr><td colspan="4" 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-db-usage', '#puq-db-add', aliveCount, window.puqDbLimit || 0, puqT('wf_add_database'));
            var html = '';
            if (!rows.length) {
                html = '<tr><td colspan="4" class="text-muted text-center" style="padding:24px;">' + puqT('wf_no_databases') + '</td></tr>';
            } else {
                rows.forEach(function(d){
                    var ed = puqIsEditable(d.deploy_status);
                    var op = d.remote_id ? 'update' : 'create';
                    var pma = '';
                    if (window.puqPmaUrl && d.engine === 'mysql' && ed) {
                        pma = '<a class="puq-btn puq-btn-outline puq-btn-sm" href="' + puqEsc(window.puqPmaUrl) + '" target="_blank" rel="noopener noreferrer" title="' + puqT('wf_open_phpmyadmin') + '"><i class="fa fa-external-link-alt"></i> pma</a> ';
                    }
                    var diskCell;
                    if (!ed && !d.remote_id) {
                        diskCell = '<span style="color:var(--puq-muted);">—</span>';
                    } else {
                        var mb = parseFloat(d.size_mb || 0);
                        diskCell = mb >= 1024
                            ? (mb / 1024).toFixed(2) + ' <small style="color:var(--puq-muted);">GB</small>'
                            : mb.toFixed(2) + ' <small style="color:var(--puq-muted);">MB</small>';
                    }
                    html += '<tr data-name="' + puqEscAttr(d.db_name) + '">' +
                        '<td><code>' + puqEsc(fullName(d.db_name)) + '</code></td>' +
                        '<td style="text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap;">' + diskCell + '</td>' +
                        '<td>' + puqDeployBadge(d.deploy_status, d.deploy_error, op) + '</td>' +
                        '<td>' + pma +
                            (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('db', rows, 'db_name', 'deploy_status', 'database', 'db_name');
            auto.schedule(anyPending);
        });
    }

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

    $('#puq-db-add').on('click', function(e){
        e.preventDefault();
        if (atLimit()) {
            puqConfirm({
                type: 'warning', icon: 'fa-ban',
                title: puqT('wf_db_limit_reached'),
                text: puqT('wf_db_limit_text_a') + ' <strong>' + (window.puqDbLimit || 0) + '</strong> ' + puqT('wf_db_limit_text_b'),
                ok: puqT('wf_got_it'), cancel: puqT('wf_close')
            });
            return;
        }
        $form[0].reset(); puqClearInputErrors($form); $createBox.show();
        $form.find('[name=db_name]').focus();
    });
    $('#puq-db-cancel').on('click', function(e){ e.preventDefault(); $createBox.hide(); });

    $(document).on('click', '#puq-db-table .puq-del', function(e){
        e.preventDefault();
        var name = $(this).closest('tr').data('name');
        puqConfirm({
            type: 'danger', icon: 'fa-trash-alt',
            title: puqT('wf_delete_database_q'),
            text: puqT('wf_database') + ' <code>' + puqEsc(fullName(name)) + '</code> ' + puqT('wf_db_delete_text') + ' <strong>' + puqT('wf_all_data_lost') + '</strong>',
            ok: puqT('wf_delete'), cancel: puqT('wf_keep'),
            onConfirm: function(){
                return new Promise(function(resolve, reject){
                    puqClientAjax('databaseDelete', { db_name: name }, function(r){
                        if (r.status === 'success') { puqToast('success', puqT('wf_db_queued_deletion')); load(); resolve(); }
                        else reject(new Error(r.msg || puqT('wf_delete_failed')));
                    }, 'POST');
                });
            }
        });
    });

    $(document).on('click', '#puq-db-table .puq-pw', function(e){
        e.preventDefault();
        var name = $(this).closest('tr').data('name');
        puqPrompt({
            type: 'info', icon: 'fa-key',
            title: puqT('wf_change_db_password'),
            text: puqT('wf_new_password_for') + ' <code>' + puqEsc(fullName(name)) + '</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('databaseChangePassword', { db_name: name, 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 $n = $form.find('[name=db_name]');
        var $p = $form.find('[name=db_password]');
        var name = ($n.val() || '').trim();
        var pw   = $p.val() || '';
        var ok = true;
        var maxSuffix = Math.max(1, 32 - (window.puqWebUsername || '').length - 1);
        if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(name)) {
            puqShowInputError($n, puqT('wf_db_name_start_rule')); ok = false;
        } else if (name.length > maxSuffix) {
            puqShowInputError($n, puqT('wf_max') + ' ' + maxSuffix + ' ' + puqT('wf_chars')); ok = false;
        }
        if (!puqValidate.passwordStrong(pw)) {
            puqShowInputError($p, puqValidate.passwordStrongMsg); ok = false;
        }
        if (!ok) return;
        var $btn = $form.find('button[type=submit]'); puqBtnSpin($btn, puqT('wf_creating'));
        puqClientAjax('databaseCreate', $form.serialize(), function(r){
            puqBtnRestore($btn);
            if (r.status === 'success') {
                puqToast('success', puqT('wf_db_create_queued') + ' ' + fullName(name));
                $createBox.hide(); load();
            } else {
                puqToast('error', r.msg || puqT('wf_create_failed'));
            }
        }, 'POST');
    });

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