<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Server Panel</title>
    <link rel="icon" type="image/png" href="<?php echo e(asset('favicon.ico')); ?>">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #6366f1;
            --primary-dark: #4f46e5;
            --secondary: #ec4899;
            --bg-dark: #0f172a;
            --bg-card: #1e293b;
            --text-main: #f8fafc;
            --text-muted: #94a3b8;
            --accent: #38bdf8;
            --glass: rgba(30,41,59,0.85);
            --border: rgba(255,255,255,0.08);
            --sidebar-w: 260px;
        }

        *, *::before, *::after { margin:0; padding:0; box-sizing:border-box; }

        html, body {
            font-family: 'Outfit', sans-serif;
            background: var(--bg-dark);
            color: var(--text-main);
            min-height: 100vh;
            overflow-x: hidden;
        }

        /* ── Particles canvas ───────────────────────────────── */
        #particles-js {
            position: fixed;
            inset: 0;
            z-index: 0;
            pointer-events: none;
        }

        /* ── Layout wrapper ─────────────────────────────────── */
        .sp-layout {
            display: flex;
            min-height: 100vh;
            position: relative;
            z-index: 1;
        }

        /* ── Overlay (mobile) ───────────────────────────────── */
        .sp-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,.55);
            backdrop-filter: blur(2px);
            z-index: 199;
        }
        .sp-overlay.show { display: block; }

        /* ── Sidebar ────────────────────────────────────────── */
        .sp-sidebar {
            width: var(--sidebar-w);
            background: var(--glass);
            border-right: 1px solid var(--border);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            height: 100vh;
            position: fixed;
            left: 0; top: 0;
            display: flex;
            flex-direction: column;
            z-index: 200;
            transition: transform .3s cubic-bezier(.4,0,.2,1);
            overflow-y: auto;
            overflow-x: hidden;
        }

        /* ── Sidebar logo ───────────────────────────────────── */
        .sp-logo {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 22px 20px 18px;
            border-bottom: 1px solid var(--border);
            text-decoration: none;
            flex-shrink: 0;
        }
        .sp-logo-icon {
            width: 36px; height: 36px;
            border-radius: 10px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            display: flex; align-items: center; justify-content: center;
            font-size: 1rem; color: #fff; flex-shrink: 0;
            box-shadow: 0 4px 12px rgba(99,102,241,.4);
        }
        .sp-logo-text { font-size: 1.05rem; font-weight: 700; line-height: 1.1; color:#22d3ee; }
        .sp-logo-text span { display: block; font-size: .62rem; font-weight: 400; color: #64748b; letter-spacing: .08em; text-transform: uppercase; }

        /* ── User badge in sidebar ──────────────────────────── */
        .sp-user-badge {
            margin: 14px 14px 4px;
            padding: 10px 12px;
            background: rgba(99,102,241,.1);
            border: 1px solid rgba(99,102,241,.2);
            border-radius: 10px;
            display: flex; align-items: center; gap: 10px;
            flex-shrink: 0;
        }
        .sp-user-avatar {
            width: 34px; height: 34px; border-radius: 50%;
            background: linear-gradient(135deg,var(--primary),var(--secondary));
            display: flex; align-items: center; justify-content: center;
            font-weight: 700; font-size: .85rem; flex-shrink: 0;
        }
        .sp-user-name { font-size: .82rem; font-weight: 600; line-height: 1.2; }
        .sp-user-role { font-size: .65rem; color: var(--text-muted); }

        /* ── Nav section label ──────────────────────────────── */
        .sp-nav-label {
            font-size: .6rem;
            font-weight: 700;
            letter-spacing: .12em;
            text-transform: uppercase;
            color: var(--text-muted);
            padding: 14px 20px 4px;
        }

        /* ── Nav links ──────────────────────────────────────── */
        .sp-nav { list-style: none; padding: 4px 10px; flex-grow: 1; }
        .sp-nav li { margin-bottom: 2px; }
        .sp-nav a {
            display: flex; align-items: center; gap: 11px;
            padding: 9px 12px;
            border-radius: 9px;
            text-decoration: none;
            color: var(--text-muted);
            font-size: .82rem;
            font-weight: 500;
            transition: all .15s;
            position: relative;
        }
        .sp-nav a i { width: 18px; text-align: center; font-size: .88rem; flex-shrink: 0; }
        .sp-nav a:hover { color: var(--text-main); background: rgba(255,255,255,.06); }
        .sp-nav a.active {
            background: linear-gradient(90deg,rgba(99,102,241,.25),rgba(99,102,241,.08));
            color: #a5b4fc;
            border-left: 2px solid var(--primary);
        }
        .sp-nav a.active i { color: #818cf8; }

        /* ── Sidebar footer ─────────────────────────────────── */
        .sp-sidebar-footer {
            padding: 10px;
            border-top: 1px solid var(--border);
            flex-shrink: 0;
        }
        .sp-logout {
            display: flex; align-items: center; gap: 10px;
            padding: 9px 12px; border-radius: 9px;
            color: #f87171; font-size: .82rem; font-weight: 500;
            text-decoration: none; cursor: pointer;
            background: none; border: none; width: 100%;
            transition: background .15s;
        }
        .sp-logout:hover { background: rgba(248,113,113,.1); }

        /* ── Topbar (mobile) ────────────────────────────────── */
        .sp-topbar {
            display: none;
            position: fixed; top: 0; left: 0; right: 0;
            height: 56px;
            background: var(--glass);
            border-bottom: 1px solid var(--border);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            z-index: 150;
            align-items: center;
            justify-content: space-between;
            padding: 0 16px;
        }
        .sp-topbar-logo {
            display: flex; align-items: center; gap: 9px;
            font-size: .95rem; font-weight: 700;
        }
        .sp-topbar-logo .sp-logo-icon { width: 28px; height: 28px; font-size: .8rem; border-radius: 7px; }
        .sp-hamburger {
            background: none; border: none; color: var(--text-main);
            font-size: 1.2rem; cursor: pointer; padding: 6px;
            border-radius: 7px; transition: background .15s;
        }
        .sp-hamburger:hover { background: rgba(255,255,255,.08); }

        /* ── Main content ───────────────────────────────────── */
        .sp-main {
            margin-left: var(--sidebar-w);
            flex-grow: 1;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* ── Page header ────────────────────────────────────── */
        .sp-page-header {
            padding: 24px 28px 0;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 12px;
        }
        .sp-page-header h1 { font-size: 1.3rem; font-weight: 700; }
        .sp-page-header p { font-size: .78rem; color: var(--text-muted); margin-top: 2px; }
        .sp-header-user {
            display: flex; align-items: center; gap: 10px;
            background: var(--glass);
            border: 1px solid var(--border);
            border-radius: 50px;
            padding: 6px 16px 6px 8px;
            backdrop-filter: blur(8px);
        }
        .sp-header-avatar {
            width: 32px; height: 32px; border-radius: 50%;
            background: linear-gradient(135deg,var(--primary),var(--secondary));
            display: flex; align-items: center; justify-content: center;
            font-weight: 700; font-size: .78rem;
        }
        .sp-header-name { font-size: .82rem; font-weight: 600; }
        .sp-header-role { font-size: .65rem; color: var(--text-muted); }

        /* ── Content area ───────────────────────────────────── */
        .sp-content {
            padding: 22px 28px 40px;
            flex-grow: 1;
        }

        /* ── Animate ────────────────────────────────────────── */
        .animate-fade {
            animation: spFade .45s ease forwards;
        }
        @keyframes spFade {
            from { opacity:0; transform:translateY(14px); }
            to   { opacity:1; transform:translateY(0); }
        }

        /* ── Responsive ─────────────────────────────────────── */
        @media (max-width: 900px) {
            .sp-sidebar {
                transform: translateX(-100%);
                box-shadow: 4px 0 30px rgba(0,0,0,.4);
            }
            .sp-sidebar.open { transform: translateX(0); }
            .sp-topbar { display: flex; }
            .sp-main { margin-left: 0; padding-top: 56px; }
            .sp-page-header { padding: 16px 16px 0; }
            .sp-content { padding: 16px 16px 32px; }
            .sp-header-user { display: none; }
        }

        @media (max-width: 480px) {
            .sp-logo-text span { display: none; }
            .sp-content { padding: 12px 12px 28px; }
        }

        /* ── Global card/btn helpers ────────────────────────── */
        .content-card {
            background: var(--bg-card);
            border-radius: 16px;
            padding: 1.5rem;
            border: 1px solid var(--border);
        }
        .btn-create {
            display: inline-flex; align-items: center; gap: 7px;
            padding: 9px 18px;
            background: var(--primary);
            color: #fff;
            border: none;
            border-radius: 10px;
            font-size: .82rem;
            font-weight: 600;
            cursor: pointer;
            transition: background .15s;
        }
        .btn-create:hover { background: var(--primary-dark); }
        .action-btn {
            background: none; border: none;
            padding: 6px 8px; border-radius: 7px;
            cursor: pointer; color: var(--text-muted);
            transition: all .15s; font-size: .85rem;
        }
        .action-btn:hover { color: var(--text-main); background: rgba(255,255,255,.06); }
        .type-badge {
            padding: 3px 10px; border-radius: 20px;
            font-size: .72rem;
            background: rgba(56,189,248,.1); color: var(--accent);
        }
        td { color: var(--text-main); }
    </style>
    <?php echo $__env->yieldContent('styles'); ?>
</head>
<body>
<!-- Particles background -->
<div id="particles-js"></div>


<?php if(!Auth::user()->isAdmin()): ?>
<style>
.sp-notif-bell{position:relative;background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);border-radius:10px;color:#e6edf3;width:36px;height:36px;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:.9rem;transition:all .2s;flex-shrink:0;text-decoration:none;}
.sp-notif-bell:hover{background:rgba(239,68,68,.18);border-color:rgba(239,68,68,.4);color:#fca5a5;}
.sp-notif-bell.has-unread{background:rgba(239,68,68,.12);border-color:rgba(239,68,68,.3);color:#fca5a5;animation:bellShake 2s ease-in-out infinite;}
@keyframes bellShake{0%,100%{transform:rotate(0);}10%,30%{transform:rotate(-8deg);}20%,40%{transform:rotate(8deg);}50%{transform:rotate(0);}}
.sp-notif-count{position:absolute;top:-5px;right:-5px;min-width:17px;height:17px;border-radius:9px;background:#ef4444;color:#fff;font-size:.58rem;font-weight:700;display:flex;align-items:center;justify-content:center;padding:0 3px;line-height:1;border:2px solid #0d1117;}
.sp-sidebar-bell-wrap{display:flex;align-items:center;padding:6px 14px;margin-bottom:2px;}
.sp-sidebar-bell-link{display:flex;align-items:center;gap:10px;width:100%;padding:9px 12px;border-radius:10px;color:#e6edf3;text-decoration:none;transition:background .15s;position:relative;border:1px solid transparent;}
.sp-sidebar-bell-link:hover{background:rgba(239,68,68,.1);border-color:rgba(239,68,68,.2);color:#fca5a5;}
.sp-sidebar-bell-link.has-unread{background:rgba(239,68,68,.08);border-color:rgba(239,68,68,.2);color:#fca5a5;}
.sp-sidebar-bell-link .sp-notif-count{position:static;border:none;margin-left:auto;flex-shrink:0;}
</style>
<?php endif; ?>

<div class="sp-layout">
    <!-- Mobile overlay -->
    <div class="sp-overlay" id="spOverlay"></div>

    <!-- Mobile topbar -->
    <div class="sp-topbar">
        <div class="sp-topbar-logo">
            <div class="sp-logo-icon"><i class="fas fa-server"></i></div>
            <span style="color:#22d3ee;font-weight:700;">Server Panel</span>
        </div>
        <div style="display:flex;align-items:center;gap:8px;">
            <?php if(!Auth::user()->isAdmin()): ?>
            <a href="<?php echo e(route('notif.page')); ?>" class="sp-notif-bell" id="topbarBell" title="Notifications">
                <i class="fas fa-bell"></i>
                <span class="sp-notif-count" id="topbarBellCount" style="display:none;">0</span>
            </a>
            <?php endif; ?>
            <button class="sp-hamburger" id="spHamburger">
                <i class="fas fa-bars" id="spHamIcon"></i>
            </button>
        </div>
    </div>

    <!-- Sidebar -->
    <aside class="sp-sidebar" id="spSidebar">
        <a href="<?php echo e(route('dashboard')); ?>" class="sp-logo">
            <div class="sp-logo-icon"><i class="fas fa-server"></i></div>
            <div class="sp-logo-text">
                Server Panel
                <span>Hosting Control</span>
            </div>
        </a>

        <?php if(!Auth::user()->isAdmin()): ?>
        <div class="sp-sidebar-bell-wrap">
            <a href="<?php echo e(route('notif.page')); ?>" class="sp-sidebar-bell-link" id="sidebarBell" title="Notifications">
                <i class="fas fa-bell" style="font-size:.88rem;"></i>
                <span style="font-size:.78rem;font-weight:600;">Notifications</span>
                <span class="sp-notif-count" id="sidebarBellCount" style="display:none;">0</span>
            </a>
        </div>
        <?php endif; ?>

        

        <div class="sp-nav-label">Main</div>
        <ul class="sp-nav">
            <li>
                <a href="<?php echo e(route('dashboard')); ?>" class="<?php echo e(request()->routeIs('dashboard') ? 'active' : ''); ?>">
                    <i class="fas fa-th-large"></i>
                    <span><?php echo e(Auth::user()->isAdmin() ? 'Overview' : 'Dashboard'); ?></span>
                </a>
            </li>
            <?php if(Auth::user()->isAdmin()): ?>
            <li>
                <a href="<?php echo e(route('admin.clients')); ?>" class="<?php echo e(request()->routeIs('admin.clients') ? 'active' : ''); ?>">
                    <i class="fas fa-users-cog"></i>
                    <span>Manage Clients</span>
                </a>
            </li>
            <?php endif; ?>
        </ul>

        <div class="sp-nav-label">Hosting</div>
        <ul class="sp-nav">
            <li>
                <a href="<?php echo e(route('domains')); ?>" class="<?php echo e(request()->routeIs('domains') ? 'active' : ''); ?>">
                    <i class="fas fa-globe"></i><span>My Domains</span>
                </a>
            </li>
            <li>
                <a href="<?php echo e(route('domain.manager')); ?>" class="<?php echo e(request()->routeIs('domain.*') ? 'active' : ''); ?>">
                    <i class="fas fa-sitemap"></i><span>Domain Manager</span>
                </a>
            </li>
            <li>
                <a href="<?php echo e(route('files')); ?>" class="<?php echo e(request()->routeIs('files') ? 'active' : ''); ?>">
                    <i class="fas fa-folder-tree"></i><span>File Manager</span>
                </a>
            </li>
            <li>
                <a href="<?php echo e(route('databases')); ?>" class="<?php echo e(request()->routeIs('databases') || request()->routeIs('mysql.*') ? 'active' : ''); ?>">
                    <i class="fas fa-database"></i><span>Databases</span>
                </a>
            </li>
            <li>
                <a href="<?php echo e(route('emails')); ?>" class="<?php echo e(request()->routeIs('emails') || request()->routeIs('email.*') ? 'active' : ''); ?>">
                    <i class="fas fa-envelope"></i><span>Email</span>
                </a>
            </li>
        </ul>

        <div class="sp-nav-label">Server</div>
        <ul class="sp-nav">
            <li>
                <a href="<?php echo e(route('php.version')); ?>" class="<?php echo e(request()->routeIs('php.*') ? 'active' : ''); ?>">
                    <i class="fab fa-php"></i><span>PHP Version</span>
                </a>
            </li>
            <li>
                <a href="<?php echo e(route('ssl')); ?>" class="<?php echo e(request()->routeIs('ssl*') ? 'active' : ''); ?>">
                    <i class="fas fa-lock"></i><span>SSL / TLS</span>
                </a>
            </li>
        </ul>


        <div class="sp-sidebar-footer">
            <form id="sp-logout-form" action="<?php echo e(route('logout')); ?>" method="POST" style="display:none;"><?php echo csrf_field(); ?></form>
            <button class="sp-logout" onclick="document.getElementById('sp-logout-form').submit()">
                <i class="fas fa-sign-out-alt"></i><span>Logout</span>
            </button>
        </div>
    </aside>

    <!-- Main content -->
    <main class="sp-main">
        <div class="sp-page-header">
            <div>
                <h1><?php echo e(Auth::user()->isAdmin() ? 'Welcome, Admin' : 'Welcome, ' . Auth::user()->name); ?></h1>
                <p>Manage your hosting services from one place.</p>
            </div>
            <div class="sp-header-user">
                <div class="sp-header-avatar"><?php echo e(strtoupper(substr(Auth::user()->name,0,1))); ?></div>
                <div>
                    <div class="sp-header-name"><?php echo e(Auth::user()->name); ?></div>
                    <div class="sp-header-role"><?php echo e(Auth::user()->role === 'admin' ? 'Administrator' : 'Client'); ?></div>
                </div>
            </div>
        </div>

        <div class="sp-content">
            <?php echo $__env->yieldContent('content'); ?>
        </div>
    </main>
</div>


<?php if(!Auth::user()->isAdmin()): ?>
<?php
    $daysLeft   = Auth::user()->daysUntilExpiry();
    $expiryDate = Auth::user()->subscription_expires_at;
    $renewLink  = Auth::user()->renew_url ?: \App\Models\AdminSetting::get('renew_url', '');
?>
<?php if($daysLeft !== null && $daysLeft <= 7 && $daysLeft >= 0): ?>
<div id="expiryBanner" style="
    position:fixed;bottom:0;left:0;right:0;z-index:400;
    background:<?php echo e($daysLeft <= 2 ? 'linear-gradient(90deg,#7f1d1d,#991b1b)' : 'linear-gradient(90deg,#78350f,#92400e)'); ?>;
    border-top:1px solid <?php echo e($daysLeft <= 2 ? 'rgba(239,68,68,.4)' : 'rgba(245,158,11,.4)'); ?>;
    padding:10px 20px;display:flex;align-items:center;gap:14px;flex-wrap:wrap;">
    <div style="font-size:1.2rem;"><?php echo e($daysLeft <= 2 ? '🚨' : '⚠️'); ?></div>
    <div style="flex:1;">
        <div style="font-size:.84rem;font-weight:700;color:#fff;">
            <?php if($daysLeft == 0): ?> Your subscription expires TODAY!
            <?php elseif($daysLeft == 1): ?> Your subscription expires TOMORROW!
            <?php else: ?> Your subscription expires in <?php echo e($daysLeft); ?> days (<?php echo e($expiryDate->format('d M Y')); ?>)
            <?php endif; ?>
        </div>
        <div style="font-size:.72rem;color:rgba(255,255,255,.7);">Renew now to avoid service interruption. Plan: <?php echo e(Auth::user()->plan_name); ?></div>
    </div>
    <?php if($renewLink): ?>
    <a href="<?php echo e($renewLink); ?>" target="_blank"
       style="display:inline-flex;align-items:center;gap:6px;padding:8px 18px;background:#f59e0b;border-radius:8px;color:#000;font-size:.8rem;font-weight:700;text-decoration:none;white-space:nowrap;">
        <i class="fas fa-redo"></i> Renew Now
    </a>
    <?php endif; ?>
    <button onclick="document.getElementById('expiryBanner').style.display='none'"
        style="background:none;border:none;color:rgba(255,255,255,.5);cursor:pointer;font-size:1rem;">
        <i class="fas fa-times"></i>
    </button>
</div>
<?php endif; ?>
<?php endif; ?>


<?php if(!Auth::user()->isAdmin()): ?>
<div id="spNewMsgNotif" style="display:none;position:fixed;top:60px;right:20px;z-index:700;background:linear-gradient(135deg,#1e1b4b,#312e81);border:1px solid rgba(99,102,241,.4);border-radius:10px;padding:10px 18px;font-size:.8rem;font-weight:600;color:#c7d2fe;box-shadow:0 8px 24px rgba(0,0,0,.4);align-items:center;gap:8px;animation:fadeIn .3s ease;max-width:300px;"></div>
<?php endif; ?>




<?php if(!Auth::user()->isAdmin()): ?>
<style>
/* ── Chat FAB ── */
.sp-chat-fab{position:fixed;bottom:24px;right:24px;z-index:600;width:52px;height:52px;border-radius:50%;background:linear-gradient(135deg,#6366f1,#8b5cf6);border:none;color:#fff;font-size:1.2rem;cursor:pointer;box-shadow:0 4px 20px rgba(99,102,241,.5);transition:transform .2s;}
.sp-chat-fab:hover{transform:scale(1.1);}
.sp-chat-badge{position:absolute;top:-4px;right:-4px;min-width:18px;height:18px;border-radius:9px;background:#ef4444;color:#fff;font-size:.65rem;font-weight:700;display:flex;align-items:center;justify-content:center;padding:0 4px;display:none;}
/* ── Chat window ── */
.sp-chat-window{position:fixed;bottom:88px;right:24px;z-index:600;width:min(360px,calc(100vw - 48px));background:#161b22;border:1px solid #30363d;border-radius:16px;box-shadow:0 20px 60px rgba(0,0,0,.5);display:none;flex-direction:column;overflow:hidden;animation:chatPop .2s ease;}
.sp-chat-window.open{display:flex;}
@keyframes chatPop{from{opacity:0;transform:translateY(16px) scale(.96);}to{opacity:1;transform:translateY(0) scale(1);}}
.sp-chat-head{padding:12px 16px;background:#0d1117;border-bottom:1px solid #30363d;display:flex;align-items:center;gap:10px;}
.sp-chat-head-icon{width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,#6366f1,#8b5cf6);display:flex;align-items:center;justify-content:center;font-size:.85rem;}
.sp-chat-head-info strong{font-size:.84rem;display:block;}
.sp-chat-head-info span{font-size:.68rem;color:#3fb950;}
/* ── Messages ── */
.sp-chat-msgs{flex:1;overflow-y:auto;padding:12px;display:flex;flex-direction:column;gap:6px;min-height:220px;max-height:340px;}
.sp-chat-msg{max-width:85%;line-height:1.4;}
.sp-chat-msg.user{align-self:flex-end;}
.sp-chat-msg.admin{align-self:flex-start;}
.sp-msg-bubble{padding:8px 12px;border-radius:10px;font-size:.79rem;word-break:break-word;}
.sp-chat-msg.user .sp-msg-bubble{background:rgba(99,102,241,.18);color:#c7d2fe;border-bottom-right-radius:3px;}
.sp-chat-msg.admin .sp-msg-bubble{background:rgba(56,189,248,.1);color:#7dd3fc;border-bottom-left-radius:3px;}
.sp-msg-time{font-size:.6rem;opacity:.4;margin-top:2px;text-align:right;}
.sp-chat-msg.admin .sp-msg-time{text-align:left;}
.sp-agent-label{font-size:.6rem;color:#818cf8;font-weight:700;margin-bottom:2px;display:flex;align-items:center;gap:5px;}
.sp-agent-mini-av{width:18px;height:18px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.48rem;font-weight:800;color:#fff;flex-shrink:0;}
/* ── System event (joined/left) ── */
.sp-chat-msg.system{align-self:center;width:100%;}
.sp-system-event{display:flex;align-items:center;gap:7px;padding:5px 0;}
.sp-system-line{flex:1;height:1px;background:linear-gradient(90deg,transparent,rgba(99,102,241,.2),transparent);}
.sp-system-pill{display:flex;align-items:center;gap:5px;padding:4px 12px 4px 5px;border-radius:99px;font-size:.68rem;font-weight:600;white-space:nowrap;}
.sp-system-pill.joined{background:rgba(63,185,80,.1);border:1px solid rgba(63,185,80,.2);color:#4ade80;}
.sp-system-pill.left{background:rgba(239,68,68,.07);border:1px solid rgba(239,68,68,.15);color:#f87171;}
/* ── Chat image ── */
.sp-chat-img{max-width:200px;max-height:160px;border-radius:8px;cursor:zoom-in;border:1px solid rgba(255,255,255,.08);}
/* ── Audio ── */
.sp-chat-audio{width:100%;max-width:220px;height:32px;accent-color:#6366f1;}
/* ── Image paste preview ── */
.sp-img-preview{background:rgba(99,102,241,.08);border:1px dashed rgba(99,102,241,.3);border-radius:8px;padding:6px 10px;margin:0 12px;display:none;align-items:center;gap:8px;font-size:.75rem;color:#a5b4fc;}
.sp-img-preview img{height:40px;border-radius:4px;}
/* ── Voice recording indicator ── */
.sp-rec-indicator{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.2);border-radius:8px;padding:5px 10px;margin:0 12px;display:none;align-items:center;gap:6px;font-size:.73rem;color:#fca5a5;}
.sp-rec-dot{width:7px;height:7px;border-radius:50%;background:#ef4444;animation:recBlink 1s step-end infinite;}
@keyframes recBlink{0%,100%{opacity:1;}50%{opacity:0;}}
/* ── Compose bar ── */
.sp-chat-compose{display:flex;gap:6px;padding:8px 12px;border-top:1px solid #30363d;align-items:center;}
.sp-chat-compose input{flex:1;background:#0d1117;border:1px solid #30363d;border-radius:8px;color:#e6edf3;padding:7px 10px;font-size:.8rem;outline:none;font-family:inherit;min-width:0;}
.sp-chat-compose input:focus{border-color:#6366f1;}
.sp-compose-btn{background:#0d1117;border:1px solid #30363d;border-radius:8px;color:#8b949e;padding:7px 9px;cursor:pointer;font-size:.8rem;transition:all .15s;flex-shrink:0;}
.sp-compose-btn:hover{background:#6366f1;border-color:#6366f1;color:#fff;}
.sp-compose-btn.active{background:#ef4444;border-color:#ef4444;color:#fff;}
.sp-send-btn{background:#6366f1;border:none;border-radius:8px;color:#fff;padding:7px 12px;cursor:pointer;font-size:.82rem;flex-shrink:0;}
@media(max-width:480px){.sp-chat-window{right:12px;bottom:80px;width:calc(100vw - 24px);}.sp-chat-fab{right:12px;bottom:16px;}}
</style>

<button class="sp-chat-fab" onclick="toggleChatWidget()" title="Support Chat">
    <i class="fas fa-comments" id="chatFabIcon"></i>
    <span class="sp-chat-badge" id="chatBadge">0</span>
</button>

<div class="sp-chat-window" id="spChatWindow">
    <div class="sp-chat-head">
        <div class="sp-chat-head-icon"><i class="fas fa-headset"></i></div>
        <div class="sp-chat-head-info">
            <strong>Support Chat</strong>
            <span><i class="fas fa-circle" style="font-size:.5rem;"></i> Online</span>
        </div>
        <button onclick="toggleChatWidget()" style="margin-left:auto;background:none;border:none;color:#8b949e;cursor:pointer;font-size:1rem;"><i class="fas fa-times"></i></button>
    </div>

    <div class="sp-chat-msgs" id="spChatMsgs">
        <p style="font-size:.75rem;color:#475569;text-align:center;margin:auto;">Loading…</p>
    </div>

    
    <div class="sp-img-preview" id="spImgPreview">
        <img id="spImgThumb" src="" alt="">
        <span id="spImgName" style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"></span>
        <button onclick="spClearImg()" style="background:none;border:none;color:#ef4444;cursor:pointer;font-size:.8rem;">✕</button>
    </div>

    
    <div class="sp-rec-indicator" id="spRecIndicator">
        <span class="sp-rec-dot"></span>
        <span id="spRecTime">0:00</span>
        <span style="flex:1;">Recording…</span>
        <button onclick="spStopRecording(true)" style="background:none;border:none;color:#ef4444;cursor:pointer;font-size:.75rem;font-weight:700;">Send</button>
        <button onclick="spStopRecording(false)" style="background:none;border:none;color:#8b949e;cursor:pointer;font-size:.75rem;">Cancel</button>
    </div>

    <div class="sp-chat-compose">
        <button class="sp-compose-btn" onclick="spPickImage()" title="Send image"><i class="fas fa-image"></i></button>
        <button class="sp-compose-btn" id="spVoiceBtn" onclick="spToggleRecording()" title="Voice message"><i class="fas fa-microphone"></i></button>
        <input type="text" id="spChatInput" placeholder="Type or paste image…" onkeydown="if(event.key==='Enter')spSendMsg()">
        <button class="sp-send-btn" onclick="spSendMsg()"><i class="fas fa-paper-plane"></i></button>
    </div>

    
    <input type="file" id="spFileInput" accept="image/*" style="display:none" onchange="spHandleFileSelect(this)">
</div>



<script>
var spChatOpen  = false;
var SUPPORT_SEND   = '<?php echo e(route("support.send")); ?>';
var SUPPORT_UPLOAD = '<?php echo e(route("support.upload")); ?>';
var SUPPORT_MSGS   = '<?php echo e(route("support.messages")); ?>';
var SP_CSRF = '<?php echo e(csrf_token()); ?>';

// ── Toggle chat widget ────────────────────────────────────────
function toggleChatWidget() {
    spChatOpen = !spChatOpen;
    var win = document.getElementById('spChatWindow');
    win.classList.toggle('open', spChatOpen);
    document.getElementById('chatFabIcon').className = spChatOpen ? 'fas fa-times' : 'fas fa-comments';
    if (spChatOpen) spLoadMessages();
}

// ── Load & render messages ────────────────────────────────────
function spLoadMessages() {
    fetch(SUPPORT_MSGS)
        .then(r => r.json())
        .then(function(d) {
            spRenderMessages(d.messages);
            var badge = document.getElementById('chatBadge');
            badge.textContent = d.unread;
            badge.style.display = d.unread > 0 ? 'flex' : 'none';
        });
}

// ── Avatar helpers ────────────────────────────────────────────
var SP_AGENT_COLORS = ['#6366f1','#8b5cf6','#ec4899','#f59e0b','#10b981','#3b82f6','#ef4444','#14b8a6'];
function spAgentColor(name) {
    if (!name) return '#6366f1';
    var sum=0; for(var i=0;i<name.length;i++) sum+=name.charCodeAt(i);
    return SP_AGENT_COLORS[sum % SP_AGENT_COLORS.length];
}
function spAgentInitials(name) {
    if (!name) return '?';
    var p = name.trim().split(/\s+/);
    return (p[0][0]+(p[1]?p[1][0]:'')).toUpperCase();
}
function spMiniAvatar(name) {
    var c = spAgentColor(name);
    return '<div class="sp-agent-mini-av" style="background:'+c+'">'+spAgentInitials(name)+'</div>';
}

function spRenderMsg(m) {
    var type = m.message_type || 'text';

    // System messages (agent joined / left)
    if (type === 'system' || m.sender === 'system') {
        var isJoin   = m.message && m.message.toLowerCase().includes('joined');
        var pillCls  = isJoin ? 'joined' : 'left';
        var icon     = isJoin ? '👋' : '🚪';
        var avHtml   = m.agent_name ? spMiniAvatar(m.agent_name) : '';
        return '<div class="sp-chat-msg system">'
            + '<div class="sp-system-event">'
            + '<div class="sp-system-line"></div>'
            + '<div class="sp-system-pill ' + pillCls + '">' + avHtml + icon + ' ' + spEsc(m.message) + '</div>'
            + '<div class="sp-system-line"></div>'
            + '</div>'
            + '<div class="sp-msg-time" style="text-align:center;font-size:.58rem;">' + m.created_at + '</div>'
            + '</div>';
    }

    // Admin messages with agent name
    var agentHtml = '';
    if (m.sender === 'admin' && m.agent_name) {
        agentHtml = '<div class="sp-agent-label">' + spMiniAvatar(m.agent_name) + spEsc(m.agent_name) + '</div>';
    }

    var content = '';
    if (type === 'image' && m.file_url) {
        content = '<img src="' + m.file_url + '" class="sp-chat-img" onclick="window.open(this.src)" onerror="this.style.display=\'none\'">';
        if (m.message && m.message !== '📷 Image') content += '<div style="font-size:.73rem;margin-top:4px;">' + spEsc(m.message) + '</div>';
    } else if (type === 'voice' && m.file_url) {
        content = '<audio class="sp-chat-audio" controls src="' + m.file_url + '"></audio>';
    } else {
        content = spEsc(m.message);
    }

    return '<div class="sp-chat-msg ' + m.sender + '">'
        + agentHtml
        + '<div class="sp-msg-bubble">' + content + '</div>'
        + '<div class="sp-msg-time">' + m.created_at + '</div>'
        + '</div>';
}

function spRenderMessages(msgs) {
    var box = document.getElementById('spChatMsgs');
    if (!msgs || !msgs.length) {
        box.innerHTML = '<p style="font-size:.75rem;color:#475569;text-align:center;margin:auto;">Send us a message — we\'ll reply shortly.</p>';
        return;
    }
    box.innerHTML = msgs.map(spRenderMsg).join('');
    box.scrollTop = box.scrollHeight;
}

// ── Send text ────────────────────────────────────────────────
function spSendMsg() {
    // If image staged → send image
    if (spStagedFile) { spUploadStaged(); return; }
    var input = document.getElementById('spChatInput');
    var msg = input.value.trim();
    if (!msg) return;
    input.value = '';
    fetch(SUPPORT_SEND, {
        method: 'POST',
        headers: {'Content-Type':'application/json','X-CSRF-TOKEN':SP_CSRF},
        body: JSON.stringify({message: msg})
    }).then(() => spLoadMessages());
}

// ── Escape HTML ───────────────────────────────────────────────
function spEsc(s) {
    return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

// ── Image sharing (paste / pick) ─────────────────────────────
var spStagedFile = null;
function spPickImage() {
    document.getElementById('spFileInput').click();
}
function spHandleFileSelect(input) {
    if (input.files && input.files[0]) spStageFile(input.files[0]);
}
function spStageFile(file) {
    if (!file.type.startsWith('image/')) return;
    spStagedFile = file;
    var reader = new FileReader();
    reader.onload = function(e) {
        var preview = document.getElementById('spImgPreview');
        document.getElementById('spImgThumb').src = e.target.result;
        document.getElementById('spImgName').textContent = file.name || 'pasted image';
        preview.style.display = 'flex';
    };
    reader.readAsDataURL(file);
}
function spClearImg() {
    spStagedFile = null;
    document.getElementById('spImgPreview').style.display = 'none';
    document.getElementById('spImgThumb').src = '';
}
function spUploadStaged() {
    if (!spStagedFile) return;
    var fd = new FormData();
    fd.append('file', spStagedFile);
    fd.append('type', 'image');
    fd.append('caption', document.getElementById('spChatInput').value.trim());
    fd.append('_token', SP_CSRF);
    spClearImg();
    document.getElementById('spChatInput').value = '';
    fetch(SUPPORT_UPLOAD, {method:'POST', body: fd})
        .then(() => spLoadMessages());
}

// ── Clipboard paste ───────────────────────────────────────────
document.addEventListener('paste', function(e) {
    if (!spChatOpen) return;
    var items = (e.clipboardData || e.originalEvent.clipboardData).items;
    for (var i = 0; i < items.length; i++) {
        if (items[i].type.startsWith('image/')) {
            var file = items[i].getAsFile();
            if (file) spStageFile(file);
            e.preventDefault();
            break;
        }
    }
});

// ── Voice recording ───────────────────────────────────────────
var spMediaRecorder = null;
var spAudioChunks   = [];
var spRecTimerEl    = null;
var spRecSeconds    = 0;

function spToggleRecording() {
    if (spMediaRecorder && spMediaRecorder.state === 'recording') {
        spStopRecording(true);
    } else {
        spStartRecording();
    }
}
function spStartRecording() {
    navigator.mediaDevices.getUserMedia({audio:true}).then(function(stream) {
        spAudioChunks = [];
        spMediaRecorder = new MediaRecorder(stream);
        spMediaRecorder.ondataavailable = function(e) { spAudioChunks.push(e.data); };
        spMediaRecorder.start();
        document.getElementById('spRecIndicator').style.display = 'flex';
        document.getElementById('spVoiceBtn').classList.add('active');
        spRecSeconds = 0;
        spRecTimerEl = setInterval(function() {
            spRecSeconds++;
            var m = Math.floor(spRecSeconds/60), s = spRecSeconds%60;
            document.getElementById('spRecTime').textContent = m + ':' + (s<10?'0':'') + s;
        }, 1000);
    }).catch(function() { alert('Microphone access denied.'); });
}
function spStopRecording(send) {
    if (!spMediaRecorder) return;
    clearInterval(spRecTimerEl);
    document.getElementById('spRecIndicator').style.display = 'none';
    document.getElementById('spVoiceBtn').classList.remove('active');
    spMediaRecorder.onstop = function() {
        if (send) {
            var blob = new Blob(spAudioChunks, {type:'audio/webm'});
            var fd   = new FormData();
            fd.append('file', blob, 'voice_' + Date.now() + '.webm');
            fd.append('type', 'voice');
            fd.append('_token', SP_CSRF);
            fetch(SUPPORT_UPLOAD, {method:'POST', body:fd}).then(() => spLoadMessages());
        }
        // Stop all tracks
        spMediaRecorder.stream.getTracks().forEach(t => t.stop());
        spMediaRecorder = null;
        spAudioChunks   = [];
    };
    spMediaRecorder.stop();
}

// ── Notification sound ────────────────────────────────────────
var spPrevUnread = 0;
function spPlaySound() {
    try {
        var ctx = new (window.AudioContext || window.webkitAudioContext)();
        [[660,.0,.1,.35],[880,.12,.1,.3],[1100,.24,.14,.25]].forEach(function(n){
            var o=ctx.createOscillator(),g=ctx.createGain();
            o.type='sine';o.frequency.value=n[0];
            g.gain.setValueAtTime(n[3],ctx.currentTime+n[1]);
            g.gain.exponentialRampToValueAtTime(.001,ctx.currentTime+n[1]+n[2]);
            o.connect(g);g.connect(ctx.destination);
            o.start(ctx.currentTime+n[1]);o.stop(ctx.currentTime+n[1]+n[2]);
        });
    } catch(e){}
}
function spShowNotif(msg) {
    spPlaySound();
    var n = document.getElementById('spNewMsgNotif');
    if (n) { n.textContent = '💬 ' + msg; n.style.display='flex'; setTimeout(function(){n.style.display='none';},6000); }
    if (Notification.permission === 'granted') {
        new Notification('Server Panel — Support Reply', {body: msg});
    }
}

// ── Poll for new replies every 10s ────────────────────────────
setInterval(function() {
    fetch(SUPPORT_MSGS)
        .then(r => r.json())
        .then(function(d) {
            var badge = document.getElementById('chatBadge');
            badge.textContent = d.unread;
            badge.style.display = d.unread > 0 ? 'flex' : 'none';
            if (d.unread > spPrevUnread) {
                var lastAdmin = [...(d.messages||[])].reverse().find(m => m.sender === 'admin');
                var notifText = lastAdmin && lastAdmin.agent_name
                    ? lastAdmin.agent_name + ' replied!'
                    : 'Admin replied to your message!';
                spShowNotif(notifText);
            }
            spPrevUnread = d.unread;
            if (spChatOpen) spRenderMessages(d.messages);
        });
}, 10000);
if (Notification.permission === 'default') {
    document.addEventListener('click', function(){ Notification.requestPermission(); }, {once:true});
}

// ════════════════════════════════════════════════
// NOTIFICATION BELL BADGE POLLER
// ════════════════════════════════════════════════
var NOTIF_UNREAD  = '<?php echo e(route("notif.unread")); ?>';
var spNotifPrevUnread = 0;
var spNotifSoundLoop  = null;

function spUpdateBells(count) {
    var countEls = document.querySelectorAll('.sp-notif-count');
    var bells    = [document.getElementById('topbarBell'), document.getElementById('sidebarBell')];
    countEls.forEach(function(el) {
        if (count > 0) {
            el.textContent  = count > 99 ? '99+' : count;
            el.style.display = 'flex';
        } else {
            el.style.display = 'none';
        }
    });
    bells.forEach(function(el) {
        if (!el) return;
        if (count > 0) el.classList.add('has-unread');
        else           el.classList.remove('has-unread');
    });

    // Loop sound while unread notifications exist
    if (count > 0 && !spNotifSoundLoop) {
        spPlaySound();
        spNotifSoundLoop = setInterval(function() { spPlaySound(); }, 8000);
    } else if (count === 0 && spNotifSoundLoop) {
        clearInterval(spNotifSoundLoop);
        spNotifSoundLoop = null;
    }
}

function spPollNotifUnread() {
    fetch(NOTIF_UNREAD)
        .then(function(r){ return r.json(); })
        .then(function(d) {
            spUpdateBells(d.count);
            spNotifPrevUnread = d.count;
        });
}

// Poll every 20s
setInterval(spPollNotifUnread, 20000);
spPollNotifUnread();
</script>
<?php endif; ?>

<!-- Particles.js CDN -->
<script src="https://cdn.jsdelivr.net/npm/particles.js@2.0.0/particles.min.js"></script>
<script>
particlesJS('particles-js', {
    particles: {
        number: { value: 55, density: { enable: true, value_area: 900 } },
        color: { value: ['#6366f1','#38bdf8','#ec4899','#a371f7'] },
        shape: { type: 'circle' },
        opacity: { value: 0.25, random: true, anim: { enable: true, speed: 0.6, opacity_min: 0.05, sync: false } },
        size: { value: 2.5, random: true },
        line_linked: { enable: true, distance: 140, color: '#6366f1', opacity: 0.1, width: 1 },
        move: { enable: true, speed: 0.7, direction: 'none', random: true, straight: false, out_mode: 'out' }
    },
    interactivity: {
        detect_on: 'canvas',
        events: { onhover: { enable: true, mode: 'grab' }, onclick: { enable: false }, resize: true },
        modes: { grab: { distance: 160, line_linked: { opacity: 0.3 } } }
    },
    retina_detect: true
});

// ── Sidebar toggle ────────────────────────────────────────
const sidebar  = document.getElementById('spSidebar');
const overlay  = document.getElementById('spOverlay');
const hamburger= document.getElementById('spHamburger');
const hamIcon  = document.getElementById('spHamIcon');

function openSidebar() {
    sidebar.classList.add('open');
    overlay.classList.add('show');
    hamIcon.className = 'fas fa-times';
}
function closeSidebar() {
    sidebar.classList.remove('open');
    overlay.classList.remove('show');
    hamIcon.className = 'fas fa-bars';
}

hamburger.addEventListener('click', function() {
    sidebar.classList.contains('open') ? closeSidebar() : openSidebar();
});
overlay.addEventListener('click', closeSidebar);

// Close sidebar when nav link clicked on mobile
sidebar.querySelectorAll('a').forEach(function(link) {
    link.addEventListener('click', function() {
        if (window.innerWidth <= 900) closeSidebar();
    });
});
</script>
<?php echo $__env->yieldContent('scripts'); ?>
</body>
</html>
<?php /**PATH /home/fullread/public_html/resources/views/layouts/dashboard.blade.php ENDPATH**/ ?>