
<?php $__env->startSection('content'); ?>
<style>
:root{--em-bg:#0d1117;--em-surface:#161b22;--em-card:#21262d;--em-border:#30363d;--em-blue:#58a6ff;--em-green:#3fb950;--em-red:#f85149;--em-yellow:#d29922;--em-purple:#a371f7;--em-text:#e6edf3;--em-muted:#8b949e;}
.em-wrap{font-family:'Outfit',sans-serif;color:var(--em-text);}

/* Toolbar */
.em-toolbar{display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;gap:12px;flex-wrap:wrap;}
.em-toolbar h2{font-size:1.2rem;display:flex;align-items:center;gap:10px;}
.em-toolbar h2 i{color:var(--em-blue);}

/* Stats bar */
.em-stats{display:flex;gap:12px;margin-bottom:20px;flex-wrap:wrap;}
.em-stat{background:var(--em-surface);border:1px solid var(--em-border);border-radius:10px;padding:12px 18px;display:flex;align-items:center;gap:10px;}
.em-stat i{font-size:1.1rem;color:var(--em-blue);}
.em-stat-val{font-size:1.2rem;font-weight:700;}
.em-stat-lbl{font-size:.68rem;color:var(--em-muted);}

/* Email table */
.em-table-wrap{background:var(--em-surface);border:1px solid var(--em-border);border-radius:12px;overflow:hidden;}
.em-table{width:100%;border-collapse:collapse;font-size:.8rem;}
.em-table th{background:var(--em-card);color:var(--em-muted);padding:10px 14px;text-align:left;border-bottom:1px solid var(--em-border);font-size:.68rem;text-transform:uppercase;letter-spacing:.05em;}
.em-table td{padding:10px 14px;border-bottom:1px solid rgba(48,54,61,.4);vertical-align:middle;}
.em-table tr:last-child td{border-bottom:none;}
.em-table tr:hover td{background:rgba(88,166,255,.03);}
.em-avatar{width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,#58a6ff,#a371f7);display:flex;align-items:center;justify-content:center;font-weight:700;font-size:.75rem;color:#fff;flex-shrink:0;}
.em-email-info{display:flex;align-items:center;gap:10px;}
.em-email-name{font-weight:600;color:var(--em-text);}
.em-email-addr{font-size:.72rem;color:var(--em-muted);}
.em-quota-bar{width:80px;height:5px;background:var(--em-border);border-radius:3px;overflow:hidden;margin-top:3px;}
.em-quota-fill{height:100%;border-radius:3px;background:var(--em-green);}
.em-quota-fill.warn{background:var(--em-yellow);}
.em-quota-fill.full{background:var(--em-red);}

/* Buttons */
.em-btn{display:inline-flex;align-items:center;gap:5px;padding:5px 12px;border-radius:7px;font-size:.75rem;font-weight:600;cursor:pointer;border:1px solid;transition:all .13s;}
.em-btn.blue{background:rgba(88,166,255,.12);border-color:var(--em-blue);color:var(--em-blue);}.em-btn.blue:hover{background:var(--em-blue);color:#000;}
.em-btn.green{background:rgba(63,185,80,.12);border-color:var(--em-green);color:var(--em-green);}.em-btn.green:hover{background:var(--em-green);color:#000;}
.em-btn.red{background:rgba(248,81,73,.12);border-color:var(--em-red);color:var(--em-red);}.em-btn.red:hover{background:var(--em-red);color:#fff;}
.em-btn.purple{background:rgba(163,113,247,.12);border-color:var(--em-purple);color:var(--em-purple);}.em-btn.purple:hover{background:var(--em-purple);color:#fff;}
.em-btn.ghost{background:transparent;border-color:var(--em-border);color:var(--em-muted);}.em-btn.ghost:hover{border-color:var(--em-blue);color:var(--em-blue);}
.em-btn.xs{padding:3px 9px;font-size:.7rem;}
.em-btn.sm{padding:5px 12px;}

/* Modals */
.em-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.65);backdrop-filter:blur(4px);z-index:900;align-items:center;justify-content:center;}
.em-overlay.show{display:flex;}
.em-modal{background:var(--em-surface);border:1px solid var(--em-border);border-radius:14px;width:min(440px,90vw);padding:24px;animation:em-pop .25s ease;}
@keyframes em-pop{from{transform:scale(.92);opacity:0;}to{transform:scale(1);opacity:1;}}
.em-modal h3{font-size:.95rem;margin-bottom:16px;display:flex;align-items:center;gap:8px;}
.em-modal h3 i{color:var(--em-blue);}
.em-field{margin-bottom:12px;}
.em-field label{display:block;font-size:.73rem;color:var(--em-muted);margin-bottom:4px;}
.em-field input,.em-field select{width:100%;background:var(--em-card);border:1px solid var(--em-border);border-radius:7px;color:var(--em-text);padding:8px 12px;font-size:.82rem;outline:none;}
.em-field input:focus,.em-field select:focus{border-color:var(--em-blue);}
.em-field-row{display:grid;grid-template-columns:1fr 1fr;gap:10px;}
.em-modal-footer{display:flex;gap:8px;justify-content:flex-end;margin-top:16px;border-top:1px solid var(--em-border);padding-top:14px;}
.em-pw-toggle{position:relative;}
.em-pw-toggle input{padding-right:36px;}
.em-pw-toggle .eye{position:absolute;right:10px;top:50%;transform:translateY(-50%);cursor:pointer;color:var(--em-muted);font-size:.8rem;}

/* Toast */
.em-toast{position:fixed;bottom:24px;right:24px;z-index:9999;display:flex;flex-direction:column;gap:6px;}
.em-toast-item{padding:10px 18px;border-radius:8px;font-size:.8rem;font-weight:600;animation:em-slide-in .3s ease;box-shadow:0 6px 20px rgba(0,0,0,.4);}
.em-toast-item.ok{background:#3fb950;color:#000;}.em-toast-item.err{background:#f85149;color:#fff;}.em-toast-item.info{background:#58a6ff;color:#000;}
@keyframes em-slide-in{from{transform:translateX(100%);opacity:0;}to{transform:translateX(0);opacity:1;}}
</style>

<div class="em-wrap">
    <div class="em-toolbar">
        <h2><i class="fas fa-envelope"></i> Email Accounts</h2>
        <div style="display:flex;gap:8px;flex-wrap:wrap;">
            <a href="<?php echo e($webmailUrl); ?>" target="_blank" class="em-btn purple">
                <i class="fas fa-sign-in-alt"></i> Webmail Login
            </a>
            <button class="em-btn green" onclick="openCreate()">
                <i class="fas fa-plus"></i> Create Email
            </button>
        </div>
    </div>

    
    <div class="em-stats">
        <div class="em-stat">
            <i class="fas fa-envelope"></i>
            <div><div class="em-stat-val"><?php echo e(count($emails)); ?></div><div class="em-stat-lbl">Email Accounts</div></div>
        </div>
        <div class="em-stat">
            <i class="fas fa-globe"></i>
            <div><div class="em-stat-val"><?php echo e(count($userDomains)); ?></div><div class="em-stat-lbl">Domains</div></div>
        </div>
    </div>

    
    <div class="em-table-wrap">
        <table class="em-table" id="emailTable">
            <thead>
                <tr>
                    <th>Email</th>
                    <th>Domain</th>
                    <th>Disk Usage</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="emailTbody">
                <?php $__empty_1 = true; $__currentLoopData = $emails; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $acc): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                <?php
                    $name   = $acc['email'] ?? ($acc['login'] ?? '');
                    $domain = $acc['_domain'] ?? ($acc['domain'] ?? '');
                    $full   = $name . '@' . $domain;
                    $quota  = $acc['_max_quota_bytes'] ?? ($acc['diskquota'] ?? 0);
                    $used   = $acc['_diskused_bytes']  ?? ($acc['diskused']  ?? 0);
                    $letter = strtoupper(substr($name, 0, 1)) ?: 'E';
                    $pct    = $quota > 0 ? min(100, round(($used/$quota)*100)) : 0;
                    $cls    = $pct >= 90 ? 'full' : ($pct >= 75 ? 'warn' : '');
                ?>
                <tr id="erow-<?php echo e(md5($full)); ?>">
                    <td>
                        <div class="em-email-info">
                            <div class="em-avatar"><?php echo e($letter); ?></div>
                            <div>
                                <div class="em-email-name"><?php echo e($name); ?></div>
                                <div class="em-email-addr"><?php echo e($full); ?></div>
                            </div>
                        </div>
                    </td>
                    <td style="color:var(--em-muted);"><?php echo e($domain); ?></td>
                    <td>
                        <?php if($quota > 0): ?>
                            <div style="font-size:.72rem;color:var(--em-muted);"><?php echo e(round($used/1048576,1)); ?> / <?php echo e(round($quota/1048576)); ?> MB</div>
                            <div class="em-quota-bar"><div class="em-quota-fill <?php echo e($cls); ?>" style="width:<?php echo e($pct); ?>%"></div></div>
                        <?php else: ?>
                            <span style="font-size:.72rem;color:var(--em-muted);">Unlimited</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div style="display:flex;gap:5px;flex-wrap:wrap;">
                            <a href="<?php echo e($webmailUrl); ?>" target="_blank" class="em-btn ghost xs">
                                <i class="fas fa-sign-in-alt"></i> Webmail
                            </a>
                            <button class="em-btn blue xs" onclick="openPwd('<?php echo e($name); ?>','<?php echo e($domain); ?>')">
                                <i class="fas fa-key"></i> Password
                            </button>
                            <button class="em-btn red xs" onclick="deleteEmail('<?php echo e($name); ?>','<?php echo e($domain); ?>','<?php echo e(md5($full)); ?>')">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                <tr id="emptyRow">
                    <td colspan="4" style="padding:40px;text-align:center;color:var(--em-muted);">
                        <i class="fas fa-envelope" style="font-size:2rem;display:block;margin-bottom:8px;opacity:.3;"></i>
                        No email accounts yet. Click <strong>Create Email</strong> to add one.
                    </td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>


<div class="em-overlay" id="createModal">
    <div class="em-modal">
        <h3><i class="fas fa-plus-circle"></i> Create Email Account</h3>
        <div class="em-field-row">
            <div class="em-field">
                <label>Username</label>
                <input type="text" id="newEmailUser" placeholder="e.g. info, support">
            </div>
            <div class="em-field">
                <label>Domain</label>
                <select id="newEmailDomain">
                    <?php $__currentLoopData = $userDomains; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $dom): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <option value="<?php echo e($dom); ?>"><?php echo e($dom); ?></option>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </select>
            </div>
        </div>
        <div class="em-field">
            <label>Password</label>
            <div class="em-pw-toggle">
                <input type="password" id="newEmailPass" placeholder="Min. 8 characters">
                <i class="fas fa-eye eye" id="eyeCreate" onclick="toggleEye('newEmailPass','eyeCreate')"></i>
            </div>
        </div>
        <div class="em-field-row">
            <div class="em-field">
                <label>Quota (MB) — 0 = Unlimited</label>
                <input type="number" id="newEmailQuota" value="250" min="0" max="10240">
            </div>
        </div>
        <div class="em-modal-footer">
            <button class="em-btn ghost" onclick="closeModal('createModal')">Cancel</button>
            <button class="em-btn green" id="createBtn" onclick="createEmail()"><i class="fas fa-plus"></i> Create</button>
        </div>
    </div>
</div>


<div class="em-overlay" id="pwdModal">
    <div class="em-modal">
        <h3><i class="fas fa-key"></i> Change Email Password</h3>
        <div style="padding:8px 12px;background:rgba(88,166,255,.08);border:1px solid rgba(88,166,255,.25);border-radius:8px;margin-bottom:14px;font-size:.78rem;color:var(--em-blue);">
            <i class="fas fa-envelope" style="margin-right:6px;"></i>
            <span id="pwdEmailDisplay">-</span>
        </div>
        <div class="em-field">
            <label>New Password</label>
            <div class="em-pw-toggle">
                <input type="password" id="newPwd" placeholder="Min. 8 characters">
                <i class="fas fa-eye eye" id="eyePwd" onclick="toggleEye('newPwd','eyePwd')"></i>
            </div>
        </div>
        <div class="em-modal-footer">
            <button class="em-btn ghost" onclick="closeModal('pwdModal')">Cancel</button>
            <button class="em-btn blue" id="pwdBtn" onclick="changePassword()"><i class="fas fa-save"></i> Update</button>
        </div>
    </div>
</div>

<div class="em-toast" id="emToastArea"></div>

<script>
const CSRF = '<?php echo e(csrf_token()); ?>';
let pwdTarget = { email: '', domain: '' };

function emToast(msg, type='ok') {
    const area = document.getElementById('emToastArea');
    const el   = document.createElement('div');
    el.className = `em-toast-item ${type}`;
    el.innerHTML = `<i class="fas fa-${type==='ok'?'check-circle':type==='err'?'exclamation-circle':'info-circle'}"></i> ${msg}`;
    area.appendChild(el);
    setTimeout(() => el.remove(), 3500);
}

async function emApi(url, method, data={}) {
    const r = await fetch(url, {
        method,
        headers: {'Content-Type':'application/json','X-CSRF-TOKEN':CSRF,'X-Requested-With':'XMLHttpRequest'},
        body: ['GET','HEAD'].includes(method) ? undefined : JSON.stringify(data),
    });
    return r.json();
}

function openCreate() { document.getElementById('createModal').classList.add('show'); }
function closeModal(id) { document.getElementById(id).classList.remove('show'); }
function openPwd(email, domain) {
    pwdTarget = { email, domain };
    document.getElementById('pwdEmailDisplay').textContent = email + '@' + domain;
    document.getElementById('newPwd').value = '';
    document.getElementById('pwdModal').classList.add('show');
}
function toggleEye(inputId, eyeId) {
    const i = document.getElementById(inputId);
    const e = document.getElementById(eyeId);
    if (i.type === 'password') { i.type = 'text'; e.classList.replace('fa-eye','fa-eye-slash'); }
    else { i.type = 'password'; e.classList.replace('fa-eye-slash','fa-eye'); }
}

async function createEmail() {
    const user   = document.getElementById('newEmailUser').value.trim();
    const domain = document.getElementById('newEmailDomain').value;
    const pass   = document.getElementById('newEmailPass').value;
    const quota  = parseInt(document.getElementById('newEmailQuota').value) || 0;
    if (!user || !pass) return emToast('Fill all required fields', 'err');
    if (pass.length < 8) return emToast('Password must be at least 8 characters', 'err');

    const btn = document.getElementById('createBtn');
    btn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Creating…'; btn.disabled = true;

    const d = await emApi('<?php echo e(route("email.create")); ?>', 'POST', { email: user, domain, password: pass, quota });
    btn.innerHTML = '<i class="fas fa-plus"></i> Create'; btn.disabled = false;

    if (!d.success) return emToast(d.message || d.error || 'Failed', 'err');
    emToast(`${d.full} created!`);
    closeModal('createModal');

    // Add to table
    document.getElementById('emptyRow')?.remove();
    const letter = user.charAt(0).toUpperCase();
    const full   = d.full;
    const hash   = btoa(full).replace(/=/g,'');
    document.getElementById('emailTbody').insertAdjacentHTML('beforeend', `
        <tr id="erow-${hash}">
            <td>
                <div class="em-email-info">
                    <div class="em-avatar">${letter}</div>
                    <div>
                        <div class="em-email-name">${user}</div>
                        <div class="em-email-addr">${full}</div>
                    </div>
                </div>
            </td>
            <td style="color:var(--em-muted);">${domain}</td>
            <td><span style="font-size:.72rem;color:var(--em-muted);">Unlimited</span></td>
            <td>
                <div style="display:flex;gap:5px;flex-wrap:wrap;">
                    <a href="<?php echo e($webmailUrl); ?>" target="_blank" class="em-btn ghost xs"><i class="fas fa-sign-in-alt"></i> Webmail</a>
                    <button class="em-btn blue xs" onclick="openPwd('${user}','${domain}')"><i class="fas fa-key"></i> Password</button>
                    <button class="em-btn red xs" onclick="deleteEmail('${user}','${domain}','${hash}')"><i class="fas fa-trash"></i></button>
                </div>
            </td>
        </tr>`);
    document.getElementById('newEmailUser').value  = '';
    document.getElementById('newEmailPass').value  = '';
}

async function changePassword() {
    const pass = document.getElementById('newPwd').value;
    if (pass.length < 8) return emToast('Password must be at least 8 characters', 'err');
    const btn = document.getElementById('pwdBtn');
    btn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Saving…'; btn.disabled = true;

    const d = await emApi('<?php echo e(route("email.password")); ?>', 'POST', { email: pwdTarget.email, domain: pwdTarget.domain, password: pass });
    btn.innerHTML = '<i class="fas fa-save"></i> Update'; btn.disabled = false;

    if (!d.success) return emToast(d.message || d.error || 'Failed', 'err');
    emToast('Password updated!');
    closeModal('pwdModal');
}

async function deleteEmail(email, domain, hash) {
    if (!confirm(`Delete ${email}@${domain}? This cannot be undone.`)) return;
    const d = await emApi('<?php echo e(route("email.delete")); ?>', 'DELETE', { email, domain });
    if (!d.success) return emToast(d.message || d.error || 'Failed', 'err');
    document.getElementById(`erow-${hash}`)?.remove();
    emToast(`${email}@${domain} deleted`);
}

// Close modals on backdrop click
document.querySelectorAll('.em-overlay').forEach(o => {
    o.addEventListener('click', e => { if(e.target === o) o.classList.remove('show'); });
});
</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/emails.blade.php ENDPATH**/ ?>