<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <title><?php echo $__env->yieldContent('title', 'Dashboard'); ?> - <?php echo e(setting('site_name', config('app.name'))); ?></title>

    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">

    <style>
        :root {
            --sidebar-width: 260px;
            --sidebar-collapsed-width: 64px;
            --topbar-height: 60px;
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            top: 0;
            left: 0;
            height: 100vh;
            width: var(--sidebar-width);
            background: linear-gradient(180deg, #2c3e50 0%, #1a252f 100%);
            color: white;
            overflow: visible;
            z-index: 1000;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
        }
        .sidebar.collapsed {
            width: var(--sidebar-collapsed-width);
        }
        body.sidebar-collapsed .sidebar {
            width: var(--sidebar-collapsed-width);
        }

        .sidebar-header {
            padding: 20px;
            background: rgba(0,0,0,0.2);
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }

        .sidebar-header h4 {
            margin: 0;
            font-weight: 600;
            font-size: 20px;
        }

        .sidebar-menu {
            padding: 20px 0;
            height: calc(100vh - 96px);
            overflow-y: auto;
        }

        .menu-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 20px;
            color: rgba(255,255,255,0.8);
            text-decoration: none;
            transition: all 0.3s;
            border-left: 3px solid transparent;
            position: relative;
        }

        .menu-item:hover {
            background: rgba(255,255,255,0.1);
            color: white;
            border-left-color: #667eea;
        }

        .menu-item.active {
            background: rgba(102, 126, 234, 0.2);
            color: white;
            border-left-color: #667eea;
        }

        .menu-item i {
            width: 20px;
            margin-right: 10px;
        }
        .menu-label {
            display: inline-block;
            vertical-align: middle;
        }
        .menu-section {
            padding: 10px 20px 6px;
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 0.06em;
            color: rgba(255,255,255,0.5);
        }
        .menu-section-label {
            display: inline-block;
            vertical-align: middle;
        }
        .menu-section i {
            margin-right: 8px;
            font-size: 12px;
            vertical-align: -1px;
        }
        .menu-site-heading {
            margin: 10px 14px 6px;
            padding: 10px 12px;
            border-top: none;
            border-radius: 8px;
            background: #f8fafc;
            border: 1px solid rgba(15, 23, 42, 0.12);
            font-size: 16px;
            text-transform: none;
            letter-spacing: 0;
            color: #0f172a;
            font-weight: 700;
        }
        .menu-site-heading i {
            color: #334155;
        }
        .site-menu-block {
            margin: 10px 12px 14px;
            padding: 8px;
            border-radius: 12px;
            border: 1px solid rgba(255,255,255,0.16);
            box-shadow: inset 0 0 0 1px rgba(255,255,255,0.04);
        }
        .site-menu-block .menu-site-heading {
            margin: 0 0 6px;
            padding: 10px 12px;
        }
        .site-menu-block .menu-item {
            padding: 10px 12px;
            margin: 3px 0 0;
            border-left-width: 2px;
            border-radius: 8px;
        }
        .site-menu-block .menu-item i {
            margin-right: 9px;
        }
        .site-menu-block.site-theme-red {
            background: linear-gradient(180deg, #3b1313 0%, #250d0d 100%);
            border-color: rgba(227, 32, 20, 0.45);
            box-shadow: inset 0 0 0 1px rgba(227, 32, 20, 0.18);
        }
        .site-menu-block.site-theme-red .menu-site-heading {
            background: #f8fafc;
            border-color: rgba(120, 25, 25, 0.35);
            color: #3c1111;
        }
        .site-menu-block.site-theme-red .menu-site-heading i {
            color: #6f1d1d;
        }
        .site-menu-block.site-theme-red .menu-item:hover {
            background: rgba(227, 32, 20, 0.28);
            border-left-color: #f87171;
        }
        .site-menu-block.site-theme-red .menu-item.active {
            background: rgba(239, 68, 68, 0.36);
            border-left-color: #fecaca;
        }
        .site-menu-block.site-theme-gold {
            background: linear-gradient(180deg, #322214 0%, #21160f 100%);
            border-color: rgba(224, 131, 47, 0.48);
            box-shadow: inset 0 0 0 1px rgba(224, 131, 47, 0.2);
        }
        .site-menu-block.site-theme-gold .menu-site-heading {
            background: #f8fafc;
            border-color: rgba(121, 74, 22, 0.35);
            color: #3c2511;
        }
        .site-menu-block.site-theme-gold .menu-site-heading i {
            color: #8a5218;
        }
        .site-menu-block.site-theme-gold .menu-item:hover {
            background: rgba(224, 131, 47, 0.24);
            border-left-color: #facc15;
        }
        .site-menu-block.site-theme-gold .menu-item.active {
            background: rgba(217, 119, 6, 0.34);
            border-left-color: #fde68a;
        }

        .sidebar-badge {
            margin-left: auto;
            font-weight: 600;
            font-size: 10px;
        }
        body.sidebar-collapsed .sidebar-badge {
            margin-left: 0;
            position: absolute;
            right: 10px;
        }

        /* Topbar */
        .topbar {
            position: fixed;
            top: 0;
            left: var(--sidebar-width);
            right: 0;
            height: var(--topbar-height);
            background: white;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 30px;
            z-index: 999;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
        }
        body.sidebar-collapsed .topbar {
            left: var(--sidebar-collapsed-width);
        }

        .topbar-left h5 {
            margin: 0;
            font-weight: 600;
            color: #333;
        }
        .sidebar-toggle {
            background: none;
            border: none;
            color: #4b5563;
            font-size: 20px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 36px;
            height: 36px;
            border-radius: 8px;
            transition: background 0.2s, color 0.2s;
            cursor: pointer;
            margin-right: 10px;
        }
        .sidebar-toggle:hover {
            background: #f1f5f9;
            color: #1f2937;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .notification-btn {
            position: relative;
            background: none;
            border: none;
            font-size: 20px;
            color: #666;
            cursor: pointer;
            transition: color 0.3s;
        }

        .notification-btn:hover {
            color: #667eea;
        }

        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #dc3545;
            color: white;
            border-radius: 10px;
            padding: 2px 6px;
            font-size: 10px;
            font-weight: bold;
        }

        .notification-badge.is-dot,
        .sidebar-badge.is-dot {
            width: 10px;
            height: 10px;
            padding: 0;
            border-radius: 50%;
            display: inline-block;
            text-indent: -9999px;
            overflow: hidden;
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--primary-gradient);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
        }

        .user-avatar i {
            font-size: 18px;
        }

        .dropdown-icon {
            font-size: 12px;
            color: #888;
        }

        /* Main Content */
        .main-content {
            margin-left: var(--sidebar-width);
            margin-top: var(--topbar-height);
            padding: 30px;
            min-height: calc(100vh - var(--topbar-height));
        }
        body.sidebar-collapsed .main-content {
            margin-left: var(--sidebar-collapsed-width);
        }

        body.sidebar-collapsed .sidebar-header h4,
        body.sidebar-collapsed .sidebar-header small,
        body.sidebar-collapsed .menu-label {
            display: none;
        }
        body.sidebar-collapsed .menu-section-label {
            display: none;
        }
        body.sidebar-collapsed .sidebar-header {
            text-align: center;
        }
        body.sidebar-collapsed .menu-item {
            padding: 12px 16px;
        }
        body.sidebar-collapsed .menu-item i {
            margin-right: 0;
        }
        body.sidebar-collapsed .menu-section {
            padding: 10px 16px 6px;
        }
        body.sidebar-collapsed .menu-site-heading {
            margin: 10px 8px 6px;
            padding: 10px 8px;
            text-align: center;
        }
        body.sidebar-collapsed .menu-site-heading i {
            margin-right: 0;
        }
        body.sidebar-collapsed .site-menu-block {
            margin: 10px 6px 12px;
            padding: 6px;
        }
        body.sidebar-collapsed .site-menu-block .menu-item {
            padding: 10px 8px;
        }
        body.sidebar-collapsed .site-menu-block .menu-item i {
            margin-right: 0;
        }
        body.sidebar-collapsed .site-menu-block .menu-site-heading {
            margin: 0 0 6px;
            padding: 10px 8px;
        }
        .sidebar-hover-label {
            position: fixed;
            left: 0;
            top: 0;
            transform: translateY(-50%);
            background: linear-gradient(180deg, #2c3e50 0%, #1a252f 100%);
            color: #ffffff;
            border: 1px solid rgba(102, 126, 234, 0.8);
            border-radius: 8px;
            padding: 7px 11px;
            font-size: 12px;
            font-weight: 600;
            white-space: nowrap;
            box-shadow: 0 8px 22px rgba(0, 0, 0, 0.28);
            z-index: 3000;
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.12s ease-in-out;
        }
        .sidebar-hover-label.is-visible {
            opacity: 1;
        }

        /* Cards */
        .card {
            border: none;
            border-radius: 10px;
        }

        .card-header {
            background: white;
            border-bottom: 1px solid #e0e0e0;
            padding: 15px 20px;
            font-weight: 600;
        }

        /* Action buttons in tables */
        .table .btn-group.btn-group-sm {
            display: inline-flex;
            flex-wrap: nowrap;
        }

        .table .btn-group.btn-group-sm .btn {
            min-width: 38px;
            padding: 0.35rem 0.55rem;
        }

        /* Scrollbar */
        .sidebar::-webkit-scrollbar {
            width: 6px;
        }

        .sidebar::-webkit-scrollbar-track {
            background: rgba(0,0,0,0.1);
        }

        .sidebar::-webkit-scrollbar-thumb {
            background: rgba(255,255,255,0.2);
            border-radius: 3px;
        }

        .sidebar::-webkit-scrollbar-thumb:hover {
            background: rgba(255,255,255,0.3);
        }
    </style>

    <?php echo $__env->yieldPushContent('styles'); ?>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="sidebar-header">
            <i class="bi bi-shield-lock fs-3 mb-2"></i>
            <h4><?php echo e(setting('site_name', 'Finance Panel')); ?></h4>
            <small class="text-light">Finance Portal</small>
        </div>
        <div class="sidebar-menu">
            <?php
                $sidebarSites = \App\Models\Site::orderBy('name')->get();
                $activeSiteRouteValue = request()->route('site');
                $activeSiteId = $activeSiteRouteValue instanceof \App\Models\Site
                    ? (int) $activeSiteRouteValue->id
                    : (is_numeric($activeSiteRouteValue) ? (int) $activeSiteRouteValue : null);
                $financeSidebarUser = auth()->guard('finance')->user();
                $financeSidebarGroup = $financeSidebarUser ? $financeSidebarUser->financeGroup : null;
                $financeCryptoEnabled = false;
                if ($financeSidebarGroup) {
                    $hasCryptoToggleColumn = \Illuminate\Support\Facades\Schema::hasColumn('finance_groups', 'is_crypto_enabled');
                    $financeCryptoEnabled = !$hasCryptoToggleColumn || (bool) $financeSidebarGroup->is_crypto_enabled;
                }
            ?>
            <div class="menu-section"><i class="bi bi-grid"></i> Genel</div>
            <a href="<?php echo e(route('finance.dashboard')); ?>" class="menu-item <?php echo e(request()->routeIs('finance.dashboard') ? 'active' : ''); ?>">
                <i class="bi bi-speedometer2"></i>
                Dashboard
            </a>

            <div class="menu-section"><i class="bi bi-arrow-left-right"></i> Islemler</div>
            <?php $__currentLoopData = $sidebarSites; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $sidebarSite): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <?php
                $siteSid = (string) ($sidebarSite->sid ?? '');
                if ($siteSid === 'pg_sid_7qcu15y1ippvtsh1wv3cbc70cugxp1ci') {
                    $siteThemeClass = 'site-theme-red';
                } elseif ($siteSid === 'pg_sid_8f3c1b2a4d5e6f708192a3b4c5d6e7f8') {
                    $siteThemeClass = 'site-theme-gold';
                } else {
                    $siteThemeClass = ($loop->iteration % 2 === 1) ? 'site-theme-red' : 'site-theme-gold';
                }
            ?>
            <div class="site-menu-block <?php echo e($siteThemeClass); ?>">
                <div class="menu-section menu-site-heading">
                    <i class="bi bi-globe2"></i> <?php echo e($sidebarSite->name); ?>

                </div>

                <a href="<?php echo e(route('finance.sites.deposits.index', $sidebarSite->id)); ?>" class="menu-item <?php echo e(request()->routeIs('finance.sites.deposits.*') && $activeSiteId === (int) $sidebarSite->id ? 'active' : ''); ?>">
                    <i class="bi bi-arrow-down-circle"></i>
                    Yatirimlar
                    <span
                        class="badge bg-warning text-dark sidebar-badge d-none"
                        data-badge-type="deposits"
                        data-site-id="<?php echo e((int) $sidebarSite->id); ?>"
                    >0</span>
                </a>

                <a href="<?php echo e(route('finance.sites.withdrawals.index', $sidebarSite->id)); ?>" class="menu-item <?php echo e(request()->routeIs('finance.sites.withdrawals.*') && $activeSiteId === (int) $sidebarSite->id ? 'active' : ''); ?>">
                    <i class="bi bi-arrow-up-circle"></i>
                    Cekimler
                    <span
                        class="badge bg-warning text-dark sidebar-badge d-none"
                        data-badge-type="withdrawals"
                        data-site-id="<?php echo e((int) $sidebarSite->id); ?>"
                    >0</span>
                </a>

                <a href="<?php echo e(route('finance.sites.bank-accounts.index', $sidebarSite->id)); ?>" class="menu-item <?php echo e(request()->routeIs('finance.sites.bank-accounts.*') && $activeSiteId === (int) $sidebarSite->id ? 'active' : ''); ?>">
                    <i class="bi bi-bank"></i>
                    Banka Hesaplari
                </a>
            </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

            <?php if($financeCryptoEnabled): ?>
            <a href="<?php echo e(route('finance.crypto-accounts.index')); ?>" class="menu-item <?php echo e(request()->routeIs('finance.crypto-accounts.*') ? 'active' : ''); ?>">
                <i class="bi bi-currency-bitcoin"></i>
                Kripto Hesablari
            </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Topbar -->
    <div class="topbar">
        <div class="topbar-left">
            <button type="button" class="sidebar-toggle" id="sidebarToggle" aria-label="Toggle sidebar">
                <i class="bi bi-list"></i>
            </button>
        </div>

        <div class="topbar-right">
            <button class="notification-btn" title="Bildirimler">
                <i class="bi bi-bell"></i>
                <span class="notification-badge">0</span>
            </button>

            <div class="dropdown">
                <div class="user-menu" data-bs-toggle="dropdown" aria-expanded="false">
                    <div class="user-avatar">
                        <i class="bi bi-person"></i>
                    </div>
                    <div class="d-none d-md-block">
                        <div class="fw-semibold"><?php echo e(auth()->guard('finance')->user()->full_name); ?></div>
                        <small class="text-muted"><?php echo e(auth()->guard('finance')->user()->financeGroup->name ?? 'Finans Kullanıcısı'); ?></small>
                    </div>
                    <i class="bi bi-chevron-down dropdown-icon"></i>
                </div>
                <div class="dropdown-menu dropdown-menu-end">
                    <a class="dropdown-item" href="<?php echo e(route('finance.2fa')); ?>">
                        <i class="bi bi-shield-lock me-1"></i>2FA Ayarlari
                    </a>
                    <form action="<?php echo e(route('finance.logout')); ?>" method="POST" class="px-3 py-1">
                        <?php echo csrf_field(); ?>
                        <button type="submit" class="btn btn-link p-0 text-danger">
                            <i class="bi bi-box-arrow-right me-1"></i>Cikis Yap
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

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

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <!-- Bootstrap 5 JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- DataTables -->
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <!-- Number Formatter -->
    <script src="<?php echo e(asset('js/number-formatter.js')); ?>"></script>

    <?php echo $__env->yieldPushContent('scripts'); ?>
    <script>
        (function () {
            const sidebar = document.querySelector('.sidebar');
            const toggle = document.getElementById('sidebarToggle');
            if (!sidebar || !toggle) return;

            function setCollapsed(isCollapsed) {
                document.body.classList.toggle('sidebar-collapsed', isCollapsed);
                sidebar.classList.toggle('collapsed', isCollapsed);
                localStorage.setItem('financeSidebarCollapsed', isCollapsed ? '1' : '0');
            }

            const saved = localStorage.getItem('financeSidebarCollapsed');
            if (saved === '1') {
                setCollapsed(true);
            }

            toggle.addEventListener('click', function () {
                const isCollapsed = document.body.classList.contains('sidebar-collapsed');
                setCollapsed(!isCollapsed);
            });

            document.querySelectorAll('.menu-item').forEach(function (item) {
                if (!item.dataset.label) {
                    const label = item.textContent.trim();
                    if (label) {
                        item.dataset.label = label;
                    }
                }
                if (!item.querySelector('.menu-label')) {
                    const nodes = Array.from(item.childNodes).filter(function (n) {
                        return n.nodeType === Node.TEXT_NODE && n.textContent.trim().length;
                    });
                    if (nodes.length) {
                        const span = document.createElement('span');
                        span.className = 'menu-label';
                        span.textContent = nodes.map(n => n.textContent).join(' ').trim();
                        nodes.forEach(n => n.parentNode.removeChild(n));
                        const badge = item.querySelector('.sidebar-badge');
                        if (badge) {
                            item.insertBefore(span, badge);
                        } else {
                            item.appendChild(span);
                        }
                    }
                }
                const menuLabel = item.querySelector('.menu-label');
                const cleanLabel = menuLabel ? menuLabel.textContent.trim() : '';
                if (cleanLabel) {
                    item.dataset.label = cleanLabel;
                }
            });

            document.querySelectorAll('.menu-section').forEach(function (section) {
                if (!section.querySelector('.menu-section-label')) {
                    const nodes = Array.from(section.childNodes).filter(function (n) {
                        return n.nodeType === Node.TEXT_NODE && n.textContent.trim().length;
                    });
                    if (nodes.length) {
                        const span = document.createElement('span');
                        span.className = 'menu-section-label';
                        span.textContent = nodes.map(n => n.textContent).join(' ').trim();
                        nodes.forEach(n => n.parentNode.removeChild(n));
                        section.appendChild(span);
                    }
                }
            });

            let hoverLabel = null;
            function removeHoverLabel() {
                if (!hoverLabel) {
                    return;
                }
                hoverLabel.remove();
                hoverLabel = null;
            }

            function showHoverLabel(item) {
                const labelText = (item.dataset.label || '').trim();
                const isCollapsed = document.body.classList.contains('sidebar-collapsed');
                if (!labelText || !isCollapsed) {
                    return;
                }

                removeHoverLabel();
                hoverLabel = document.createElement('div');
                hoverLabel.className = 'sidebar-hover-label';
                hoverLabel.textContent = labelText;
                document.body.appendChild(hoverLabel);

                const rect = item.getBoundingClientRect();
                hoverLabel.style.left = `${Math.round(rect.right + 10)}px`;
                hoverLabel.style.top = `${Math.round(rect.top + rect.height / 2)}px`;
                requestAnimationFrame(function () {
                    if (hoverLabel) {
                        hoverLabel.classList.add('is-visible');
                    }
                });
            }

            document.querySelectorAll('.menu-item').forEach(function (item) {
                item.addEventListener('mouseenter', function () {
                    showHoverLabel(item);
                });
                item.addEventListener('mouseleave', removeHoverLabel);
                item.addEventListener('focus', function () {
                    showHoverLabel(item);
                });
                item.addEventListener('blur', removeHoverLabel);
            });

            window.addEventListener('scroll', removeHoverLabel, { passive: true });
            window.addEventListener('resize', removeHoverLabel);
            toggle.addEventListener('click', removeHoverLabel);
        })();
    </script>
    <script>
        $(document).ready(function() {
            const badge = document.querySelector('.notification-badge');
            const depositBadges = Array.from(document.querySelectorAll('[data-badge-type="deposits"][data-site-id]'));
            const withdrawalBadges = Array.from(document.querySelectorAll('[data-badge-type="withdrawals"][data-site-id]'));
            if (!badge && !depositBadges.length && !withdrawalBadges.length) return;

            function setBadgeState(el, count) {
                if (!el) return;
                if (count > 0) {
                    el.classList.remove('d-none');
                    el.classList.remove('is-dot');
                    el.textContent = String(count);
                } else {
                    el.classList.add('d-none');
                    el.classList.remove('is-dot');
                    el.textContent = '0';
                }
            }

            function getStatsRequestParams(siteId) {
                const params = {
                    date_mode: 'actual',
                    date_from: '2000-01-01 00:00',
                    date_to: '2099-12-31 23:59'
                };
                if (siteId) {
                    params.site_id = siteId;
                }
                return params;
            }

            async function fetchPendingCount(url, siteId) {
                try {
                    const response = await $.get(url, getStatsRequestParams(siteId));
                    return Number((response || {}).pending || 0);
                } catch (error) {
                    return 0;
                }
            }

            async function updatePendingBadge() {
                const siteIds = Array.from(new Set(
                    depositBadges
                        .concat(withdrawalBadges)
                        .map(function (el) { return Number(el.dataset.siteId || 0); })
                        .filter(function (v) { return v > 0; })
                ));

                if (!siteIds.length) {
                    const [depositPending, withdrawalPending] = await Promise.all([
                        fetchPendingCount('<?php echo e(route("finance.deposits.stats")); ?>'),
                        fetchPendingCount('<?php echo e(route("finance.withdrawals.stats")); ?>')
                    ]);
                    const totalPending = depositPending + withdrawalPending;
                    if (badge) {
                        if (totalPending > 0) {
                            badge.classList.remove('d-none');
                            badge.classList.add('is-dot');
                            badge.textContent = '';
                        } else {
                            badge.classList.add('d-none');
                            badge.classList.remove('is-dot');
                        }
                    }
                    return;
                }

                let totalPending = 0;

                await Promise.all(siteIds.map(async function(siteId) {
                    const [depositStats, withdrawalStats] = await Promise.all([
                        fetchPendingCount('<?php echo e(route("finance.deposits.stats")); ?>', siteId),
                        fetchPendingCount('<?php echo e(route("finance.withdrawals.stats")); ?>', siteId),
                    ]);

                    const depositPending = Number(depositStats || 0);
                    const withdrawalPending = Number(withdrawalStats || 0);
                    totalPending += depositPending + withdrawalPending;

                    depositBadges
                        .filter(function (el) { return Number(el.dataset.siteId || 0) === siteId; })
                        .forEach(function (el) { setBadgeState(el, depositPending); });

                    withdrawalBadges
                        .filter(function (el) { return Number(el.dataset.siteId || 0) === siteId; })
                        .forEach(function (el) { setBadgeState(el, withdrawalPending); });
                }));

                if (badge) {
                    if (totalPending > 0) {
                        badge.classList.remove('d-none');
                        badge.classList.add('is-dot');
                        badge.textContent = '';
                    } else {
                        badge.classList.add('d-none');
                        badge.classList.remove('is-dot');
                    }
                }
            }

            updatePendingBadge();
            setInterval(updatePendingBadge, 5000);
        });
    </script>
    <?php if(
        !request()->routeIs('finance.deposits.*')
        && !request()->routeIs('finance.withdrawals.*')
        && !request()->routeIs('finance.sites.deposits.*')
        && !request()->routeIs('finance.sites.withdrawals.*')
    ): ?>
    <script>
        $(document).ready(function() {
            const soundEnabled = '<?php echo e(setting('notification_sound', 'enabled')); ?>' !== 'disabled';
            let lastDepositTimestamp = Math.floor(Date.now() / 1000);
            let lastWithdrawalTimestamp = Math.floor(Date.now() / 1000);
            let pollingInterval = null;

            const depositSound = new Audio('<?php echo e(asset('audio/deposit.mp3')); ?>');
            depositSound.preload = 'auto';
            depositSound.volume = 0.7;

            const withdrawalSound = new Audio('<?php echo e(asset('audio/withdrawal.mp3')); ?>');
            withdrawalSound.preload = 'auto';
            withdrawalSound.volume = 0.7;

            let soundUnlocked = false;

            function unlockSound() {
                if (soundUnlocked || !soundEnabled) return;
                depositSound.play().then(function() {
                    depositSound.pause();
                    depositSound.currentTime = 0;
                    soundUnlocked = true;
                }).catch(function() {});
            }

            document.addEventListener('click', unlockSound, { once: true });
            document.addEventListener('keydown', unlockSound, { once: true });
            document.addEventListener('touchstart', unlockSound, { once: true });

            function playSound(type) {
                if (!soundEnabled) return;
                if (!soundUnlocked) {
                    unlockSound();
                }
                const audio = type === 'withdrawal' ? withdrawalSound : depositSound;
                audio.currentTime = 0;
                audio.play().catch(() => {});
            }

            const notificationToast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true,
                didOpen: (toast) => {
                    toast.addEventListener('mouseenter', Swal.stopTimer);
                    toast.addEventListener('mouseleave', Swal.resumeTimer);
                }
            });

            function showNotificationToast(options) {
                const fire = () => notificationToast.fire(options);
                if (Swal.isVisible()) {
                    const interval = setInterval(function() {
                        if (!Swal.isVisible()) {
                            clearInterval(interval);
                            fire();
                        }
                    }, 250);
                    return;
                }
                fire();
            }

            function resolveSiteLabel(items) {
                if (!Array.isArray(items) || items.length === 0) {
                    return 'Tum Siteler';
                }
                const names = Array.from(new Set(
                    items
                        .map(function(item) { return String(item.site_name || '').trim(); })
                        .filter(function(name) { return name && name !== '-'; })
                ));
                if (!names.length) {
                    return 'Tum Siteler';
                }
                if (names.length === 1) {
                    return names[0];
                }
                return names[0] + ' +' + (names.length - 1);
            }

            function checkNewDeposits() {
                $.ajax({
                    url: '<?php echo e(route("finance.deposits.check-new")); ?>',
                    method: 'GET',
                    data: { since: lastDepositTimestamp },
                    success: function(response) {
                        if (!response || !response.success) {
                            return;
                        }

                        const latestFromServer = response.latest_timestamp ? Number(response.latest_timestamp) : lastDepositTimestamp;
                        if (response.data && response.data.length > 0) {
                            const latestCreated = Math.max(...response.data.map(d => d.created_at_timestamp));
                            lastDepositTimestamp = Math.max(lastDepositTimestamp, latestFromServer, latestCreated);
                        } else {
                            lastDepositTimestamp = Math.max(lastDepositTimestamp, latestFromServer);
                        }

                        if (response.count > 0) {
                            playSound('deposit');
                            const siteLabel = resolveSiteLabel(response.data || []);
                            showNotificationToast({
                                title: siteLabel + ' - Yeni Yatirim',
                                html: `<strong>${response.count}</strong> yeni yatirim islemi alindi.`,
                                icon: 'info'
                            });
                        }
                    }
                });
            }

            function checkNewWithdrawals() {
                $.ajax({
                    url: '<?php echo e(route("finance.withdrawals.check-new")); ?>',
                    method: 'GET',
                    data: { since: lastWithdrawalTimestamp },
                    success: function(response) {
                        if (!response || !response.success) {
                            return;
                        }

                        const latestFromServer = response.latest_timestamp ? Number(response.latest_timestamp) : lastWithdrawalTimestamp;
                        if (response.data && response.data.length > 0) {
                            const latestCreated = Math.max(...response.data.map(d => d.created_at_timestamp));
                            lastWithdrawalTimestamp = Math.max(lastWithdrawalTimestamp, latestFromServer, latestCreated);
                        } else {
                            lastWithdrawalTimestamp = Math.max(lastWithdrawalTimestamp, latestFromServer);
                        }

                        if (response.count > 0) {
                            playSound('withdrawal');
                            const siteLabel = resolveSiteLabel(response.data || []);
                            showNotificationToast({
                                title: siteLabel + ' - Yeni Cekim',
                                html: `<strong>${response.count}</strong> yeni cekim islemi alindi.`,
                                icon: 'info'
                            });
                        }
                    }
                });
            }

            function startPolling() {
                pollingInterval = setInterval(function() {
                    checkNewDeposits();
                    checkNewWithdrawals();
                }, 5000);
            }

            startPolling();
        });
    </script>
    <?php endif; ?>
</body>
</html>


<?php /**PATH /home/cmummhol/public_html/zoom/resources/views/finance/layouts/app.blade.php ENDPATH**/ ?>