<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    @php
        $pageWebsite = \App\Models\WebsiteSetting::current();
    @endphp
    <title>{{ $title ?? 'Dashboard' }} | {{ $pageWebsite->website_name }}</title>
    @if($pageWebsite->favicon)<link rel="icon" href="{{ asset('storage/'.$pageWebsite->favicon) }}">@endif
    <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=Inter:wght@400;500;600;700;800&family=Poppins:wght@500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
@php
    $theme = in_array(\App\Models\Setting::valueFor('theme_preset', 'sky-sun'), ['sky-sun','cloud','lemon','glass'], true) ? \App\Models\Setting::valueFor('theme_preset', 'sky-sun') : 'sky-sun';
    $font = \App\Models\Setting::valueFor('font_preset', 'studio');
    $cardFinish = \App\Models\Setting::valueFor('card_finish', 'gloss');
    $website = \App\Models\WebsiteSetting::current();
    $brandTheme = \App\Models\BrandSetting::current();
    $role = auth()->user()->role;
    $oneTimeClient = $role === 'client' && auth()->user()->client_type === 'one_time';
    $portalRole = auth()->user()->portalRole();
    $isAdminPortal = auth()->user()->isAdminRole();
    $isGtsAdminPortal = $isAdminPortal && request()->routeIs('gts-admin.*');
    $userId = auth()->id();
    $tasksReady = \Illuminate\Support\Facades\Schema::hasTable('tasks');
    $requestsReady = \Illuminate\Support\Facades\Schema::hasTable('client_requests');
    $paymentsReady = \Illuminate\Support\Facades\Schema::hasTable('payments');
    $gtsTablesReady = \Illuminate\Support\Facades\Schema::hasTable('gts_orders') && \Illuminate\Support\Facades\Schema::hasTable('gts_wallet_transactions');
    $notificationsReady = \Illuminate\Support\Facades\Schema::hasTable('notifications');
    $adminPulse = $isAdminPortal ? [
        'tasks' => $tasksReady ? \App\Models\Task::whereIn('status', ['pending', 'assigned', 'in_progress', 'revision_required'])->count() : 0,
        'requests' => $requestsReady ? \App\Models\ClientRequest::whereIn('status', ['pending', 'assigned'])->count() : 0,
        'payments' => $paymentsReady ? \App\Models\Payment::where('status', 'pending')->count() : 0,
        'notifications' => $notificationsReady ? \App\Models\AgencyNotification::where('status', 'unread')->count() : 0,
    ] : [];
    $gtsAdminPulse = ($isAdminPortal && $gtsTablesReady) ? [
        'orders' => \App\Models\GtsOrder::whereIn('status', ['queued', 'processing', 'partial'])->count(),
        'deposits' => \App\Models\GtsWalletTransaction::where('type', 'credit')->where('status', 'pending')->count(),
    ] : ['orders' => 0, 'deposits' => 0];
    $clientPulse = $role === 'client' ? [
        'requests' => $requestsReady ? \App\Models\ClientRequest::where('user_id', $userId)->where('status', 'pending')->count() : 0,
        'work' => $tasksReady ? \App\Models\Task::where('client_id', $userId)->whereNotIn('status', ['completed', 'delivered'])->count() : 0,
        'downloads' => $tasksReady && \Illuminate\Support\Facades\Schema::hasTable('task_files') ? \App\Models\Task::where('client_id', $userId)->whereHas('files')->count() : 0,
        'payments' => $paymentsReady ? \App\Models\Payment::where('user_id', $userId)->where('status', 'pending')->count() : 0,
    ] : [];
    $designerPulse = $role === 'designer' ? [
        'tasks' => $tasksReady ? \App\Models\Task::where('designer_id', $userId)->whereIn('status', ['pending', 'assigned', 'in_progress'])->count() : 0,
        'submitted' => $tasksReady ? \App\Models\Task::where('designer_id', $userId)->where('status', 'submitted')->count() : 0,
        'revisions' => $tasksReady ? \App\Models\Task::where('designer_id', $userId)->whereIn('status', ['revision', 'revision_required'])->count() : 0,
    ] : [];
    $gtsPulse = ($role === 'gts_client' && $gtsTablesReady && \Illuminate\Support\Facades\Schema::hasTable('gts_wallets')) ? [
        'orders' => \App\Models\GtsOrder::where('user_id', $userId)->whereIn('status', ['queued', 'processing', 'partial'])->count(),
        'completed' => \App\Models\GtsOrder::where('user_id', $userId)->where('status', 'completed')->count(),
        'balance' => \App\Models\GtsWallet::where('user_id', $userId)->value('balance') ?? 0,
    ] : ['orders' => 0, 'completed' => 0, 'balance' => 0];
    $headerLinks = match (true) {
        $isAdminPortal => [
            ['label' => 'Portals', 'route' => 'admin.portal', 'badge' => 0],
            ['label' => 'Alerts', 'route' => 'admin.notifications', 'badge' => $adminPulse['notifications'] ?? 0],
        ],
        $role === 'gts_client' => [
            ['label' => 'Wallet', 'route' => 'gts-client.wallet', 'badge' => 0],
            ['label' => 'Orders', 'route' => 'gts-client.orders', 'badge' => $gtsPulse['orders'] ?? 0],
        ],
        $role === 'client' => [
            ['label' => 'New Order', 'route' => 'service.order', 'badge' => 0],
            ['label' => 'Support', 'route' => 'client.messages', 'badge' => 0],
        ],
        default => [
            ['label' => 'Tasks', 'route' => 'designer.tasks', 'badge' => $designerPulse['tasks'] ?? 0],
            ['label' => 'Messages', 'route' => 'designer.messages', 'badge' => 0],
        ],
    };
    $sidebarLinks = match (true) {
        $isAdminPortal && $isGtsAdminPortal => [
            ['gts-admin.dashboard', 'seller', 'GTS Dashboard', 0, 'view_reports'],
            ['admin.portal', 'panel', 'Portal Choose', 0, 'view_dashboard'],
            ['gts-admin.api-manager', 'settings', 'API Manager', 0, 'manage_plans', \App\Models\Setting::enabled('gts_api_manager_enabled', true)],
            ['gts-admin.gts-clients.index', 'clients', 'GTS Clients', 0, 'manage_clients'],
            ['gts-admin.gts-providers.index', 'settings', 'API Providers', 0, 'manage_plans', \Illuminate\Support\Facades\Schema::hasTable('gts_providers')],
            ['gts-admin.gts-services.index', 'services', 'GTS Services', 0, 'manage_plans'],
            ['gts-admin.gts-orders.index', 'tasks', 'GTS Orders', $gtsAdminPulse['orders'], 'manage_tasks'],
            ['gts-admin.gts-wallets.index', 'payments', 'Wallets', 0, 'manage_payments'],
            ['gts-admin.gts-wallet-transactions.index', 'methods', 'Deposits', $gtsAdminPulse['deposits'], 'manage_payments'],
            ['admin.notifications', 'bell', 'Notifications', $adminPulse['notifications'], 'view_dashboard'],
            ['admin.settings', 'settings', 'Settings', 0, 'edit_settings'],
        ],
        $isAdminPortal => [
            ['admin.dashboard', 'dashboard', 'Dashboard', 0, 'view_dashboard'],
            ['admin.portal', 'panel', 'Portal Choose', 0, 'view_dashboard'],
            ['admin.clients.index', 'clients', 'Clients', 0, 'manage_clients'],
            ['admin.client-subscriptions.index', 'plans', 'Subscriptions', 0, 'manage_clients'],
            ['admin.designers.index', 'designer', 'Designers', 0, 'manage_designers'],
            ['admin.plans.index', 'plans', 'Plans', 0, 'manage_plans'],
            ['admin.services.index', 'services', 'Services', 0, 'manage_plans'],
            ['admin.tasks.index', 'tasks', 'Tasks', $adminPulse['tasks'], 'manage_tasks'],
            ['admin.requests.index', 'requests', 'Requests', $adminPulse['requests'], 'manage_tasks'],
            ['admin.payments.index', 'payments', 'Payments', $adminPulse['payments'], 'manage_payments'],
            ['admin.payment-methods.index', 'methods', 'Payment Methods', 0, 'manage_payments'],
            ['admin.portfolio.index', 'portfolio', 'Portfolio', 0, 'manage_portfolio'],
            ['admin.about-sections.index', 'profile', 'About Content', 0, 'manage_portfolio'],
            ['admin.team-members.index', 'clients', 'Team Members', 0, 'manage_portfolio'],
            ['admin.reports', 'reports', 'Reports', 0, 'view_reports'],
            ['admin.notifications', 'bell', 'Notifications', $adminPulse['notifications'], 'view_dashboard'],
            ['admin.settings', 'settings', 'Settings', 0, 'edit_settings'],
        ],
        $role === 'client' => [
            ['client.dashboard', 'dashboard', 'Dashboard', 0, 'view_dashboard'],
            ['service.order', 'services', 'New Order', 0, 'view_dashboard', $oneTimeClient],
            ['client.plan', 'plans', 'My Plan', 0, 'view_dashboard', ! $oneTimeClient],
            ['client.requests', 'requests', 'My Requests', $clientPulse['requests'], 'submit_requests'],
            ['client.work', 'tasks', 'My Work', $clientPulse['work'], 'view_dashboard'],
            ['client.downloads', 'downloads', 'Downloads', $clientPulse['downloads'], 'download_files'],
            ['client.payments', 'payments', 'Payments', $clientPulse['payments'], 'view_dashboard'],
            ['client.messages', 'requests', 'Messages', 0, 'view_dashboard'],
            ['client.profile', 'profile', 'Profile Settings', 0, 'view_dashboard'],
            ['client.password', 'lock', 'Change Password', 0, 'view_dashboard'],
        ],
        $role === 'gts_client' => [
            ['gts-client.dashboard', 'dashboard', 'Dashboard', 0, 'view_dashboard'],
            ['gts-client.wallet', 'payments', 'Wallet', 0, 'view_dashboard'],
            ['gts-client.services', 'services', 'Services', 0, 'view_dashboard'],
            ['gts-client.orders', 'tasks', 'Orders', $gtsPulse['orders'], 'view_dashboard'],
            ['gts-client.settings', 'settings', 'Settings', 0, 'view_dashboard'],
        ],
        default => [
            ['designer.dashboard', 'dashboard', 'Dashboard', 0, 'view_dashboard'],
            ['designer.tasks', 'tasks', 'My Tasks', $designerPulse['tasks'], 'manage_tasks'],
            ['designer.upload', 'upload', 'Upload Work', 0, 'upload_files'],
            ['designer.submitted', 'downloads', 'Submitted Work', $designerPulse['submitted'], 'manage_tasks'],
            ['designer.revisions', 'revision', 'Revision Tasks', $designerPulse['revisions'], 'manage_tasks'],
            ['designer.completed', 'tasks', 'Completed', 0, 'manage_tasks'],
            ['designer.messages', 'requests', 'Messages', 0, 'view_dashboard'],
            ['designer.profile', 'profile', 'Profile Settings', 0, 'view_dashboard'],
            ['designer.password', 'lock', 'Change Password', 0, 'view_dashboard'],
        ],
    };
@endphp
<body class="dash-body @if(! $brandTheme->animations_enabled) animations-off @endif @if(! $brandTheme->gradient_enabled) gradients-off @endif" data-theme="{{ $theme }}" data-font="{{ $font }}" data-card-finish="{{ $cardFinish }}" style="--brand-primary:{{ $brandTheme->primary_color }};--brand-secondary:{{ $brandTheme->secondary_color }};--brand-bg:{{ $brandTheme->background_color }};--brand-text:{{ $brandTheme->text_color }};--brand-button-radius:{{ $brandTheme->button_radius }}px;--brand-card-radius:{{ $brandTheme->card_radius }}px;--brand-font:{{ $brandTheme->font_family }};">
    <aside class="sidebar" id="portal-sidebar">
        <nav class="side-nav">
            @foreach ($sidebarLinks as $link)
                @continue(isset($link[5]) && ! $link[5])
                @continue(isset($link[4]) && ! \App\Models\RolePermission::allows($role, $link[4]))
                <a class="{{ request()->routeIs($link[0]) ? 'active' : '' }}" href="{{ route($link[0]) }}" title="{{ $link[2] }}">
                    <x-sidebar-icon :name="$link[1]"/>
                    <span>{{ $link[2] }}</span>
                    @if (($link[3] ?? 0) > 0)<b class="pulse-badge">{{ $link[3] }}</b>@endif
                </a>
            @endforeach
        </nav>
        <form class="sidebar-logout" method="post" action="{{ route('logout') }}">@csrf<button class="btn full"><x-sidebar-icon name="lock"/><span>Logout</span></button></form>
    </aside>
    <button class="icon-button sidebar-toggle portal-floating-toggle" type="button" aria-label="Toggle sidebar" aria-controls="portal-sidebar" aria-expanded="true" onclick="togglePortalSidebar(this)"><x-sidebar-icon name="panel"/></button>
    <main class="dash-main">
        <header class="portal-topbar compact-portal-header">
            <div class="portal-title">
                <p class="eyebrow">{{ $isGtsAdminPortal ? 'GTS Portal' : str($role)->replace('_', ' ')->headline() }}</p>
                <h1>{{ $title ?? 'Dashboard' }}</h1>
            </div>
            <nav class="portal-header-actions" aria-label="Portal shortcuts">
                @foreach ($headerLinks as $headerLink)
                    <a class="ghost small" href="{{ route($headerLink['route']) }}">
                        {{ $headerLink['label'] }}
                        @if (($headerLink['badge'] ?? 0) > 0)<b>{{ $headerLink['badge'] }}</b>@endif
                    </a>
                @endforeach
                <a class="profile-chip compact-profile" href="{{ route($portalRole.'.dashboard') }}"><b>{{ strtoupper(substr(auth()->user()->name, 0, 1)) }}</b><span>{{ auth()->user()->name }}</span></a>
            </nav>
        </header>
        @if (session('status'))<div class="flash">{{ session('status') }}</div>@endif
        @if ($errors->any())<div class="flash error">{{ $errors->first() }}</div>@endif
        {{ $slot }}
    </main>
    <script>
        function syncPortalSidebarToggle(button) {
            if (button) {
                button.setAttribute('aria-expanded', document.body.classList.contains('sidebar-collapsed') ? 'false' : 'true');
            }
        }
        function togglePortalSidebar(button) {
            document.body.classList.toggle('sidebar-collapsed');
            localStorage.setItem('mgg-sidebar-collapsed', document.body.classList.contains('sidebar-collapsed') ? '1' : '0');
            syncPortalSidebarToggle(button);
        }
        if (localStorage.getItem('mgg-sidebar-collapsed') === '1') {
            document.body.classList.add('sidebar-collapsed');
        }
        syncPortalSidebarToggle(document.querySelector('.sidebar-toggle'));
    </script>
</body>
</html>
