<?php $__env->startSection('content'); ?>
<style>
:root{--dm-bg:#0d1117;--dm-surface:#161b22;--dm-card:#21262d;--dm-border:#30363d;--dm-blue:#58a6ff;--dm-green:#3fb950;--dm-red:#f85149;--dm-yellow:#d29922;--dm-purple:#a371f7;--dm-text:#e6edf3;--dm-muted:#8b949e;}
.dm-wrap{font-family:'Outfit',sans-serif;color:var(--dm-text);}
.dm-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:20px;}
.dm-header h2{font-size:1.2rem;display:flex;align-items:center;gap:10px;}
.dm-header h2 i{color:var(--dm-blue);}

/* Domain cards grid */
.dm-domain-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(340px,1fr));gap:16px;margin-bottom:24px;}
.dm-domain-card{background:var(--dm-surface);border:1px solid var(--dm-border);border-radius:12px;overflow:hidden;}
.dm-domain-head{padding:14px 16px;background:var(--dm-card);border-bottom:1px solid var(--dm-border);display:flex;align-items:center;justify-content:space-between;}
.dm-domain-name{font-weight:700;font-size:.9rem;display:flex;align-items:center;gap:8px;}
.dm-domain-name i{color:var(--dm-blue);}
.dm-domain-badge{font-size:.65rem;padding:2px 8px;border-radius:10px;font-weight:600;text-transform:uppercase;}
.dm-badge-primary{background:rgba(88,166,255,.15);color:var(--dm-blue);}
.dm-badge-addon{background:rgba(163,113,247,.15);color:var(--dm-purple);}
.dm-domain-tabs{display:flex;border-bottom:1px solid var(--dm-border);}
.dm-dtab{flex:1;padding:8px;text-align:center;cursor:pointer;font-size:.75rem;color:var(--dm-muted);border-bottom:2px solid transparent;transition:all .15s;background:none;border-top:none;border-left:none;border-right:none;}
.dm-dtab:hover{color:var(--dm-text);}
.dm-dtab.active{color:var(--dm-blue);border-bottom-color:var(--dm-blue);}
.dm-domain-body{padding:14px;}
.dm-dpanel{display:none;}.dm-dpanel.active{display:block;}

/* Subdomain list */
.dm-sub-list{display:flex;flex-direction:column;gap:6px;margin-bottom:10px;max-height:180px;overflow-y:auto;}
.dm-sub-item{display:flex;align-items:center;gap:8px;padding:6px 10px;background:var(--dm-card);border:1px solid var(--dm-border);border-radius:7px;font-size:.78rem;}
.dm-sub-item .sub-name{flex:1;color:var(--dm-blue);}
.dm-sub-item .sub-dir{font-size:.68rem;color:var(--dm-muted);flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}

/* Add subdomain form */
.dm-add-form{display:flex;gap:6px;align-items:stretch;margin-top:8px;}
.dm-add-form input,.dm-add-form select{background:var(--dm-card);border:1px solid var(--dm-border);border-radius:7px;color:var(--dm-text);padding:6px 10px;font-size:.78rem;outline:none;flex:1;}
.dm-add-form input:focus{border-color:var(--dm-blue);}

/* DNS table */
.dm-dns-wrap{max-height:300px;overflow-y:auto;border:1px solid var(--dm-border);border-radius:8px;}
.dm-dns-table{width:100%;border-collapse:collapse;font-size:.73rem;}
.dm-dns-table th{background:var(--dm-card);color:var(--dm-muted);padding:6px 10px;text-align:left;border-bottom:1px solid var(--dm-border);font-size:.67rem;text-transform:uppercase;letter-spacing:.04em;position:sticky;top:0;z-index:2;}
.dm-dns-table td{padding:5px 10px;border-bottom:1px solid rgba(48,54,61,.4);vertical-align:middle;}
.dm-dns-table tr:hover td{background:rgba(88,166,255,.03);}
.dm-type-badge{display:inline-block;padding:1px 7px;border-radius:4px;font-size:.65rem;font-weight:700;}
.dm-type-a{background:rgba(88,166,255,.15);color:var(--dm-blue);}
.dm-type-mx{background:rgba(163,113,247,.15);color:var(--dm-purple);}
.dm-type-txt{background:rgba(63,185,80,.15);color:var(--dm-green);}
.dm-type-cname{background:rgba(210,153,34,.15);color:var(--dm-yellow);}
.dm-type-other{background:rgba(139,148,158,.12);color:var(--dm-muted);}

/* Add DNS form */
.dm-dns-add{background:var(--dm-card);border:1px solid var(--dm-border);border-radius:8px;padding:12px;margin-top:10px;}
.dm-dns-add h4{font-size:.76rem;color:var(--dm-muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:10px;}
.dm-dns-row{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:7px;margin-bottom:7px;}
.dm-dns-row input,.dm-dns-row select{background:var(--dm-bg);border:1px solid var(--dm-border);border-radius:6px;color:var(--dm-text);padding:5px 8px;font-size:.76rem;outline:none;width:100%;}
.dm-dns-row input:focus,.dm-dns-row select:focus{border-color:var(--dm-blue);}

/* Buttons */
.dm-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;white-space:nowrap;}
.dm-btn.blue{background:rgba(88,166,255,.12);border-color:var(--dm-blue);color:var(--dm-blue);}.dm-btn.blue:hover{background:var(--dm-blue);color:#000;}
.dm-btn.green{background:rgba(63,185,80,.12);border-color:var(--dm-green);color:var(--dm-green);}.dm-btn.green:hover{background:var(--dm-green);color:#000;}
.dm-btn.red{background:rgba(248,81,73,.12);border-color:var(--dm-red);color:var(--dm-red);}.dm-btn.red:hover{background:var(--dm-red);color:#fff;}
.dm-btn.ghost{background:transparent;border-color:var(--dm-border);color:var(--dm-muted);}.dm-btn.ghost:hover{border-color:var(--dm-blue);color:var(--dm-blue);}
.dm-btn.xs{padding:3px 8px;font-size:.68rem;}

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

/* Loader spinner */
.dm-spin{display:inline-block;animation:dm-spin-anim .6s linear infinite;}
@keyframes dm-spin-anim{to{transform:rotate(360deg);}}

/* Empty */
.dm-empty{padding:20px;text-align:center;color:var(--dm-muted);font-size:.78rem;}
.dm-empty i{font-size:1.5rem;display:block;margin-bottom:8px;opacity:.3;}
</style>

<div class="dm-wrap">
    <div class="dm-header">
        <h2><i class="fas fa-globe"></i> Domain Manager</h2>
    </div>

    <?php if(empty($userDomains)): ?>
    <div style="background:var(--dm-surface);border:1px solid var(--dm-border);border-radius:12px;padding:40px;text-align:center;color:var(--dm-muted);">
        <i class="fas fa-globe" style="font-size:2.5rem;display:block;margin-bottom:12px;opacity:.3;"></i>
        <p>No domains found. Add a domain from the <a href="<?php echo e(route('domains')); ?>" style="color:var(--dm-blue);">Domains</a> page first.</p>
    </div>
    <?php else: ?>
    <div class="dm-domain-grid">
        <?php $__currentLoopData = $userDomains; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $domain): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
        <?php $isPrimary = $domain === Auth::user()->primary_domain; ?>
        <div class="dm-domain-card" id="dcard-<?php echo e(md5($domain)); ?>">
            <div class="dm-domain-head">
                <div class="dm-domain-name">
                    <i class="fas fa-globe"></i>
                    <span><?php echo e($domain); ?></span>
                </div>
                <span class="dm-domain-badge <?php echo e($isPrimary ? 'dm-badge-primary' : 'dm-badge-addon'); ?>">
                    <?php echo e($isPrimary ? 'Primary' : 'Addon'); ?>

                </span>
            </div>
            <div class="dm-domain-tabs">
                <button class="dm-dtab active" onclick="dmTab('<?php echo e(md5($domain)); ?>','sub',this)"><i class="fas fa-sitemap"></i> Subdomains</button>
                <button class="dm-dtab" onclick="dmTab('<?php echo e(md5($domain)); ?>','dns',this)"><i class="fas fa-network-wired"></i> DNS Records</button>
            </div>
            <div class="dm-domain-body">
                
                <div class="dm-dpanel active" id="dpanel-sub-<?php echo e(md5($domain)); ?>">
                    <div class="dm-sub-list" id="sublist-<?php echo e(md5($domain)); ?>">
                        <?php if(!empty($allSubdomains[$domain])): ?>
                            <?php $__currentLoopData = $allSubdomains[$domain]; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $sub): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php $fullSub = ($sub['domain'] ?? '') . '.' . ($sub['rootdomain'] ?? $domain); ?>
                            <div class="dm-sub-item" id="sub-<?php echo e(md5($fullSub)); ?>">
                                <i class="fas fa-angle-right" style="color:var(--dm-muted);font-size:.7rem;"></i>
                                <span class="sub-name"><?php echo e($fullSub); ?></span>
                                <span class="sub-dir"><?php echo e($sub['dir'] ?? ''); ?></span>
                                <button class="dm-btn red xs" onclick="deleteSub('<?php echo e($fullSub); ?>','<?php echo e(md5($fullSub)); ?>')">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        <?php else: ?>
                            <div class="dm-empty" id="sub-empty-<?php echo e(md5($domain)); ?>"><i class="fas fa-sitemap"></i>No subdomains</div>
                        <?php endif; ?>
                    </div>
                    <div class="dm-add-form">
                        <input type="text" id="newSub-<?php echo e(md5($domain)); ?>" placeholder="sub (e.g. blog)" style="flex:1.2;">
                        <span style="display:flex;align-items:center;padding:0 4px;font-size:.8rem;color:var(--dm-muted);">.<?php echo e($domain); ?></span>
                        <button class="dm-btn green" onclick="createSub('<?php echo e($domain); ?>','<?php echo e(md5($domain)); ?>')">
                            <i class="fas fa-plus"></i> Add
                        </button>
                    </div>
                </div>

                
                <div class="dm-dpanel" id="dpanel-dns-<?php echo e(md5($domain)); ?>" data-loaded="0" data-domain="<?php echo e($domain); ?>">
                    <div id="dns-content-<?php echo e(md5($domain)); ?>">
                        <div class="dm-empty"><i class="fas fa-circle-notch dm-spin"></i></div>
                    </div>
                    
                    <div class="dm-dns-add">
                        <h4><i class="fas fa-plus-circle" style="color:var(--dm-green);margin-right:4px;"></i> Add DNS Record</h4>
                        <div class="dm-dns-row">
                            <select id="dnsType-<?php echo e(md5($domain)); ?>" onchange="toggleDnsFields('<?php echo e(md5($domain)); ?>',this.value)">
                                <option value="A">A</option>
                                <option value="AAAA">AAAA</option>
                                <option value="CNAME">CNAME</option>
                                <option value="MX">MX</option>
                                <option value="TXT">TXT</option>
                            </select>
                            <input type="text" id="dnsName-<?php echo e(md5($domain)); ?>" placeholder="Name (e.g. @, sub)">
                            <input type="number" id="dnsTtl-<?php echo e(md5($domain)); ?>" placeholder="TTL" value="14400" style="width:80px;">
                        </div>
                        <div class="dm-dns-row" id="dnsExtra-<?php echo e(md5($domain)); ?>">
                            <input type="text" id="dnsVal-<?php echo e(md5($domain)); ?>" placeholder="Value / IP / Target" style="grid-column:1/-1;">
                        </div>
                        <div style="margin-top:6px;">
                            <button class="dm-btn green" onclick="addDns('<?php echo e($domain); ?>','<?php echo e(md5($domain)); ?>')"><i class="fas fa-plus"></i> Add Record</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    </div>
    <?php endif; ?>
</div>

<div class="dm-toast" id="dmToastArea"></div>

<script>
const CSRF = '<?php echo e(csrf_token()); ?>';

// ── Tab switching ────────────────────────────────────────────
function dmTab(hash, name, btn) {
    document.querySelectorAll(`#dcard-${hash} .dm-dtab`).forEach(b => b.classList.remove('active'));
    document.querySelectorAll(`#dcard-${hash} .dm-dpanel`).forEach(p => p.classList.remove('active'));
    btn.classList.add('active');
    document.getElementById(`dpanel-${name}-${hash}`).classList.add('active');

    // Load DNS on first open
    if (name === 'dns') {
        const panel = document.getElementById(`dpanel-dns-${hash}`);
        if (panel.dataset.loaded === '0') {
            panel.dataset.loaded = '1';
            loadDns(panel.dataset.domain, hash);
        }
    }
}

// ── Toast ────────────────────────────────────────────────────
function dmToast(msg, type='ok') {
    const area = document.getElementById('dmToastArea');
    const el = document.createElement('div');
    el.className = `dm-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);
}

// ── API helper ───────────────────────────────────────────────
async function dmApi(url, method='POST', data={}) {
    const r = await fetch(url, {
        method,
        headers: {'Content-Type':'application/json','X-CSRF-TOKEN':CSRF,'X-Requested-With':'XMLHttpRequest'},
        body: method !== 'GET' ? JSON.stringify(data) : undefined,
    });
    return r.json();
}

// ── Subdomains ───────────────────────────────────────────────
async function createSub(domain, hash) {
    const input = document.getElementById(`newSub-${hash}`);
    const sub   = input.value.trim();
    if (!sub) return dmToast('Enter subdomain name', 'err');

    const d = await dmApi('<?php echo e(route("domain.sub.create")); ?>', 'POST', { subdomain: sub, root_domain: domain });
    if (!d.success) return dmToast(d.message || d.error || 'Failed', 'err');

    dmToast(`${d.full} created!`);
    input.value = '';
    const list = document.getElementById(`sublist-${hash}`);
    // Remove empty state
    document.getElementById(`sub-empty-${hash}`)?.remove();
    const id = btoa(d.full).replace(/=/g,'');
    list.insertAdjacentHTML('beforeend', `
        <div class="dm-sub-item" id="sub-${id}">
            <i class="fas fa-angle-right" style="color:var(--dm-muted);font-size:.7rem;"></i>
            <span class="sub-name">${d.full}</span>
            <span class="sub-dir">${d.dir || ('domains/' + domain + '/' + sub)}</span>
            <button class="dm-btn red xs" onclick="deleteSub('${d.full}','${id}')">
                <i class="fas fa-trash"></i>
            </button>
        </div>`);
}

async function deleteSub(subdomain, id) {
    if (!confirm(`Delete subdomain ${subdomain}?`)) return;
    const d = await dmApi('<?php echo e(route("domain.sub.delete")); ?>', 'DELETE', { subdomain });
    if (!d.success) return dmToast(d.message || d.error || 'Failed', 'err');
    document.getElementById(`sub-${id}`)?.remove();
    dmToast(`${subdomain} deleted`);
}

// ── DNS Records ──────────────────────────────────────────────
async function loadDns(domain, hash) {
    const wrap = document.getElementById(`dns-content-${hash}`);
    wrap.innerHTML = '<div class="dm-empty"><i class="fas fa-circle-notch dm-spin"></i> Loading DNS records…</div>';
    try {
        const r = await fetch(`/domain-manager/${encodeURIComponent(domain)}/dns`, {
            headers: {'X-Requested-With':'XMLHttpRequest'}
        });
        const d = await r.json();
        if (d.error) { wrap.innerHTML=`<div class="dm-empty" style="color:var(--dm-red);">${d.error}</div>`; return; }
        renderDns(d.records, domain, hash, wrap);
    } catch(e) { wrap.innerHTML=`<div class="dm-empty" style="color:var(--dm-red);">${e.message}</div>`; }
}

function renderDns(records, domain, hash, wrap) {
    if (!records.length) { wrap.innerHTML='<div class="dm-empty"><i class="fas fa-network-wired"></i>No DNS records</div>'; return; }
    const typeClass = t => {
        if(t==='A'||t==='AAAA') return 'dm-type-a';
        if(t==='MX') return 'dm-type-mx';
        if(t==='TXT') return 'dm-type-txt';
        if(t==='CNAME') return 'dm-type-cname';
        return 'dm-type-other';
    };
    const val = r => r.address || r.cname || r.exchange || r.txtdata || r.target || r.data_b64 || '';
    let h = `<div class="dm-dns-wrap"><table class="dm-dns-table">
        <thead><tr><th>Type</th><th>Name</th><th>Value</th><th>TTL</th><th></th></tr></thead>
        <tbody>`;
    records.forEach(r => {
        if (!r.type || r.type === 'SOA') return;
        const v = String(val(r)).slice(0, 60);
        h += `<tr>
            <td><span class="dm-type-badge ${typeClass(r.type)}">${r.type}</span></td>
            <td style="max-width:120px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="${r.name||''}">${r.name||''}</td>
            <td style="max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:monospace;font-size:.7rem;" title="${v}">${v}</td>
            <td style="color:var(--dm-muted);">${r.ttl||''}</td>
            <td>${r.line !== undefined ? `<button class="dm-btn red xs" onclick="deleteDns('${domain}','${hash}',${r.line})"><i class="fas fa-trash"></i></button>` : ''}</td>
        </tr>`;
    });
    h += '</tbody></table></div>';
    wrap.innerHTML = h;
}

async function addDns(domain, hash) {
    const type = document.getElementById(`dnsType-${hash}`).value;
    const name = document.getElementById(`dnsName-${hash}`).value.trim();
    const ttl  = parseInt(document.getElementById(`dnsTtl-${hash}`).value) || 14400;
    const val  = document.getElementById(`dnsVal-${hash}`).value.trim();
    if (!name || !val) return dmToast('Enter name and value', 'err');

    const payload = { type, name, ttl };
    if (type==='A'||type==='AAAA') payload.address   = val;
    else if (type==='CNAME')        payload.cname     = val;
    else if (type==='MX')           payload.exchange  = val;
    else if (type==='TXT')          payload.txtdata   = val;

    const d = await dmApi(`/domain-manager/${encodeURIComponent(domain)}/dns`, 'POST', payload);
    if (!d.success) return dmToast(d.message || d.error || 'Failed', 'err');
    dmToast('DNS record added!');
    document.getElementById(`dnsName-${hash}`).value = '';
    document.getElementById(`dnsVal-${hash}`).value  = '';
    // Reload DNS
    loadDns(domain, hash);
}

async function deleteDns(domain, hash, line) {
    if (!confirm('Delete this DNS record?')) return;
    const d = await dmApi(`/domain-manager/${encodeURIComponent(domain)}/dns`, 'DELETE', { line });
    if (!d.success) return dmToast(d.message || d.error || 'Failed', 'err');
    dmToast('DNS record deleted');
    loadDns(domain, hash);
}

function toggleDnsFields(hash, type) {
    const el = document.getElementById(`dnsVal-${hash}`);
    const hints = { A:'IP Address (e.g. 1.2.3.4)', AAAA:'IPv6 Address', CNAME:'Target (e.g. example.com)', MX:'Mail server (e.g. mail.domain.com)', TXT:'Text value' };
    el.placeholder = hints[type] || 'Value';
}
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.dashboard', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Program Files\Ampps\www\resources\views/dashboard/domain_manager.blade.php ENDPATH**/ ?>