@extends('layouts.dashboard')
@section('content')
<style>
:root{--sl-bg:#0d1117;--sl-surface:#161b22;--sl-card:#21262d;--sl-border:#30363d;--sl-blue:#58a6ff;--sl-green:#3fb950;--sl-red:#f85149;--sl-yellow:#d29922;--sl-purple:#a371f7;--sl-orange:#f0883e;--sl-text:#e6edf3;--sl-muted:#8b949e;}
.sl-wrap{font-family:'Outfit',sans-serif;color:var(--sl-text);}

/* Header */
.sl-header{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin-bottom:22px;}
.sl-header h2{font-size:1.15rem;display:flex;align-items:center;gap:10px;}
.sl-header h2 i{color:var(--sl-green);}
.sl-header p{font-size:.78rem;color:var(--sl-muted);margin-top:3px;}

/* Info banner */
.sl-banner{display:flex;gap:12px;align-items:flex-start;padding:14px 18px;border-radius:12px;margin-bottom:22px;font-size:.8rem;line-height:1.6;}
.sl-banner.info{background:rgba(88,166,255,.08);border:1px solid rgba(88,166,255,.2);color:var(--sl-blue);}
.sl-banner.warn{background:rgba(210,153,34,.08);border:1px solid rgba(210,153,34,.25);color:var(--sl-yellow);}
.sl-banner i{font-size:1.1rem;margin-top:1px;flex-shrink:0;}

/* Stats row */
.sl-stats{display:flex;gap:12px;margin-bottom:22px;flex-wrap:wrap;}
.sl-stat{background:var(--sl-surface);border:1px solid var(--sl-border);border-radius:10px;padding:14px 20px;display:flex;align-items:center;gap:12px;min-width:150px;}
.sl-stat-icon{width:36px;height:36px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:.95rem;flex-shrink:0;}
.sl-stat-val{font-size:1.4rem;font-weight:800;line-height:1;}
.sl-stat-lbl{font-size:.68rem;color:var(--sl-muted);margin-top:2px;}

/* Domain cards */
.sl-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(360px,1fr));gap:14px;}
.sl-card{background:var(--sl-surface);border:1px solid var(--sl-border);border-radius:14px;overflow:hidden;transition:border-color .2s;}
.sl-card.secured{border-left:3px solid var(--sl-green);}
.sl-card.unsecured{border-left:3px solid var(--sl-red);}
.sl-card.expiring{border-left:3px solid var(--sl-yellow);}

.sl-card-head{padding:14px 16px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--sl-border);}
.sl-domain-info{display:flex;align-items:center;gap:10px;}
.sl-domain-icon{width:36px;height:36px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:.9rem;flex-shrink:0;}
.sl-domain-name{font-weight:700;font-size:.88rem;}
.sl-domain-type{font-size:.67rem;color:var(--sl-muted);}

/* SSL Status Badge */
.sl-badge{display:inline-flex;align-items:center;gap:5px;padding:4px 11px;border-radius:20px;font-size:.7rem;font-weight:700;}
.sl-badge.ok{background:rgba(63,185,80,.12);border:1px solid rgba(63,185,80,.3);color:var(--sl-green);}
.sl-badge.err{background:rgba(248,81,73,.12);border:1px solid rgba(248,81,73,.3);color:var(--sl-red);}
.sl-badge.warn{background:rgba(210,153,34,.12);border:1px solid rgba(210,153,34,.3);color:var(--sl-yellow);}
.sl-badge.loading{background:rgba(139,148,158,.1);border:1px solid var(--sl-border);color:var(--sl-muted);}

/* Cert details */
.sl-card-body{padding:14px 16px;}
.sl-cert-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:12px;}
.sl-cert-item{background:var(--sl-card);border-radius:7px;padding:8px 10px;}
.sl-cert-label{font-size:.64rem;color:var(--sl-muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:2px;}
.sl-cert-val{font-size:.78rem;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}

/* Progress bar for expiry */
.sl-expiry-bar{height:4px;border-radius:2px;background:var(--sl-border);overflow:hidden;margin-top:4px;}
.sl-expiry-fill{height:100%;border-radius:2px;transition:width .4s;}

/* Actions row */
.sl-actions{display:flex;gap:6px;flex-wrap:wrap;}
.sl-btn{display:inline-flex;align-items:center;gap:5px;padding:6px 13px;border-radius:7px;font-size:.74rem;font-weight:700;cursor:pointer;border:1px solid;transition:all .13s;white-space:nowrap;}
.sl-btn.green{background:rgba(63,185,80,.12);border-color:var(--sl-green);color:var(--sl-green);}.sl-btn.green:hover{background:var(--sl-green);color:#000;}
.sl-btn.blue{background:rgba(88,166,255,.12);border-color:var(--sl-blue);color:var(--sl-blue);}.sl-btn.blue:hover{background:var(--sl-blue);color:#000;}
.sl-btn.red{background:rgba(248,81,73,.12);border-color:var(--sl-red);color:var(--sl-red);}.sl-btn.red:hover{background:var(--sl-red);color:#fff;}
.sl-btn.ghost{background:transparent;border-color:var(--sl-border);color:var(--sl-muted);}.sl-btn.ghost:hover{border-color:var(--sl-blue);color:var(--sl-blue);}
.sl-btn.orange{background:rgba(240,136,62,.12);border-color:var(--sl-orange);color:var(--sl-orange);}.sl-btn.orange:hover{background:var(--sl-orange);color:#000;}
.sl-btn:disabled{opacity:.5;cursor:not-allowed;}

/* Run AutoSSL global btn */
.sl-run-btn{display:inline-flex;align-items:center;gap:8px;padding:9px 20px;border-radius:9px;font-size:.82rem;font-weight:700;cursor:pointer;border:1px solid var(--sl-green);background:rgba(63,185,80,.12);color:var(--sl-green);transition:all .15s;}
.sl-run-btn:hover{background:var(--sl-green);color:#000;}
.sl-run-btn:disabled{opacity:.5;cursor:not-allowed;}

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

<div class="sl-wrap">
    <div class="sl-header">
        <div>
            <h2><i class="fas fa-lock"></i> SSL / TLS Manager</h2>
            <p>Manage SSL certificates for your domains — powered by AutoSSL (Let's Encrypt)</p>
        </div>
        <button class="sl-run-btn" id="runAutoSslBtn" onclick="runAutoSsl()">
            <i class="fas fa-sync-alt"></i> Run AutoSSL Now
        </button>
    </div>

    <div class="sl-banner info">
        <i class="fas fa-info-circle"></i>
        <div>
            <strong>AutoSSL (Let's Encrypt)</strong> automatically issues and renews free SSL certificates for your domains.
            Click <strong>Run AutoSSL Now</strong> to trigger an immediate check, or use the per-domain buttons below.
            Certificates are renewed automatically before they expire.
        </div>
    </div>

    @php
        $securedCount  = 0;
        $expiringCount = 0;
        $unsecuredCount= 0;
        foreach($userDomains as $d) {
            $info   = $sslInfo[$d] ?? [];
            $expiry = $info['not_after'] ?? ($info['expiry_date'] ?? null);
            if ($expiry) {
                $days = (int)ceil((strtotime($expiry) - time()) / 86400);
                if ($days <= 30) $expiringCount++;
                else $securedCount++;
            } else {
                $unsecuredCount++;
            }
        }
    @endphp

    {{-- Stats --}}
    <div class="sl-stats">
        <div class="sl-stat">
            <div class="sl-stat-icon" style="background:rgba(63,185,80,.15);color:var(--sl-green);"><i class="fas fa-lock"></i></div>
            <div><div class="sl-stat-val" style="color:var(--sl-green);">{{ $securedCount }}</div><div class="sl-stat-lbl">Secured</div></div>
        </div>
        <div class="sl-stat">
            <div class="sl-stat-icon" style="background:rgba(210,153,34,.15);color:var(--sl-yellow);"><i class="fas fa-exclamation-triangle"></i></div>
            <div><div class="sl-stat-val" style="color:var(--sl-yellow);">{{ $expiringCount }}</div><div class="sl-stat-lbl">Expiring Soon</div></div>
        </div>
        <div class="sl-stat">
            <div class="sl-stat-icon" style="background:rgba(248,81,73,.15);color:var(--sl-red);"><i class="fas fa-lock-open"></i></div>
            <div><div class="sl-stat-val" style="color:var(--sl-red);">{{ $unsecuredCount }}</div><div class="sl-stat-lbl">No SSL</div></div>
        </div>
        <div class="sl-stat">
            <div class="sl-stat-icon" style="background:rgba(88,166,255,.15);color:var(--sl-blue);"><i class="fas fa-globe"></i></div>
            <div><div class="sl-stat-val" style="color:var(--sl-blue);">{{ count($userDomains) }}</div><div class="sl-stat-lbl">Total Domains</div></div>
        </div>
    </div>

    @if(empty($userDomains))
    <div style="text-align:center;padding:60px;color:var(--sl-muted);">
        <i class="fas fa-globe" style="font-size:2.5rem;display:block;margin-bottom:12px;opacity:.3;"></i>
        No domains found.
    </div>
    @else
    <div class="sl-grid">
        @foreach($userDomains as $domain)
        @php
            $isPrimary = $domain === Auth::user()->primary_domain;
            $info      = $sslInfo[$domain] ?? [];
            $issuer    = $info['issuer'] ?? ($info['certificate_owner'] ?? '');
            $subject   = $info['subject'] ?? ($info['domains'] ?? '');
            $notBefore = $info['not_before'] ?? ($info['activation_time'] ?? '');
            $notAfter  = $info['not_after']  ?? ($info['expiry_date']     ?? '');
            $hasSsl    = !empty($notAfter);
            $daysLeft  = $hasSsl ? (int)ceil((strtotime($notAfter) - time()) / 86400) : 0;
            $isExpiring= $hasSsl && $daysLeft <= 30;
            $isExpired = $hasSsl && $daysLeft <= 0;
            $cardClass = $isExpired ? 'unsecured' : ($isExpiring ? 'expiring' : ($hasSsl ? 'secured' : 'unsecured'));
            $expiryPct = $hasSsl ? max(0,min(100,round(($daysLeft/90)*100))) : 0;
            $barColor  = $isExpired ? 'var(--sl-red)' : ($isExpiring ? 'var(--sl-yellow)' : 'var(--sl-green)');

            $autoMeta  = $autoSslMeta[$domain] ?? [];
            $autoEnabled = !empty($autoMeta);
        @endphp
        <div class="sl-card {{ $cardClass }}" id="slcard-{{ md5($domain) }}">
            <div class="sl-card-head">
                <div class="sl-domain-info">
                    <div class="sl-domain-icon" style="background:{{ $hasSsl ? 'rgba(63,185,80,.12)' : 'rgba(248,81,73,.1)' }};color:{{ $hasSsl ? 'var(--sl-green)' : 'var(--sl-red)' }};">
                        <i class="fas fa-{{ $hasSsl ? 'lock' : 'lock-open' }}"></i>
                    </div>
                    <div>
                        <div class="sl-domain-name">{{ $domain }}</div>
                        <div class="sl-domain-type">{{ $isPrimary ? 'Primary Domain' : 'Addon Domain' }}</div>
                    </div>
                </div>
                <span class="sl-badge {{ $isExpired ? 'err' : ($isExpiring ? 'warn' : ($hasSsl ? 'ok' : 'err')) }}" id="slbadge-{{ md5($domain) }}">
                    @if($isExpired)
                        <i class="fas fa-times-circle"></i> Expired
                    @elseif($isExpiring)
                        <i class="fas fa-exclamation-triangle"></i> Expires in {{ $daysLeft }}d
                    @elseif($hasSsl)
                        <i class="fas fa-check-circle"></i> Secured · {{ $daysLeft }}d left
                    @else
                        <i class="fas fa-lock-open"></i> No SSL
                    @endif
                </span>
            </div>
            <div class="sl-card-body">
                @if($hasSsl)
                <div class="sl-cert-grid">
                    <div class="sl-cert-item">
                        <div class="sl-cert-label">Issued By</div>
                        <div class="sl-cert-val" title="{{ $issuer }}">{{ $issuer ?: 'Let\'s Encrypt' }}</div>
                    </div>
                    <div class="sl-cert-item">
                        <div class="sl-cert-label">Expires</div>
                        <div class="sl-cert-val" style="color:{{ $barColor }};">
                            {{ $notAfter ? date('M d, Y', strtotime($notAfter)) : '—' }}
                        </div>
                        <div class="sl-expiry-bar">
                            <div class="sl-expiry-fill" style="width:{{ $expiryPct }}%;background:{{ $barColor }};"></div>
                        </div>
                    </div>
                    @if($notBefore)
                    <div class="sl-cert-item">
                        <div class="sl-cert-label">Activated</div>
                        <div class="sl-cert-val">{{ date('M d, Y', strtotime($notBefore)) }}</div>
                    </div>
                    @endif
                    <div class="sl-cert-item">
                        <div class="sl-cert-label">Auto-Renew</div>
                        <div class="sl-cert-val" style="color:var(--sl-green);">
                            <i class="fas fa-check-circle"></i> Enabled
                        </div>
                    </div>
                </div>
                @else
                <div style="padding:10px 0;text-align:center;color:var(--sl-muted);font-size:.78rem;margin-bottom:10px;">
                    <i class="fas fa-lock-open" style="font-size:1.4rem;display:block;margin-bottom:6px;color:var(--sl-red);opacity:.6;"></i>
                    No SSL certificate installed. Run AutoSSL to issue a free Let's Encrypt certificate.
                </div>
                @endif

                <div class="sl-actions">
                    <button class="sl-btn green" onclick="runAutoSslDomain('{{ $domain }}','{{ md5($domain) }}')">
                        <i class="fas fa-certificate"></i>
                        {{ $hasSsl ? 'Renew SSL' : 'Issue SSL' }}
                    </button>
                    <button class="sl-btn blue" onclick="checkStatus('{{ $domain }}','{{ md5($domain) }}')">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                    @if($hasSsl)
                    <button class="sl-btn red" onclick="removeSsl('{{ $domain }}','{{ md5($domain) }}')">
                        <i class="fas fa-trash"></i> Remove
                    </button>
                    @endif
                    <a href="https://{{ $domain }}" target="_blank" class="sl-btn ghost">
                        <i class="fas fa-external-link-alt"></i> Visit
                    </a>
                </div>
            </div>
        </div>
        @endforeach
    </div>
    @endif
</div>

<div class="sl-toast" id="slToastArea"></div>

<script>
const CSRF = '{{ csrf_token() }}';

function slToast(msg, type='ok') {
    const area = document.getElementById('slToastArea');
    const el   = document.createElement('div');
    el.className = `sl-toast-item ${type}`;
    el.innerHTML = `<i class="fas fa-${type==='ok'?'check-circle':type==='err'?'exclamation-circle':'info-circle'}" style="margin-right:6px;"></i>${msg}`;
    area.appendChild(el);
    setTimeout(() => el.remove(), 4500);
}

async function slApi(url, method='POST', 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();
}

// ── Run AutoSSL globally ─────────────────────────────────────
async function runAutoSsl() {
    const btn = document.getElementById('runAutoSslBtn');
    btn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Running…'; btn.disabled = true;
    const d = await slApi('{{ route("ssl.autossl") }}');
    btn.innerHTML = '<i class="fas fa-sync-alt"></i> Run AutoSSL Now'; btn.disabled = false;
    slToast(d.message || (d.success ? 'AutoSSL started!' : 'Failed'), d.success ? 'ok' : 'err');
}

// ── Run AutoSSL for a specific domain ────────────────────────
async function runAutoSslDomain(domain, hash) {
    slToast('Triggering AutoSSL for ' + domain + '…', 'info');
    const d = await slApi('{{ route("ssl.autossl") }}');
    slToast(d.message || (d.success ? 'AutoSSL started! Refresh in ~60s.' : 'Failed'), d.success ? 'ok' : 'err');
}

// ── Refresh SSL status for single domain ─────────────────────
async function checkStatus(domain, hash) {
    const badge = document.getElementById(`slbadge-${hash}`);
    badge.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i> Checking…';
    badge.className = 'sl-badge loading';

    const d = await slApi('{{ route("ssl.check") }}', 'POST', { domain });
    if (!d.success) {
        badge.innerHTML = '<i class="fas fa-lock-open"></i> No SSL';
        badge.className = 'sl-badge err';
        return slToast(d.message || 'Check failed', 'err');
    }

    const cert    = d.cert || {};
    const notAfter = cert.not_after || cert.expiry_date || null;
    if (notAfter) {
        const days = Math.ceil((new Date(notAfter) - Date.now()) / 86400000);
        const cls  = days <= 0 ? 'err' : days <= 30 ? 'warn' : 'ok';
        const ico  = days <= 0 ? 'times-circle' : days <= 30 ? 'exclamation-triangle' : 'check-circle';
        badge.innerHTML = `<i class="fas fa-${ico}"></i> ${days <= 0 ? 'Expired' : `Secured · ${days}d left`}`;
        badge.className = `sl-badge ${cls}`;
        slToast('SSL status refreshed for ' + domain);
    } else {
        badge.innerHTML = '<i class="fas fa-lock-open"></i> No SSL';
        badge.className = 'sl-badge err';
        slToast('No SSL certificate found for ' + domain, 'err');
    }
}

// ── Remove SSL from domain ───────────────────────────────────
async function removeSsl(domain, hash) {
    if (!confirm(`Remove SSL certificate from ${domain}? The site will become HTTP only.`)) return;
    const d = await slApi('{{ route("ssl.remove") }}', 'DELETE', { domain });
    if (!d.success) return slToast(d.message || 'Failed', 'err');
    slToast(`SSL removed from ${domain}`);
    const badge = document.getElementById(`slbadge-${hash}`);
    badge.innerHTML = '<i class="fas fa-lock-open"></i> No SSL';
    badge.className = 'sl-badge err';
    location.reload();
}
</script>
@endsection
