

<?php $__env->startSection('styles'); ?>
<style>
:root {
    --db-blue:   #38bdf8;
    --db-purple: #818cf8;
    --db-green:  #10b981;
    --db-red:    #ef4444;
    --db-amber:  #f59e0b;
}

/* ── page header ── */
.db-page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 1rem;
    margin-bottom: 2rem;
}
.db-page-header h2 {
    font-size: 1.5rem;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 0.6rem;
}
.db-page-header h2 i { color: var(--db-blue); }


/* ── tab nav ── */
.db-tabs {
    display: flex;
    gap: 4px;
    background: rgba(255,255,255,0.04);
    border: 1px solid var(--border);
    border-radius: 12px;
    padding: 4px;
    margin-bottom: 1.6rem;
    width: fit-content;
}
.db-tab {
    padding: 8px 22px;
    border-radius: 9px;
    border: none;
    background: transparent;
    color: var(--text-muted);
    cursor: pointer;
    font-size: 0.85rem;
    font-weight: 600;
    transition: all 0.18s;
    display: flex;
    align-items: center;
    gap: 7px;
}
.db-tab.active {
    background: var(--primary);
    color: #fff;
    box-shadow: 0 4px 12px rgba(99,102,241,0.35);
}
.db-tab:not(.active):hover { color: var(--text-main); background: rgba(255,255,255,0.07); }

/* ── tab panels ── */
.db-panel { display: none; }
.db-panel.active { display: block; }

/* ── section card ── */
.db-section {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 16px;
    overflow: hidden;
    margin-bottom: 1.5rem;
}
.db-section-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 1rem 1.4rem;
    border-bottom: 1px solid var(--border);
    background: rgba(255,255,255,0.025);
}
.db-section-head h3 {
    font-size: 0.92rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 7px;
    color: var(--text-main);
}

/* ── create form ── */
.db-create-form {
    padding: 1.2rem 1.4rem;
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    align-items: flex-end;
    background: rgba(56,189,248,0.03);
    border-bottom: 1px solid var(--border);
}
.db-create-form .field { display: flex; flex-direction: column; gap: 5px; flex: 1; min-width: 160px; }
.db-create-form label { font-size: 0.75rem; color: var(--text-muted); font-weight: 500; }
.db-create-form .prefix-input { display: flex; align-items: center; }
.db-create-form .prefix-input .pre {
    background: rgba(255,255,255,0.06);
    border: 1px solid var(--border);
    border-right: none;
    border-radius: 8px 0 0 8px;
    padding: 8px 10px;
    font-size: 0.82rem;
    color: var(--text-muted);
    white-space: nowrap;
}
.db-input {
    background: rgba(255,255,255,0.05);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 8px 12px;
    color: var(--text-main);
    font-size: 0.85rem;
    outline: none;
    width: 100%;
    transition: border-color 0.15s;
}
.db-input.joined { border-radius: 0 8px 8px 0; }
.db-input:focus { border-color: var(--db-blue); }

/* password toggle */
.pw-wrap { position: relative; display: flex; align-items: center; }
.pw-wrap .db-input { padding-right: 36px; }
.pw-toggle {
    position: absolute; right: 10px;
    background: none; border: none; color: var(--text-muted);
    cursor: pointer; padding: 0; font-size: 0.85rem;
    display: flex; align-items: center;
}
.pw-toggle:hover { color: var(--text-main); }

/* ── action btn ── */
.db-btn {
    padding: 9px 18px;
    border-radius: 8px;
    border: none;
    font-size: 0.82rem;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.15s;
    white-space: nowrap;
}
.db-btn.primary {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: #fff;
    box-shadow: 0 4px 12px rgba(99,102,241,0.3);
}
.db-btn.primary:hover { transform: translateY(-1px); box-shadow: 0 6px 16px rgba(99,102,241,0.4); }
.db-btn.danger  { background: rgba(239,68,68,0.12); color: #ef4444; border: 1px solid rgba(239,68,68,0.25); }
.db-btn.danger:hover  { background: rgba(239,68,68,0.2); }
.db-btn.success { background: rgba(16,185,129,0.12); color: #10b981; border: 1px solid rgba(16,185,129,0.25); }
.db-btn.success:hover { background: rgba(16,185,129,0.2); }
.db-btn.amber   { background: rgba(245,158,11,0.12); color: #f59e0b; border: 1px solid rgba(245,158,11,0.25); }
.db-btn.amber:hover   { background: rgba(245,158,11,0.2); }
.db-btn.blue    { background: rgba(56,189,248,0.12); color: #38bdf8; border: 1px solid rgba(56,189,248,0.25); }
.db-btn.blue:hover    { background: rgba(56,189,248,0.2); }
.db-btn:disabled { opacity: 0.4; cursor: default; transform: none !important; }

/* ── table ── */
.db-table-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; }
.db-table { width: 100%; border-collapse: collapse; min-width: 520px; }
.db-table th {
    padding: 10px 14px;
    font-size: 0.72rem;
    font-weight: 600;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: 0.07em;
    text-align: left;
    border-bottom: 1px solid var(--border);
}
.db-table td {
    padding: 11px 14px;
    font-size: 0.84rem;
    border-bottom: 1px solid rgba(255,255,255,0.04);
    vertical-align: middle;
}
.db-table tr:last-child td { border-bottom: none; }
.db-table tr:hover td { background: rgba(255,255,255,0.025); }
@media(max-width:600px){
    .db-tabs{flex-wrap:wrap;width:100%;}
    .db-tab{flex:1;justify-content:center;padding:8px 10px;font-size:.78rem;}
    .db-page-header{flex-direction:column;align-items:flex-start;}
}

/* badges */
.badge {
    display: inline-block;
    padding: 3px 9px;
    border-radius: 999px;
    font-size: 0.7rem;
    font-weight: 600;
}
.badge.blue   { background: rgba(56,189,248,0.15); color: #38bdf8; }
.badge.purple { background: rgba(129,140,248,0.15); color: #818cf8; }
.badge.green  { background: rgba(16,185,129,0.15); color: #10b981; }
.badge.muted  { background: rgba(148,163,184,0.12); color: var(--text-muted); }

/* db name monospace */
.db-name {
    font-family: 'Courier New', monospace;
    font-size: 0.82rem;
    color: var(--db-blue);
    font-weight: 600;
}

/* users in db */
.user-chips { display: flex; flex-wrap: wrap; gap: 5px; }
.user-chip {
    display: inline-flex; align-items: center; gap: 5px;
    background: rgba(129,140,248,0.1);
    border: 1px solid rgba(129,140,248,0.2);
    border-radius: 999px;
    padding: 2px 10px 2px 8px;
    font-size: 0.72rem;
    color: #818cf8;
}
.user-chip button {
    background: none; border: none; color: #818cf8;
    cursor: pointer; font-size: 0.65rem; padding: 0;
    line-height: 1; opacity: 0.6;
}
.user-chip button:hover { opacity: 1; color: #ef4444; }

/* assign modal */
.assign-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-top: 0.7rem; }
.db-select {
    background: rgba(255,255,255,0.05);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 8px 12px;
    color: var(--text-main);
    font-size: 0.84rem;
    outline: none;
    cursor: pointer;
}
.db-select:focus { border-color: var(--db-blue); }
.db-select option {
    background: #1e2533;
    color: #e2e8f0;
}

/* empty state */
.db-empty {
    text-align: center;
    padding: 2.5rem 1rem;
    color: var(--text-muted);
    font-size: 0.85rem;
}
.db-empty i { font-size: 2rem; margin-bottom: 0.7rem; display: block; opacity: 0.4; }

/* toast */
#dbToast {
    position: fixed;
    bottom: 24px; right: 24px;
    z-index: 99999;
    padding: 12px 20px;
    border-radius: 12px;
    font-size: 0.85rem;
    font-weight: 500;
    display: none;
    animation: slideUp 0.3s ease;
    min-width: 220px;
    box-shadow: 0 8px 30px rgba(0,0,0,0.4);
}
#dbToast.ok  { background: rgba(16,185,129,0.15); color: #10b981; border: 1px solid rgba(16,185,129,0.3); }
#dbToast.err { background: rgba(239,68,68,0.15);  color: #ef4444;  border: 1px solid rgba(239,68,68,0.3); }
@keyframes slideUp {
    from { opacity: 0; transform: translateY(12px); }
    to   { opacity: 1; transform: translateY(0); }
}

/* ── modal overlay (assign/revoke) ── */
#dbModalOverlay {
    position: fixed; inset: 0; z-index: 9990;
    background: rgba(5,10,20,0.8);
    backdrop-filter: blur(8px);
    display: flex; align-items: center; justify-content: center;
    opacity: 0; pointer-events: none;
    transition: opacity 0.2s ease;
}
#dbModalOverlay.open { opacity: 1; pointer-events: all; }
#dbModalBox {
    background: linear-gradient(145deg,#0f172a,#1e293b);
    border: 1px solid var(--border);
    border-radius: 20px;
    padding: 2rem;
    width: 420px; max-width: 94vw;
    transform: scale(0.9) translateY(16px);
    transition: transform 0.25s cubic-bezier(.34,1.56,.64,1);
    box-shadow: 0 24px 60px rgba(0,0,0,0.5);
}
#dbModalOverlay.open #dbModalBox { transform: scale(1) translateY(0); }
#dbModalBox h3 { font-size: 1rem; font-weight: 700; margin-bottom: 1.2rem; display: flex; align-items: center; gap: 8px; }
.dbm-field { margin-bottom: 1rem; }
.dbm-field label { display: block; font-size: 0.75rem; color: var(--text-muted); margin-bottom: 5px; font-weight: 500; }
.dbm-btns { display: flex; gap: 10px; margin-top: 1.4rem; }
.dbm-btns button { flex: 1; }
</style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="animate-fade">

    
    <div class="db-page-header">
        <h2><i class="fas fa-database"></i> Database Manager</h2>
    </div>

    
    <div class="db-tabs">
        <button class="db-tab active" onclick="switchTab('dbs', this)">
            <i class="fas fa-database"></i> Databases
        </button>
        <button class="db-tab" onclick="switchTab('users', this)">
            <i class="fas fa-user-shield"></i> DB Users
        </button>
        <button class="db-tab" onclick="switchTab('assign', this)">
            <i class="fas fa-link"></i> Assign User
        </button>
    </div>

    
    <div class="db-panel active" id="tab-dbs">
        <div class="db-section">
            <div class="db-section-head">
                <h3><i class="fas fa-plus-circle" style="color:var(--db-blue);"></i> Create Database</h3>
            </div>
            <div class="db-create-form">
                <div class="field">
                    <label>Database Name</label>
                    <div class="prefix-input">
                        <span class="pre"><?php echo e($prefix); ?></span>
                        <input class="db-input joined" id="newDbName" placeholder="mydb" maxlength="48">
                    </div>
                </div>
                <button class="db-btn primary" onclick="createDatabase()">
                    <i class="fas fa-plus"></i> Create
                </button>
            </div>
            
            <div class="db-table-wrap"><table class="db-table">
                <thead><tr>
                    <th>Database Name</th>
                    <th>Users</th>
                    <th style="text-align:right;">Actions</th>
                </tr></thead>
                <tbody id="dbTableBody">
                <?php $__empty_1 = true; $__currentLoopData = $databases; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $db): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                <tr id="dbrow-<?php echo e(md5($db)); ?>">
                    <td><span class="db-name"><?php echo e($db); ?></span></td>
                    <td>
                        <div class="user-chips" id="chips-<?php echo e(md5($db)); ?>">
                        <?php $__currentLoopData = $privMap[$db] ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $u): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <span class="user-chip">
                                <i class="fas fa-user" style="font-size:.65rem;"></i>
                                <?php echo e($u); ?>

                                <button onclick="revokeUser('<?php echo e($u); ?>','<?php echo e($db); ?>')" title="Revoke">×</button>
                            </span>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        <?php if(empty($privMap[$db])): ?>
                            <span style="color:var(--text-muted);font-size:.75rem;">No users</span>
                        <?php endif; ?>
                        </div>
                    </td>
                    <td style="text-align:right;display:flex;gap:6px;justify-content:flex-end;align-items:center;">
                        <a href="<?php echo e(route('mysql.index', ['db' => $db])); ?>" class="db-btn" style="background:rgba(88,166,255,.15);border-color:rgba(88,166,255,.4);color:#58a6ff;text-decoration:none;">
                            <i class="fas fa-tools"></i> Manage
                        </a>
                        <button class="db-btn danger" onclick="deleteDatabase('<?php echo e($db); ?>', '<?php echo e(md5($db)); ?>')">
                            <i class="fas fa-trash-alt"></i> Delete
                        </button>
                    </td>
                </tr>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                <tr><td colspan="3">
                    <div class="db-empty"><i class="fas fa-database"></i>No databases yet. Create one above.</div>
                </td></tr>
                <?php endif; ?>
                </tbody>
            </table></div>
        </div>
    </div>

    
    <div class="db-panel" id="tab-users">
        <div class="db-section">
            <div class="db-section-head">
                <h3><i class="fas fa-user-plus" style="color:var(--db-purple);"></i> Create DB User</h3>
            </div>
            <div class="db-create-form">
                <div class="field">
                    <label>Username</label>
                    <div class="prefix-input">
                        <span class="pre"><?php echo e($prefix); ?></span>
                        <input class="db-input joined" id="newUserName" placeholder="dbuser" maxlength="10">
                    </div>
                </div>
                <div class="field">
                    <label>Password</label>
                    <div class="pw-wrap">
                        <input class="db-input" type="password" id="newUserPass" placeholder="Min 8 characters">
                        <button class="pw-toggle" type="button" onclick="togglePw('newUserPass',this)">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>
                <button class="db-btn primary" onclick="createUser()">
                    <i class="fas fa-plus"></i> Create
                </button>
            </div>
            <div class="db-table-wrap"><table class="db-table">
                <thead><tr>
                    <th>Username</th>
                    <th style="text-align:right;">Actions</th>
                </tr></thead>
                <tbody id="userTableBody">
                <?php $__empty_1 = true; $__currentLoopData = $dbUsers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $u): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                <tr id="urow-<?php echo e(md5($u)); ?>">
                    <td><span class="db-name" style="color:var(--db-purple);"><?php echo e($u); ?></span></td>
                    <td style="text-align:right;display:flex;gap:6px;justify-content:flex-end;">
                        <button class="db-btn amber" onclick="showChangePassword('<?php echo e($u); ?>')">
                            <i class="fas fa-key"></i> Password
                        </button>
                        <button class="db-btn danger" onclick="deleteUser('<?php echo e($u); ?>','<?php echo e(md5($u)); ?>')">
                            <i class="fas fa-trash-alt"></i> Delete
                        </button>
                    </td>
                </tr>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                <tr><td colspan="2">
                    <div class="db-empty"><i class="fas fa-user-shield"></i>No DB users yet.</div>
                </td></tr>
                <?php endif; ?>
                </tbody>
            </table></div>
        </div>
    </div>

    
    <div class="db-panel" id="tab-assign">
        <div class="db-section">
            <div class="db-section-head">
                <h3><i class="fas fa-link" style="color:var(--db-green);"></i> Assign User to Database</h3>
            </div>
            <div class="db-create-form">
                <div class="field">
                    <label>Database</label>
                    <select class="db-select db-input" id="assignDb">
                        <option value="">— Select Database —</option>
                        <?php $__currentLoopData = $databases; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $db): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($db); ?>"><?php echo e($db); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
                <div class="field">
                    <label>User</label>
                    <select class="db-select db-input" id="assignUser">
                        <option value="">— Select User —</option>
                        <?php $__currentLoopData = $dbUsers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $u): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        <option value="<?php echo e($u); ?>"><?php echo e($u); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>
                <div class="field">
                    <label>Privileges</label>
                    <select class="db-select db-input" id="assignPriv">
                        <option value="all">ALL PRIVILEGES</option>
                        <option value="rw">Read / Write</option>
                        <option value="ro">Read Only</option>
                    </select>
                </div>
                <button class="db-btn success" onclick="assignUser()">
                    <i class="fas fa-link"></i> Assign
                </button>
            </div>
            <div style="padding:1rem 1.4rem;">
                <p style="font-size:0.8rem;color:var(--text-muted);">
                    <i class="fas fa-info-circle" style="color:var(--db-blue);"></i>
                    After assigning, the user can log in to phpMyAdmin with the database credentials.
                </p>
            </div>
        </div>
    </div>

</div>


<div id="dbModalOverlay">
    <div id="dbModalBox">
        <h3><i class="fas fa-key" style="color:var(--db-amber);"></i> Change Password</h3>
        <input type="hidden" id="cpwUser">
        <div class="dbm-field">
            <label>Username</label>
            <div class="db-input" id="cpwUserDisplay" style="background:rgba(255,255,255,0.03);color:var(--text-muted);"></div>
        </div>
        <div class="dbm-field">
            <label>New Password</label>
            <div class="pw-wrap">
                <input class="db-input" type="password" id="cpwPass" placeholder="Min 8 characters" style="width:100%;">
                <button class="pw-toggle" type="button" onclick="togglePw('cpwPass',this)"><i class="fas fa-eye"></i></button>
            </div>
        </div>
        <div class="dbm-btns">
            <button class="db-btn" style="background:rgba(255,255,255,0.06);border:1px solid var(--border);color:var(--text-muted);" onclick="closeDbModal()">Cancel</button>
            <button class="db-btn primary" onclick="submitChangePassword()"><i class="fas fa-save"></i> Save</button>
        </div>
    </div>
</div>

<div id="dbToast"></div>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
const CSRF = "<?php echo e(csrf_token()); ?>";

// ── toast ──────────────────────────────────────────────────────
function dbToast(msg, type = 'ok') {
    const t = document.getElementById('dbToast');
    t.className = type;
    t.textContent = (type === 'ok' ? '✓ ' : '✗ ') + msg;
    t.style.display = 'block';
    clearTimeout(t._timer);
    t._timer = setTimeout(() => t.style.display = 'none', 3500);
}

// ── tabs ───────────────────────────────────────────────────────
function switchTab(id, btn) {
    document.querySelectorAll('.db-panel').forEach(p => p.classList.remove('active'));
    document.querySelectorAll('.db-tab').forEach(b => b.classList.remove('active'));
    document.getElementById('tab-' + id).classList.add('active');
    btn.classList.add('active');
}

// ── api helper ─────────────────────────────────────────────────
async function dbApi(url, body) {
    const r = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': CSRF },
        body: JSON.stringify(body)
    });
    return r.json();
}

// ── password toggle ────────────────────────────────────────────
function togglePw(id, btn) {
    const el = document.getElementById(id);
    const show = el.type === 'password';
    el.type = show ? 'text' : 'password';
    btn.querySelector('i').className = show ? 'fas fa-eye-slash' : 'fas fa-eye';
}

// ── modal ──────────────────────────────────────────────────────
function closeDbModal() { document.getElementById('dbModalOverlay').classList.remove('open'); }
document.getElementById('dbModalOverlay').addEventListener('click', e => {
    if (e.target === document.getElementById('dbModalOverlay')) closeDbModal();
});

// ── CREATE DATABASE ────────────────────────────────────────────
async function createDatabase() {
    const name = document.getElementById('newDbName').value.trim();
    if (!name) return dbToast('Enter a database name', 'err');
    const btn = event.target.closest('button');
    btn.disabled = true;
    const d = await dbApi("<?php echo e(route('db.create')); ?>", { name });
    btn.disabled = false;
    if (!d.success) return dbToast(d.message || 'Failed', 'err');
    dbToast('Database created: ' + d.db);
    document.getElementById('newDbName').value = '';
    // Add row to table
    const tbody = document.getElementById('dbTableBody');
    const emptyRow = tbody.querySelector('td[colspan]');
    if (emptyRow) emptyRow.closest('tr').remove();
    const hash = simpleHash(d.db);
    tbody.insertAdjacentHTML('beforeend', `
        <tr id="dbrow-${hash}">
            <td><span class="db-name">${d.db}</span></td>
            <td><div class="user-chips" id="chips-${hash}"><span style="color:var(--text-muted);font-size:.75rem;">No users</span></div></td>
            <td style="text-align:right;">
                <button class="db-btn danger" onclick="deleteDatabase('${d.db}','${hash}')">
                    <i class="fas fa-trash-alt"></i> Delete
                </button>
            </td>
        </tr>`);
    // Also add to assign dropdown
    document.getElementById('assignDb').insertAdjacentHTML('beforeend',
        `<option value="${d.db}">${d.db}</option>`);
}

// ── DELETE DATABASE ────────────────────────────────────────────
async function deleteDatabase(db, hash) {
    if (!await confirmDanger(`Delete database <b>${db}</b>?`, 'This cannot be undone. All data will be lost.')) return;
    const d = await dbApi("<?php echo e(route('db.delete')); ?>", { db });
    if (!d.success) return dbToast(d.message || 'Failed', 'err');
    document.getElementById('dbrow-' + hash)?.remove();
    // remove from assign dropdown
    document.querySelectorAll('#assignDb option').forEach(o => { if (o.value === db) o.remove(); });
    dbToast('Database deleted');
    if (!document.getElementById('dbTableBody').querySelector('tr')) {
        document.getElementById('dbTableBody').innerHTML =
            '<tr><td colspan="3"><div class="db-empty"><i class="fas fa-database"></i>No databases yet.</div></td></tr>';
    }
}

// ── CREATE USER ────────────────────────────────────────────────
async function createUser() {
    const username = document.getElementById('newUserName').value.trim();
    const password = document.getElementById('newUserPass').value;
    if (!username) return dbToast('Enter a username', 'err');
    if (password.length < 8) return dbToast('Password must be at least 8 characters', 'err');
    const btn = event.target.closest('button');
    btn.disabled = true;
    const d = await dbApi("<?php echo e(route('db.user.create')); ?>", { username, password });
    btn.disabled = false;
    if (!d.success) return dbToast(d.message || 'Failed', 'err');
    dbToast('User created: ' + d.user);
    document.getElementById('newUserName').value = '';
    document.getElementById('newUserPass').value = '';
    const tbody = document.getElementById('userTableBody');
    const emptyRow = tbody.querySelector('td[colspan]');
    if (emptyRow) emptyRow.closest('tr').remove();
    const hash = simpleHash(d.user);
    tbody.insertAdjacentHTML('beforeend', `
        <tr id="urow-${hash}">
            <td><span class="db-name" style="color:var(--db-purple);">${d.user}</span></td>
            <td style="text-align:right;display:flex;gap:6px;justify-content:flex-end;">
                <button class="db-btn amber" onclick="showChangePassword('${d.user}')"><i class="fas fa-key"></i> Password</button>
                <button class="db-btn danger" onclick="deleteUser('${d.user}','${hash}')"><i class="fas fa-trash-alt"></i> Delete</button>
            </td>
        </tr>`);
    // add to assign dropdown
    document.getElementById('assignUser').insertAdjacentHTML('beforeend',
        `<option value="${d.user}">${d.user}</option>`);
}

// ── DELETE USER ────────────────────────────────────────────────
async function deleteUser(username, hash) {
    if (!await confirmDanger(`Delete user <b>${username}</b>?`, 'The user will be removed from all databases.')) return;
    const d = await dbApi("<?php echo e(route('db.user.delete')); ?>", { username });
    if (!d.success) return dbToast(d.message || 'Failed', 'err');
    document.getElementById('urow-' + hash)?.remove();
    document.querySelectorAll('#assignUser option').forEach(o => { if (o.value === username) o.remove(); });
    dbToast('User deleted');
    if (!document.getElementById('userTableBody').querySelector('tr')) {
        document.getElementById('userTableBody').innerHTML =
            '<tr><td colspan="2"><div class="db-empty"><i class="fas fa-user-shield"></i>No DB users yet.</div></td></tr>';
    }
}

// ── CHANGE PASSWORD ────────────────────────────────────────────
function showChangePassword(username) {
    document.getElementById('cpwUser').value = username;
    document.getElementById('cpwUserDisplay').textContent = username;
    document.getElementById('cpwPass').value = '';
    document.getElementById('dbModalOverlay').classList.add('open');
    setTimeout(() => document.getElementById('cpwPass').focus(), 200);
}
async function submitChangePassword() {
    const username = document.getElementById('cpwUser').value;
    const password = document.getElementById('cpwPass').value;
    if (password.length < 8) return dbToast('Password must be at least 8 characters', 'err');
    const btn = event.target.closest('button');
    btn.disabled = true;
    const d = await dbApi("<?php echo e(route('db.user.password')); ?>", { username, password });
    btn.disabled = false;
    if (!d.success) return dbToast(d.message || 'Failed', 'err');
    closeDbModal();
    dbToast('Password changed successfully');
}

// ── ASSIGN USER ────────────────────────────────────────────────
async function assignUser() {
    const db       = document.getElementById('assignDb').value;
    const username = document.getElementById('assignUser').value;
    const priv     = document.getElementById('assignPriv').value;
    if (!db || !username) return dbToast('Select both a database and a user', 'err');
    const btn = event.target.closest('button');
    btn.disabled = true;
    const d = await dbApi("<?php echo e(route('db.assign')); ?>", { db, username, privileges: priv });
    btn.disabled = false;
    if (!d.success) return dbToast(d.message || 'Failed', 'err');
    dbToast(`${username} assigned to ${db}`);
    // add chip to database row
    const hash = simpleHash(db);
    const chips = document.getElementById('chips-' + hash);
    if (chips) {
        chips.querySelectorAll('span[style]').forEach(s => s.remove()); // remove "No users"
        chips.insertAdjacentHTML('beforeend', `
            <span class="user-chip">
                <i class="fas fa-user" style="font-size:.65rem;"></i>
                ${username}
                <button onclick="revokeUser('${username}','${db}')" title="Revoke">×</button>
            </span>`);
    }
}

// ── REVOKE USER ────────────────────────────────────────────────
async function revokeUser(username, db) {
    if (!await confirmDanger(`Revoke <b>${username}</b> from <b>${db}</b>?`, 'The user will lose access to this database.')) return;
    const d = await dbApi("<?php echo e(route('db.revoke')); ?>", { username, db });
    if (!d.success) return dbToast(d.message || 'Failed', 'err');
    dbToast('Access revoked');
    // remove chip
    const hash = simpleHash(db);
    const chips = document.getElementById('chips-' + hash);
    if (chips) {
        chips.querySelectorAll('.user-chip').forEach(c => {
            if (c.textContent.trim().includes(username)) c.remove();
        });
        if (!chips.querySelector('.user-chip'))
            chips.innerHTML = '<span style="color:var(--text-muted);font-size:.75rem;">No users</span>';
    }
}

// ── simple confirm (reuse style from file manager if available, else basic) ──
function confirmDanger(title, msg) {
    return new Promise(resolve => {
        // Inject a mini confirm if not already present
        let ov = document.getElementById('dbConfirmOv');
        if (!ov) {
            ov = document.createElement('div');
            ov.id = 'dbConfirmOv';
            ov.style.cssText = 'position:fixed;inset:0;z-index:99998;background:rgba(5,10,20,.8);backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;transition:opacity .2s;';
            ov.innerHTML = `<div style="background:linear-gradient(145deg,#0f172a,#1e293b);border:1px solid rgba(255,255,255,.08);border-radius:20px;padding:2rem;width:380px;max-width:92vw;box-shadow:0 24px 60px rgba(0,0,0,.5);text-align:center;">
                <div style="width:58px;height:58px;border-radius:50%;background:rgba(239,68,68,.12);border:1.5px solid rgba(239,68,68,.3);color:#ef4444;font-size:1.5rem;display:flex;align-items:center;justify-content:center;margin:0 auto 1rem;box-shadow:0 0 20px rgba(239,68,68,.18);">
                    <i class="fas fa-exclamation-triangle"></i></div>
                <div id="dbCfTitle" style="font-size:1rem;font-weight:700;color:#f1f5f9;margin-bottom:.4rem;"></div>
                <div id="dbCfMsg" style="font-size:.83rem;color:#94a3b8;margin-bottom:1.4rem;"></div>
                <div style="display:flex;gap:10px;">
                    <button id="dbCfCancel" style="flex:1;padding:9px;border-radius:9px;border:1px solid rgba(255,255,255,.1);background:rgba(255,255,255,.05);color:#94a3b8;cursor:pointer;font-size:.84rem;font-weight:600;">Cancel</button>
                    <button id="dbCfOk" style="flex:1;padding:9px;border-radius:9px;border:none;background:linear-gradient(135deg,#ef4444,#dc2626);color:#fff;cursor:pointer;font-size:.84rem;font-weight:600;box-shadow:0 4px 14px rgba(239,68,68,.35);">Delete</button>
                </div></div>`;
            document.body.appendChild(ov);
        }
        document.getElementById('dbCfTitle').innerHTML = title;
        document.getElementById('dbCfMsg').innerHTML = msg;
        ov.style.opacity = '0'; ov.style.pointerEvents = 'all'; ov.style.display = 'flex';
        requestAnimationFrame(() => ov.style.opacity = '1');
        const finish = v => { ov.style.opacity = '0'; setTimeout(() => ov.style.display = 'none', 200); resolve(v); };
        document.getElementById('dbCfOk').onclick    = () => finish(true);
        document.getElementById('dbCfCancel').onclick = () => finish(false);
    });
}

// ── simple hash for DOM IDs ────────────────────────────────────
function simpleHash(s) {
    let h = 0;
    for (let i = 0; i < s.length; i++) h = (Math.imul(31, h) + s.charCodeAt(i)) | 0;
    return Math.abs(h).toString(16);
}
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.dashboard', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/fullread/public_html/resources/views/dashboard/databases.blade.php ENDPATH**/ ?>