@extends('layouts.dashboard')

@section('styles')
    <style>
        .content-card {
            background: var(--bg-card);
            border-radius: 24px;
            padding: 2rem;
            border: 1px solid var(--border);
        }

        .table-container {
            width: 100%;
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1.5rem;
        }

        th {
            text-align: left;
            color: var(--text-muted);
            font-weight: 600;
            padding-bottom: 1rem;
            border-bottom: 1px solid var(--border);
        }

        td {
            padding: 1.25rem 0;
            border-bottom: 1px solid var(--border);
        }

        .type-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.8rem;
            background: rgba(56, 189, 248, 0.1);
            color: var(--accent);
        }

        /* Modal Styling */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6);
            backdrop-filter: blur(5px);
        }

        .modal-content {
            background: var(--bg-card);
            margin: 10% auto;
            padding: 2.5rem;
            border: 1px solid var(--border);
            border-radius: 24px;
            width: 100%;
            max-width: 500px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        label {
            display: block;
            margin-bottom: 0.5rem;
            font-size: 0.9rem;
            color: var(--text-muted);
        }

        input {
            width: 100%;
            padding: 0.75rem 1rem;
            background: rgba(15, 23, 42, 0.5);
            border: 1px solid var(--border);
            border-radius: 12px;
            color: white;
        }

        .btn-submit {
            width: 100%;
            padding: 0.8rem;
            background: var(--primary);
            border: none;
            border-radius: 12px;
            color: white;
            font-weight: 600;
            cursor: pointer;
        }
    </style>
@endsection

@section('content')
    <div class="animate-fade">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
            <h2>Domain Management</h2>
            <button id="openModal" class="btn-create" style="border:none; cursor:pointer;">
                <i class="fas fa-plus"></i> Add Domain
            </button>
        </div>

        @if(session('success'))
            <div
                style="background: rgba(16, 185, 129, 0.1); color: #10b981; padding: 1rem; border-radius: 12px; margin-bottom: 2rem; border: 1px solid rgba(16, 185, 129, 0.3);">
                <i class="fas fa-check-circle"></i> {{ session('success') }}
            </div>
        @endif

        @if(session('error'))
            <div
                style="background: rgba(239, 68, 68, 0.1); color: #ef4444; padding: 1rem; border-radius: 12px; margin-bottom: 2rem; border: 1px solid rgba(239, 68, 68, 0.3);">
                <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
            </div>
        @endif

        <div class="content-card">
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th>Domain</th>
                            <th>Type</th>
                            <th>Document Root</th>
                            <th>SSL Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($domains as $domain)
                            <tr>
                                <td style="font-weight: 600;">{{ $domain['domain'] }}</td>
                                <td><span class="type-badge">{{ $domain['type'] }}</span></td>
                                <td style="color: var(--text-muted); font-family: monospace;">
                                    {{ $domain['document_root'] }}
                                </td>
                                <td><i class="fas fa-lock" style="color: #10b981;"></i> Active</td>
                                <td>
                                    <a href="{{ route('files', ['domain' => $domain['domain'], 'root' => $domain['root']]) }}"
                                        class="action-btn" title="File Manager">
                                        <i class="fas fa-folder-open" style="color: var(--accent);"></i>
                                    </a>

                                    @if($domain['type'] !== 'Primary')
                                        <form action="{{ route('domains.delete', $domain['domain']) }}" method="POST"
                                            style="display:inline;">
                                            @csrf
                                            @method('DELETE')
                                            <input type="hidden" name="subdomain" value="{{ $domain['subdomain'] ?? '' }}">
                                            <button type="submit" class="action-btn"
                                                onclick="return confirm('Are you sure you want to delete {{ $domain['domain'] }}?')">
                                                <i class="fas fa-trash-alt" style="color: #ef4444;"></i>
                                            </button>
                                        </form>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="5" style="text-align: center; padding: 3rem; color: var(--text-muted);">
                                    <i class="fas fa-globe" style="font-size: 2rem; margin-bottom: 1rem; display: block;"></i>
                                    No domains found in your account.
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>

        {{-- ── Subdomains Section ──────────────────────────────── --}}
        <div class="content-card" style="margin-top:2rem;">
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1.2rem;flex-wrap:wrap;gap:10px;">
                <h3 style="font-size:1rem;display:flex;align-items:center;gap:8px;">
                    <i class="fas fa-sitemap" style="color:var(--accent);"></i> Subdomains
                </h3>
                <button onclick="document.getElementById('addSubSection').style.display=document.getElementById('addSubSection').style.display==='none'?'flex':'none'"
                    style="display:inline-flex;align-items:center;gap:6px;padding:6px 16px;background:rgba(56,189,248,.12);border:1px solid var(--accent);border-radius:10px;color:var(--accent);font-size:.8rem;font-weight:600;cursor:pointer;">
                    <i class="fas fa-plus"></i> Add Subdomain
                </button>
            </div>

            {{-- Add subdomain inline form --}}
            <div id="addSubSection" style="display:none;gap:10px;align-items:flex-end;flex-wrap:wrap;padding:14px;background:rgba(56,189,248,.05);border:1px solid rgba(56,189,248,.18);border-radius:12px;margin-bottom:1.2rem;">
                <div style="flex:1;min-width:140px;">
                    <label style="font-size:.75rem;color:var(--text-muted);display:block;margin-bottom:4px;">Subdomain</label>
                    <input type="text" id="subInput" placeholder="e.g. blog, shop" style="padding:8px 12px;font-size:.85rem;">
                </div>
                <div style="flex:1;min-width:160px;">
                    <label style="font-size:.75rem;color:var(--text-muted);display:block;margin-bottom:4px;">Root Domain</label>
                    <select id="subRootDomain" style="width:100%;padding:8px 12px;background:rgba(15,23,42,.5);border:1px solid var(--border);border-radius:12px;color:white;font-size:.85rem;">
                        @foreach($domains as $d)
                        <option value="{{ $d['domain'] }}">{{ $d['domain'] }}</option>
                        @endforeach
                        @if(Auth::user()->primary_domain && !isset($domains[Auth::user()->primary_domain]))
                        <option value="{{ Auth::user()->primary_domain }}">{{ Auth::user()->primary_domain }}</option>
                        @endif
                    </select>
                </div>
                <button onclick="createSubdomain()" id="addSubBtn"
                    style="padding:8px 20px;background:var(--primary);border:none;border-radius:12px;color:white;font-weight:600;font-size:.85rem;cursor:pointer;white-space:nowrap;">
                    <i class="fas fa-plus"></i> Create
                </button>
            </div>

            {{-- Subdomain list --}}
            <div class="table-container">
                <table id="subTable">
                    <thead>
                        <tr>
                            <th>Subdomain</th>
                            <th>Root Domain</th>
                            <th>Document Root</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="subTbody">
                        @forelse($subdomains as $sub)
                        @php $fullSub = ($sub['domain'] ?? '') . '.' . ($sub['rootdomain'] ?? ''); @endphp
                        <tr id="subrow-{{ md5($fullSub) }}">
                            <td style="font-weight:600;color:var(--accent);">
                                <i class="fas fa-angle-right" style="color:var(--text-muted);margin-right:4px;font-size:.75rem;"></i>
                                {{ $fullSub }}
                            </td>
                            <td style="color:var(--text-muted);">{{ $sub['rootdomain'] ?? '' }}</td>
                            <td style="color:var(--text-muted);font-family:monospace;font-size:.78rem;">{{ $sub['dir'] ?? '' }}</td>
                            <td>
                                <button onclick="deleteSubdomain('{{ $fullSub }}','{{ md5($fullSub) }}')"
                                    class="action-btn" title="Delete subdomain">
                                    <i class="fas fa-trash-alt" style="color:#ef4444;"></i>
                                </button>
                            </td>
                        </tr>
                        @empty
                        <tr id="subEmpty">
                            <td colspan="4" style="text-align:center;padding:2rem;color:var(--text-muted);">
                                <i class="fas fa-sitemap" style="font-size:1.8rem;display:block;margin-bottom:8px;opacity:.3;"></i>
                                No subdomains yet.
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>

        {{-- Toast --}}
        <div id="toastArea" style="position:fixed;bottom:24px;right:24px;z-index:9999;display:flex;flex-direction:column;gap:6px;"></div>
    </div>

    <!-- Add Domain Modal -->
    <div id="domainModal" class="modal">
        <div class="modal-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem;">
                <h3 style="font-size: 1.5rem;">Add New Domain</h3>
                <span id="closeModal" style="cursor: pointer; font-size: 1.5rem; color: var(--text-muted);">&times;</span>
            </div>
            <form action="{{ route('domains.store') }}" method="POST">
                @csrf
                <div class="form-group">
                    <label>New Domain Name</label>
                    <input type="text" name="new_domain" placeholder="example.com" required
                        style="font-size: 1.1rem; padding: 1rem;">
                    <p style="font-size: 0.8rem; color: var(--text-muted); margin-top: 0.5rem; line-height: 1.4;">
                        <i class="fas fa-info-circle"></i> A folder will be automatically created at
                        <strong>~/domains/yourdomain.com</strong> (outside public_html)
                    </p>
                </div>
                <button type="submit" class="btn-submit shadow-lg" style="margin-top: 1rem;">Create Addon Domain</button>
            </form>
        </div>
    </div>
@endsection

@section('scripts')
    <script>
        const modal = document.getElementById("domainModal");
        const btn   = document.getElementById("openModal");
        const span  = document.getElementById("closeModal");

        btn.onclick  = () => modal.style.display = "block";
        span.onclick = () => modal.style.display = "none";
        window.onclick = (event) => {
            if (event.target == modal) modal.style.display = "none";
        }

        // ── Toast ──────────────────────────────────────────────
        function showToast(msg, type='ok') {
            const area = document.getElementById('toastArea');
            const el   = document.createElement('div');
            const bg   = type === 'ok' ? '#10b981' : '#ef4444';
            const icon = type === 'ok' ? 'check-circle' : 'exclamation-circle';
            el.style.cssText = `padding:10px 18px;border-radius:8px;font-size:.82rem;font-weight:600;background:${bg};color:#fff;box-shadow:0 6px 20px rgba(0,0,0,.4);animation:toastIn .3s ease;`;
            el.innerHTML = `<i class="fas fa-${icon}" style="margin-right:6px;"></i>${msg}`;
            area.appendChild(el);
            setTimeout(() => el.remove(), 3200);
        }

        // ── Create Subdomain ──────────────────────────────────
        async function createSubdomain() {
            const sub    = document.getElementById('subInput').value.trim();
            const root   = document.getElementById('subRootDomain').value;
            const addBtn = document.getElementById('addSubBtn');
            if (!sub) return showToast('Enter subdomain name', 'err');

            addBtn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Creating…';
            addBtn.disabled  = true;

            try {
                const r = await fetch('{{ route("domain.sub.create") }}', {
                    method: 'POST',
                    headers: { 'Content-Type':'application/json','X-CSRF-TOKEN':'{{ csrf_token() }}','X-Requested-With':'XMLHttpRequest' },
                    body: JSON.stringify({ subdomain: sub, root_domain: root }),
                });
                const d = await r.json();
                addBtn.innerHTML = '<i class="fas fa-plus"></i> Create';
                addBtn.disabled  = false;

                if (!d.success) return showToast(d.message || d.error || 'Failed', 'err');

                showToast(`${d.full} created!`);
                document.getElementById('subInput').value = '';
                document.getElementById('subEmpty')?.remove();

                const full = d.full;
                const hash = btoa(full).replace(/=/g, '');
                document.getElementById('subTbody').insertAdjacentHTML('beforeend', `
                    <tr id="subrow-${hash}">
                        <td style="font-weight:600;color:var(--accent);">
                            <i class="fas fa-angle-right" style="color:var(--text-muted);margin-right:4px;font-size:.75rem;"></i>
                            ${full}
                        </td>
                        <td style="color:var(--text-muted);">${root}</td>
                        <td style="color:var(--text-muted);font-family:monospace;font-size:.78rem;">domains/${full}</td>
                        <td>
                            <button onclick="deleteSubdomain('${full}','${hash}')" class="action-btn" title="Delete subdomain">
                                <i class="fas fa-trash-alt" style="color:#ef4444;"></i>
                            </button>
                        </td>
                    </tr>`);
            } catch(e) {
                addBtn.innerHTML = '<i class="fas fa-plus"></i> Create';
                addBtn.disabled  = false;
                showToast(e.message, 'err');
            }
        }

        // ── Delete Subdomain ──────────────────────────────────
        async function deleteSubdomain(subdomain, hash) {
            if (!confirm(`Delete subdomain ${subdomain}? This cannot be undone.`)) return;
            try {
                const r = await fetch('{{ route("domain.sub.delete") }}', {
                    method: 'DELETE',
                    headers: { 'Content-Type':'application/json','X-CSRF-TOKEN':'{{ csrf_token() }}','X-Requested-With':'XMLHttpRequest' },
                    body: JSON.stringify({ subdomain }),
                });
                const d = await r.json();
                if (!d.success) return showToast(d.message || d.error || 'Failed', 'err');
                document.getElementById(`subrow-${hash}`)?.remove();
                showToast(`${subdomain} deleted`);
            } catch(e) { showToast(e.message, 'err'); }
        }
    </script>
    <style>
        @keyframes toastIn { from{transform:translateX(100%);opacity:0;} to{transform:translateX(0);opacity:1;} }
    </style>
@endsection