<?php
    $user = auth()->user();
    $tenant = $user?->tenant;
    $agentProfile = $user?->role === \App\Models\User::ROLE_AGENT ? $user->agent : null;
    $primary = $tenant?->primary_color ?: '#155e75';
    $sidebarName = $user?->isSuperAdmin()
        ? config('app.name')
        : ($agentProfile?->displayName() ?: $tenant?->name);
?>
<!doctype html>
<html lang="<?php echo e(str_replace('_', '-', app()->getLocale())); ?>" data-service-worker="<?php echo e(asset('sw.js')); ?>" data-mobile-app-url="<?php echo e(route('mobile-app')); ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
    <meta name="theme-color" content="<?php echo e($primary); ?>">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="NewKipp">
    <title><?php echo $__env->yieldContent('title', config('app.name')); ?></title>
    <link rel="manifest" href="<?php echo e(asset('manifest.webmanifest')); ?>">
    <link rel="icon" type="image/svg+xml" href="<?php echo e(asset('pwa/icon.svg')); ?>">
    <link rel="apple-touch-icon" href="<?php echo e(asset('pwa/maskable-icon.svg')); ?>">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <link href="<?php echo e(asset('css/app.css')); ?>?v=<?php echo e(@filemtime(public_path('css/app.css')) ?: '1'); ?>" rel="stylesheet">
    <style>:root{--tenant-primary: <?php echo e($primary); ?>;}</style>
</head>
<body class="<?php echo \Illuminate\Support\Arr::toCssClasses(['app-authenticated' => auth()->check()]); ?>">
<?php if(auth()->guard()->check()): ?>
    <div class="app-shell d-lg-flex">
        <aside class="sidebar p-3 no-print">
            <div class="d-flex align-items-center gap-2 mb-4">
                <?php if($tenant?->displayLogoUrl()): ?>
                    <img src="<?php echo e($tenant->displayLogoUrl()); ?>" alt="<?php echo e($tenant->name); ?>" width="38" height="38" class="rounded bg-white object-fit-cover">
                <?php else: ?>
                    <div class="rounded bg-info-subtle text-info-emphasis d-grid place-items-center fw-bold" style="width:38px;height:38px;">MF</div>
                <?php endif; ?>
                <div class="lh-sm">
                    <div class="fw-semibold text-white"><?php echo e($sidebarName); ?></div>
                    <small class="text-secondary"><?php echo e($user->roleLabel()); ?></small>
                </div>
            </div>

            <nav class="nav flex-column gap-1">
                <?php if($user->isSuperAdmin()): ?>
                    <a class="nav-link <?php echo e(request()->routeIs('super.dashboard') ? 'active' : ''); ?>" href="<?php echo e(route('super.dashboard')); ?>"><i class="bi bi-speedometer2 me-2"></i> Dashboard</a>
                    <a class="nav-link <?php echo e(request()->routeIs('super.tenants.*') ? 'active' : ''); ?>" href="<?php echo e(route('super.tenants.index')); ?>"><i class="bi bi-buildings me-2"></i> Tenants</a>
                    <a class="nav-link <?php echo e(request()->routeIs('super.agents.*') ? 'active' : ''); ?>" href="<?php echo e(route('super.agents.index')); ?>"><i class="bi bi-person-badge me-2"></i> Merchants</a>
                    <a class="nav-link <?php echo e(request()->routeIs('super.software-products.*') ? 'active' : ''); ?>" href="<?php echo e(route('super.software-products.index')); ?>"><i class="bi bi-grid-1x2 me-2"></i> Software Products</a>
                    <a class="nav-link <?php echo e(request()->routeIs('super.plans.*') ? 'active' : ''); ?>" href="<?php echo e(route('super.plans.index')); ?>"><i class="bi bi-box-seam me-2"></i> Plans</a>
                    <a class="nav-link <?php echo e(request()->routeIs('super.billing.*') ? 'active' : ''); ?>" href="<?php echo e(route('super.billing.index')); ?>"><i class="bi bi-receipt me-2"></i> Billing</a>
                    <a class="nav-link <?php echo e(request()->routeIs('super.notifications.*') ? 'active' : ''); ?>" href="<?php echo e(route('super.notifications.index')); ?>"><i class="bi bi-megaphone me-2"></i> Notifications</a>
                    <a class="nav-link <?php echo e(request()->routeIs('super.communication-units.*') ? 'active' : ''); ?>" href="<?php echo e(route('super.communication-units.index')); ?>"><i class="bi bi-chat-square-text me-2"></i> Message Units</a>
                    <a class="nav-link <?php echo e(request()->routeIs('super.vtu-wallets.*') ? 'active' : ''); ?>" href="<?php echo e(route('super.vtu-wallets.index')); ?>"><i class="bi bi-phone-vibrate me-2"></i> VTU Wallets</a>
                    <a class="nav-link <?php echo e(request()->routeIs('super.email-logs.*') ? 'active' : ''); ?>" href="<?php echo e(route('super.email-logs.index')); ?>"><i class="bi bi-envelope-check me-2"></i> Email Logs</a>
                    <a class="nav-link" href="<?php echo e(route('super.settings.index')); ?>#homepage-pane"><i class="bi bi-window me-2"></i> Homepage</a>
                    <a class="nav-link <?php echo e(request()->routeIs('super.support.*') ? 'active' : ''); ?>" href="<?php echo e(route('super.support.index')); ?>"><i class="bi bi-life-preserver me-2"></i> Support</a>
                    <a class="nav-link <?php echo e(request()->routeIs('super.settings.*') ? 'active' : ''); ?>" href="<?php echo e(route('super.settings.index')); ?>"><i class="bi bi-gear me-2"></i> Settings</a>
                <?php else: ?>
                    <?php if($user->role === \App\Models\User::ROLE_AGENT): ?>
                        <a class="nav-link <?php echo e(request()->routeIs('agent.dashboard') || request()->routeIs('merchant.dashboard') ? 'active' : ''); ?>" href="<?php echo e(route('merchant.dashboard')); ?>"><i class="bi bi-speedometer2 me-2"></i> Dashboard</a>
                        <a class="nav-link <?php echo e(request()->routeIs('merchant.software-products.*') ? 'active' : ''); ?>" href="<?php echo e(route('merchant.software-products.index')); ?>"><i class="bi bi-grid-1x2 me-2"></i> Software Products</a>
                        <?php if($agentProfile?->isActive()): ?>
                            <a class="nav-link" href="<?php echo e($agentProfile->referralUrl()); ?>" target="_blank" rel="noopener"><i class="bi bi-globe2 me-2"></i> My Landing Page</a>
                            <a class="nav-link" href="<?php echo e($agentProfile->tenantSignupUrl()); ?>" target="_blank" rel="noopener"><i class="bi bi-link-45deg me-2"></i> Onboard Tenant</a>
                        <?php else: ?>
                            <a class="nav-link" href="<?php echo e(route('merchant.dashboard')); ?>"><i class="bi bi-hourglass-split me-2"></i> Landing Pending</a>
                        <?php endif; ?>
                    <?php elseif($user->role === 'customer'): ?>
                        <a class="nav-link <?php echo e(request()->routeIs('member.dashboard') ? 'active' : ''); ?>" href="<?php echo e(route('member.dashboard')); ?>"><i class="bi bi-speedometer2 me-2"></i> Dashboard</a>
                        <a class="nav-link <?php echo e(request()->routeIs('member.dashboard') ? 'active' : ''); ?>" href="<?php echo e(route('member.dashboard')); ?>#member-profile"><i class="bi bi-person me-2"></i> Profile</a>
                        <a class="nav-link <?php echo e(request()->routeIs('member.dashboard') ? 'active' : ''); ?>" href="<?php echo e(route('member.dashboard')); ?>#savings"><i class="bi bi-wallet2 me-2"></i> Savings</a>
                        <a class="nav-link <?php echo e(request()->routeIs('member.dashboard') ? 'active' : ''); ?>" href="<?php echo e(route('member.dashboard')); ?>#transfers"><i class="bi bi-arrow-left-right me-2"></i> Transfers</a>
                        <a class="nav-link <?php echo e(request()->routeIs('member.dashboard') ? 'active' : ''); ?>" href="<?php echo e(route('member.dashboard')); ?>#loans"><i class="bi bi-cash-coin me-2"></i> Loans</a>
                        <a class="nav-link <?php echo e(request()->routeIs('member.dashboard') ? 'active' : ''); ?>" href="<?php echo e(route('member.dashboard')); ?>#member-investments"><i class="bi bi-piggy-bank me-2"></i> Investments</a>
                        <a class="nav-link <?php echo e(request()->routeIs('member.dashboard') ? 'active' : ''); ?>" href="<?php echo e(route('member.dashboard')); ?>#member-bills"><i class="bi bi-phone me-2"></i> Bills</a>
                        <a class="nav-link <?php echo e(request()->routeIs('member.dashboard') ? 'active' : ''); ?>" href="<?php echo e(route('member.dashboard')); ?>#member-transactions"><i class="bi bi-clock-history me-2"></i> Transactions</a>
                    <?php else: ?>
                        <?php
                            $can = fn (string $permission) => $user->hasPermission($permission);
                            $showProfiles = $can('customers.view') || $can('staff.manage') || $can('role_profiles.manage');
                            $showProducts = $can('savings.view') || $can('loans.view') || $can('investments.view');
                            $showTransactions = $can('savings.view') || $can('repayments.view') || $can('transfers.view');
                            $showReports = $can('reports.view') || $can('accounting.view');
                            $showNotifications = $can('notifications.send') || $can('bulk_sms.send') || $can('notifications.view');
                            $showSettings = $can('settings.manage') || $can('data_imports.manage') || $can('branches.manage');
                            $showAccountCenter = $can('billing.view') || $can('communication_units.manage') || $can('bill_payments.view') || $can('audit_trail.view') || $can('support.view');
                            $profilesActive = request()->routeIs('tenant.customers.*') || request()->routeIs('tenant.staff.*') || request()->routeIs('tenant.role-profiles.*');
                            $usersActive = request()->routeIs('tenant.staff.*') || request()->routeIs('tenant.role-profiles.*');
                            $productsActive = request()->routeIs('tenant.savings.*') || request()->routeIs('tenant.loans.*') || request()->routeIs('tenant.investments.*');
                            $transactionsActive = request()->routeIs('tenant.deposits.*') || request()->routeIs('tenant.withdrawals.*') || request()->routeIs('tenant.transfers.*') || request()->routeIs('tenant.repayments.*');
                            $reportsActive = request()->routeIs('tenant.reports.*') || request()->routeIs('tenant.accounting.*');
                            $notificationsActive = request()->routeIs('tenant.customer-notifications.*') || request()->routeIs('tenant.bulk-sms.*') || request()->routeIs('tenant.notifications.*');
                            $settingsActive = request()->routeIs('tenant.settings.*') || request()->routeIs('tenant.data-imports.*') || request()->routeIs('tenant.sync.*') || request()->routeIs('tenant.branches.*');
                            $accountCenterActive = request()->routeIs('tenant.billing.*') || request()->routeIs('tenant.communication-units.*') || request()->routeIs('tenant.vtu-wallet.*') || request()->routeIs('tenant.staff-wallet.*') || request()->routeIs('tenant.bill-payments.*') || request()->routeIs('tenant.audit-trail.*') || request()->routeIs('tenant.support.*');
                        ?>
                        <?php if($can('dashboard.view')): ?>
                            <a class="nav-link <?php echo e(request()->routeIs('tenant.dashboard') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.dashboard')); ?>"><i class="bi bi-speedometer2 me-2"></i> Dashboard</a>
                        <?php endif; ?>

                        <?php if($showProfiles): ?>
                            <button class="nav-link nav-group-toggle collapsed <?php echo e($profilesActive ? 'active' : ''); ?>" type="button" data-bs-toggle="collapse" data-bs-target="#tenantProfilesMenu" aria-expanded="false" aria-controls="tenantProfilesMenu">
                                <span><i class="bi bi-person-vcard me-2"></i> Profiles</span>
                                <i class="bi bi-chevron-right ms-auto nav-group-caret"></i>
                            </button>
                            <div class="collapse nav-collapse <?php echo e($profilesActive ? 'show' : ''); ?>" id="tenantProfilesMenu">
                                <?php if($can('customers.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.customers.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.customers.index')); ?>"><i class="bi bi-people me-2"></i> Members</a>
                                <?php endif; ?>
                                <?php if($can('staff.manage') || $can('role_profiles.manage')): ?>
                                    <button class="nav-link nav-sublink nav-group-toggle collapsed <?php echo e($usersActive ? 'active' : ''); ?>" type="button" data-bs-toggle="collapse" data-bs-target="#tenantUsersMenu" aria-expanded="false" aria-controls="tenantUsersMenu">
                                        <span><i class="bi bi-person-gear me-2"></i> Users</span>
                                        <i class="bi bi-chevron-right ms-auto nav-group-caret"></i>
                                    </button>
                                    <div class="collapse nav-collapse <?php echo e($usersActive ? 'show' : ''); ?>" id="tenantUsersMenu">
                                        <?php if($can('staff.manage')): ?>
                                            <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.staff.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.staff.index')); ?>"><i class="bi bi-person-badge me-2"></i> Staff</a>
                                        <?php endif; ?>
                                        <?php if($can('role_profiles.manage')): ?>
                                            <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.role-profiles.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.role-profiles.index')); ?>"><i class="bi bi-shield-lock me-2"></i> Role Profile</a>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>

                        <?php if($showProducts): ?>
                            <button class="nav-link nav-group-toggle collapsed <?php echo e($productsActive ? 'active' : ''); ?>" type="button" data-bs-toggle="collapse" data-bs-target="#tenantProductsMenu" aria-expanded="false" aria-controls="tenantProductsMenu">
                                <span><i class="bi bi-box-seam me-2"></i> Products</span>
                                <i class="bi bi-chevron-right ms-auto nav-group-caret"></i>
                            </button>
                            <div class="collapse nav-collapse" id="tenantProductsMenu">
                                <?php if($can('savings.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.savings.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.savings.index')); ?>"><i class="bi bi-wallet2 me-2"></i> Savings</a>
                                <?php endif; ?>
                                <?php if($can('loans.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.loans.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.loans.index')); ?>"><i class="bi bi-cash-coin me-2"></i> Loans</a>
                                <?php endif; ?>
                                <?php if($can('investments.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.investments.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.investments.index')); ?>"><i class="bi bi-piggy-bank me-2"></i> Investment</a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>

                        <?php if($showTransactions): ?>
                            <button class="nav-link nav-group-toggle collapsed <?php echo e($transactionsActive ? 'active' : ''); ?>" type="button" data-bs-toggle="collapse" data-bs-target="#tenantTransactionsMenu" aria-expanded="false" aria-controls="tenantTransactionsMenu">
                                <span><i class="bi bi-arrow-left-right me-2"></i> Transactions</span>
                                <i class="bi bi-chevron-right ms-auto nav-group-caret"></i>
                            </button>
                            <div class="collapse nav-collapse" id="tenantTransactionsMenu">
                                <?php if($can('savings.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.deposits.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.deposits.index')); ?>"><i class="bi bi-arrow-down-circle me-2"></i> Deposit</a>
                                <?php endif; ?>
                                <?php if($can('savings.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.withdrawals.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.withdrawals.index')); ?>"><i class="bi bi-arrow-up-circle me-2"></i> Withdrawal</a>
                                <?php endif; ?>
                                <?php if($can('transfers.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.transfers.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.transfers.index')); ?>"><i class="bi bi-arrow-left-right me-2"></i> Transfer</a>
                                <?php endif; ?>
                                <?php if($can('repayments.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.repayments.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.repayments.index')); ?>"><i class="bi bi-credit-card-2-front me-2"></i> Repayment</a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>

                        <?php if($can('expenses.view')): ?>
                            <a class="nav-link <?php echo e(request()->routeIs('tenant.expenses.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.expenses.index')); ?>"><i class="bi bi-cash-stack me-2"></i> Expenses</a>
                        <?php endif; ?>

                        <?php if($showReports): ?>
                            <button class="nav-link nav-group-toggle collapsed <?php echo e($reportsActive ? 'active' : ''); ?>" type="button" data-bs-toggle="collapse" data-bs-target="#tenantReportsMenu" aria-expanded="false" aria-controls="tenantReportsMenu">
                                <span><i class="bi bi-graph-up-arrow me-2"></i> Reports</span>
                                <i class="bi bi-chevron-right ms-auto nav-group-caret"></i>
                            </button>
                            <div class="collapse nav-collapse" id="tenantReportsMenu">
                                <?php if($can('reports.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.reports.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.reports.index')); ?>"><i class="bi bi-file-earmark-bar-graph me-2"></i> Reports Dashboard</a>
                                <?php endif; ?>
                                <?php if($can('accounting.view')): ?>
                                <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.accounting.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.accounting.index')); ?>"><i class="bi bi-journal-text me-2"></i> Accounting</a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>

                        <?php if($showNotifications): ?>
                            <button class="nav-link nav-group-toggle collapsed <?php echo e($notificationsActive ? 'active' : ''); ?>" type="button" data-bs-toggle="collapse" data-bs-target="#tenantNotificationsMenu" aria-expanded="false" aria-controls="tenantNotificationsMenu">
                                <span><i class="bi bi-bell me-2"></i> Notifications</span>
                                <i class="bi bi-chevron-right ms-auto nav-group-caret"></i>
                            </button>
                            <div class="collapse nav-collapse" id="tenantNotificationsMenu">
                                <?php if($can('notifications.send') || $can('bulk_sms.send')): ?>
                                <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.customer-notifications.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.customer-notifications.index')); ?>"><i class="bi bi-megaphone me-2"></i> Send Messages</a>
                                <?php endif; ?>
                                <?php if($can('notifications.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.notifications.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.notifications.index')); ?>"><i class="bi bi-bell me-2"></i> Alerts</a>
                                <?php endif; ?>
                                <?php if($can('settings.manage')): ?>
                                    <a class="nav-link nav-sublink" href="<?php echo e(route('tenant.settings.edit')); ?>#automation-pane"><i class="bi bi-broadcast me-2"></i> Automation Rules</a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>

                        <?php if($showSettings): ?>
                            <button class="nav-link nav-group-toggle collapsed <?php echo e($settingsActive ? 'active' : ''); ?>" type="button" data-bs-toggle="collapse" data-bs-target="#tenantSettingsMenu" aria-expanded="false" aria-controls="tenantSettingsMenu">
                                <span><i class="bi bi-gear me-2"></i> Settings</span>
                                <i class="bi bi-chevron-right ms-auto nav-group-caret"></i>
                            </button>
                            <div class="collapse nav-collapse" id="tenantSettingsMenu">
                                <?php if($can('settings.manage')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.settings.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.settings.edit')); ?>"><i class="bi bi-building-gear me-2"></i> Company Settings</a>
                                <?php endif; ?>
                                <?php if($can('data_imports.manage')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.data-imports.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.data-imports.index')); ?>"><i class="bi bi-file-earmark-arrow-up me-2"></i> Data Import</a>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.sync.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.sync.index')); ?>"><i class="bi bi-cloud-arrow-up me-2"></i> Sync Center</a>
                                <?php endif; ?>
                                <?php if($can('branches.manage')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.branches.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.branches.index')); ?>"><i class="bi bi-diagram-3 me-2"></i> Branches</a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>

                        <?php if($showAccountCenter): ?>
                            <button class="nav-link nav-group-toggle collapsed <?php echo e($accountCenterActive ? 'active' : ''); ?>" type="button" data-bs-toggle="collapse" data-bs-target="#tenantAccountCenterMenu" aria-expanded="false" aria-controls="tenantAccountCenterMenu">
                                <span><i class="bi bi-person-workspace me-2"></i> Account Center</span>
                                <i class="bi bi-chevron-right ms-auto nav-group-caret"></i>
                            </button>
                            <div class="collapse nav-collapse" id="tenantAccountCenterMenu">
                                <?php if($can('billing.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.billing.*') ? 'active' : ''); ?>" href="<?php echo e($tenant?->isOnTrial() ? route('tenant.billing.index').'#payment-options' : route('tenant.billing.index')); ?>">
                                        <i class="bi <?php echo e($tenant?->isOnTrial() ? 'bi-cash-coin' : 'bi-credit-card'); ?> me-2"></i> <?php echo e($tenant?->isOnTrial() ? 'Pay' : 'Billing'); ?>

                                    </a>
                                <?php endif; ?>
                                <?php if($can('communication_units.manage')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.communication-units.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.communication-units.index')); ?>"><i class="bi bi-chat-square-text me-2"></i> Message Units</a>
                                <?php endif; ?>
                                <?php if($can('bill_payments.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.vtu-wallet.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.vtu-wallet.index')); ?>"><i class="bi bi-phone-vibrate me-2"></i> VTU Wallet</a>
                                <?php endif; ?>
                                <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.staff-wallet.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.staff-wallet.index')); ?>"><i class="bi bi-wallet2 me-2"></i> My Wallet</a>
                                <?php if($can('bill_payments.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.bill-payments.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.bill-payments.index')); ?>"><i class="bi bi-phone me-2"></i> Bill Payments</a>
                                <?php endif; ?>
                                <?php if($can('audit_trail.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.audit-trail.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.audit-trail.index')); ?>"><i class="bi bi-activity me-2"></i> Audit Trail</a>
                                <?php endif; ?>
                                <?php if($can('support.view')): ?>
                                    <a class="nav-link nav-sublink <?php echo e(request()->routeIs('tenant.support.*') ? 'active' : ''); ?>" href="<?php echo e(route('tenant.support.index')); ?>"><i class="bi bi-life-preserver me-2"></i> Support</a>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                <?php endif; ?>
            </nav>
        </aside>
        <div class="mobile-sidebar-backdrop d-lg-none no-print" data-mobile-menu-close></div>

        <main class="content flex-grow-1">
            <header class="bg-white border-bottom px-3 px-lg-4 py-3 d-flex align-items-center justify-content-between no-print">
                <div class="d-flex align-items-center gap-2 min-w-0">
                    <button class="btn btn-outline-secondary btn-sm d-lg-none mobile-menu-toggle" type="button" data-mobile-menu-toggle aria-label="Open menu">
                        <i class="bi bi-list"></i>
                    </button>
                    <div class="min-w-0">
                        <h1 class="h4 mb-0 text-truncate"><?php echo $__env->yieldContent('page-title', 'Dashboard'); ?></h1>
                        <small class="text-muted d-block text-truncate"><?php echo $__env->yieldContent('page-subtitle'); ?></small>
                    </div>
                </div>
                <div class="d-flex align-items-center gap-2">
                    <button class="btn btn-primary btn-sm pwa-install-button" type="button" data-pwa-install>
                        <i class="bi bi-phone me-1"></i> <span data-pwa-install-label>Install app</span>
                    </button>
                    <form method="POST" action="<?php echo e(route('logout')); ?>">
                        <?php echo csrf_field(); ?>
                        <button class="btn btn-outline-secondary btn-sm"><i class="bi bi-box-arrow-right me-1"></i> <span class="d-none d-sm-inline">Sign out</span></button>
                    </form>
                </div>
            </header>

            <div class="p-3 p-lg-4">
                <?php if(session('impersonating_super_admin_id')): ?>
                    <div class="alert alert-dark border-0 shadow-sm d-flex flex-column flex-md-row justify-content-between gap-2 align-items-md-center no-print">
                        <div>
                            <strong>Super admin view:</strong>
                            You are inside <?php echo e(session('impersonating_tenant_name', $tenant?->name)); ?>.
                        </div>
                        <form method="POST" action="<?php echo e(route('impersonation.stop')); ?>">
                            <?php echo csrf_field(); ?>
                            <button class="btn btn-light btn-sm"><i class="bi bi-arrow-left-circle me-1"></i> Return to super admin</button>
                        </form>
                    </div>
                <?php endif; ?>
                <?php if(session('status')): ?>
                    <div class="alert alert-success"><?php echo e(session('status')); ?></div>
                <?php endif; ?>
                <?php if(session('warning')): ?>
                    <div class="alert alert-warning"><?php echo e(session('warning')); ?></div>
                <?php endif; ?>
                <?php if($errors->any()): ?>
                    <div class="alert alert-danger">
                        <div class="fw-semibold">Please check the highlighted fields.</div>
                        <ul class="mb-0">
                            <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <li><?php echo e($error); ?></li>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </ul>
                    </div>
                <?php endif; ?>
                <?php if($tenant && ! $user->isSuperAdmin() && $user->role !== 'customer'): ?>
                    <?php echo $__env->make('partials.trial-countdown', ['tenant' => $tenant], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                <?php endif; ?>
                <?php echo $__env->yieldContent('content'); ?>
            </div>
        </main>

        <nav class="mobile-bottom-nav d-lg-none no-print" aria-label="Mobile app navigation">
            <?php if($user->isSuperAdmin()): ?>
                <a href="<?php echo e(route('super.dashboard')); ?>" class="<?php echo \Illuminate\Support\Arr::toCssClasses(['active' => request()->routeIs('super.dashboard')]); ?>"><i class="bi bi-speedometer2"></i><span>Home</span></a>
                <a href="<?php echo e(route('super.tenants.index')); ?>" class="<?php echo \Illuminate\Support\Arr::toCssClasses(['active' => request()->routeIs('super.tenants.*')]); ?>"><i class="bi bi-buildings"></i><span>Tenants</span></a>
                <a href="<?php echo e(route('super.agents.index')); ?>" class="<?php echo \Illuminate\Support\Arr::toCssClasses(['active' => request()->routeIs('super.agents.*')]); ?>"><i class="bi bi-person-badge"></i><span>Merchants</span></a>
                <a href="<?php echo e(route('super.billing.index')); ?>" class="<?php echo \Illuminate\Support\Arr::toCssClasses(['active' => request()->routeIs('super.billing.*')]); ?>"><i class="bi bi-receipt"></i><span>Billing</span></a>
                <button type="button" data-mobile-menu-toggle><i class="bi bi-grid"></i><span>Menu</span></button>
            <?php elseif($user->role === \App\Models\User::ROLE_AGENT): ?>
                <a href="<?php echo e(route('merchant.dashboard')); ?>" class="<?php echo \Illuminate\Support\Arr::toCssClasses(['active' => request()->routeIs('merchant.dashboard') || request()->routeIs('agent.dashboard')]); ?>"><i class="bi bi-speedometer2"></i><span>Home</span></a>
                <?php if($agentProfile?->isActive()): ?>
                    <a href="<?php echo e($agentProfile->referralUrl()); ?>"><i class="bi bi-globe2"></i><span>Landing</span></a>
                    <?php if($agentProfile->canOnboard()): ?>
                        <a href="<?php echo e($agentProfile->tenantSignupUrl()); ?>"><i class="bi bi-building-add"></i><span>Onboard</span></a>
                    <?php endif; ?>
                    <?php if($agentProfile->canRefer()): ?>
                        <a href="<?php echo e($agentProfile->referralSignupUrl()); ?>"><i class="bi bi-link-45deg"></i><span>Refer</span></a>
                    <?php endif; ?>
                <?php endif; ?>
                <button type="button" data-mobile-menu-toggle><i class="bi bi-grid"></i><span>Menu</span></button>
            <?php elseif($user->role === 'customer'): ?>
                <a href="<?php echo e(route('member.dashboard')); ?>" class="<?php echo \Illuminate\Support\Arr::toCssClasses(['active' => request()->routeIs('member.dashboard')]); ?>"><i class="bi bi-speedometer2"></i><span>Home</span></a>
                <a href="<?php echo e(route('member.dashboard')); ?>#savings"><i class="bi bi-wallet2"></i><span>Savings</span></a>
                <a href="<?php echo e(route('member.dashboard')); ?>#transfers"><i class="bi bi-arrow-left-right"></i><span>Transfer</span></a>
                <a href="<?php echo e(route('member.dashboard')); ?>#loans"><i class="bi bi-cash-coin"></i><span>Loans</span></a>
                <a href="<?php echo e(route('member.dashboard')); ?>#member-bills"><i class="bi bi-phone"></i><span>Bills</span></a>
                <button type="button" data-mobile-menu-toggle><i class="bi bi-grid"></i><span>Menu</span></button>
            <?php else: ?>
                <a href="<?php echo e(route('tenant.dashboard')); ?>" class="<?php echo \Illuminate\Support\Arr::toCssClasses(['active' => request()->routeIs('tenant.dashboard')]); ?>"><i class="bi bi-speedometer2"></i><span>Home</span></a>
                <?php if($user->hasPermission('customers.view')): ?>
                    <a href="<?php echo e(route('tenant.customers.index')); ?>" class="<?php echo \Illuminate\Support\Arr::toCssClasses(['active' => request()->routeIs('tenant.customers.*')]); ?>"><i class="bi bi-people"></i><span>Members</span></a>
                <?php endif; ?>
                <?php if($user->hasPermission('loans.view')): ?>
                    <a href="<?php echo e(route('tenant.loans.index')); ?>" class="<?php echo \Illuminate\Support\Arr::toCssClasses(['active' => request()->routeIs('tenant.loans.*')]); ?>"><i class="bi bi-cash-coin"></i><span>Loans</span></a>
                <?php elseif($user->hasPermission('savings.view')): ?>
                    <a href="<?php echo e(route('tenant.savings.index')); ?>" class="<?php echo \Illuminate\Support\Arr::toCssClasses(['active' => request()->routeIs('tenant.savings.*')]); ?>"><i class="bi bi-wallet2"></i><span>Savings</span></a>
                <?php endif; ?>
                <?php if($user->hasPermission('reports.view')): ?>
                    <a href="<?php echo e(route('tenant.reports.index')); ?>" class="<?php echo \Illuminate\Support\Arr::toCssClasses(['active' => request()->routeIs('tenant.reports.*')]); ?>"><i class="bi bi-graph-up-arrow"></i><span>Reports</span></a>
                <?php endif; ?>
                <button type="button" data-mobile-menu-toggle><i class="bi bi-grid"></i><span>Menu</span></button>
            <?php endif; ?>
        </nav>
    </div>
<?php else: ?>
    <?php echo $__env->yieldContent('guest'); ?>
<?php endif; ?>
<?php if(auth()->guard()->guest()): ?>
    <?php if (! (request()->routeIs('landing'))): ?>
    <button class="pwa-install-fab pwa-install-button no-print" type="button" data-pwa-install>
        <i class="bi bi-phone"></i>
        <span data-pwa-install-label>Install app</span>
    </button>
    <?php endif; ?>
<?php endif; ?>
<div class="pwa-offline-badge no-print" data-pwa-offline hidden>
    <i class="bi bi-wifi-off me-1"></i> Offline mode
</div>
<div class="modal fade pwa-install-modal no-print" id="pwaInstallModal" tabindex="-1" aria-labelledby="pwaInstallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-0">
                <div>
                    <span class="site-eyebrow dark">Mobile app</span>
                    <h2 class="modal-title h5" id="pwaInstallModalLabel">Install NewKipp Microfinance Solution</h2>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body pt-0">
                <div class="pwa-install-summary">
                    <i class="bi bi-phone"></i>
                    <div>
                        <strong data-pwa-platform>Your browser</strong>
                        <span data-pwa-status>Follow the steps below to install the app.</span>
                    </div>
                </div>
                <ol class="pwa-install-steps" data-pwa-instructions>
                    <li>Open this website in your browser.</li>
                    <li>Use the browser menu and choose Install app or Add to Home Screen.</li>
                    <li>Open NewKipp Microfinance Solution from your home screen.</li>
                </ol>
                <div class="pwa-install-note" data-pwa-note>
                    The mobile app works best when the site is hosted with HTTPS.
                </div>
            </div>
            <div class="modal-footer border-0">
                <a href="<?php echo e(route('mobile-app')); ?>" class="btn btn-outline-primary" data-pwa-guide-link>Full guide</a>
                <button type="button" class="btn btn-primary" data-pwa-install-direct>
                    <i class="bi bi-download me-1"></i> Install now
                </button>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="<?php echo e(asset('js/pwa.js')); ?>?v=<?php echo e(@filemtime(public_path('js/pwa.js')) ?: '1'); ?>"></script>
<?php echo $__env->yieldPushContent('scripts'); ?>
<script>
document.querySelectorAll('[data-trial-countdown]').forEach((element) => {
    const end = new Date(element.dataset.trialCountdown).getTime();
    const update = () => {
        const seconds = Math.max(0, Math.floor((end - Date.now()) / 1000));
        const parts = {
            days: Math.floor(seconds / 86400),
            hours: Math.floor((seconds % 86400) / 3600),
            minutes: Math.floor((seconds % 3600) / 60),
            seconds: seconds % 60,
        };
        Object.entries(parts).forEach(([key, value]) => {
            const target = element.querySelector(`[data-${key}]`);
            if (target) target.textContent = String(value).padStart(key === 'days' ? 1 : 2, '0');
        });
    };
    update();
    setInterval(update, 1000);
});
</script>
<?php if(auth()->guard()->check()): ?>
    <?php
        $layoutSyncSettings = $tenant?->settings ?? [];
        $layoutAutoSyncEnabled = (bool) ($layoutSyncSettings['sync_auto_enabled'] ?? false);
        $layoutAutoSyncInterval = max(5, (int) ($layoutSyncSettings['sync_auto_interval'] ?? 15));
        $layoutCanAutoSync = $tenant
            && ! $user->isSuperAdmin()
            && in_array($user->role, [\App\Models\User::ROLE_TENANT_ADMIN, \App\Models\User::ROLE_MANAGER], true)
            && $user->hasPermission('data_imports.manage')
            && $layoutAutoSyncEnabled
            && filled($layoutSyncSettings['sync_remote_url'] ?? null)
            && filled($layoutSyncSettings['sync_remote_token'] ?? null);
    ?>
    <?php if($layoutCanAutoSync): ?>
        <script>
        (() => {
            const endpoint = <?php echo json_encode(route('tenant.sync.run'), 15, 512) ?>;
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
            const intervalMs = <?php echo e($layoutAutoSyncInterval); ?> * 60 * 1000;
            const tenantId = <?php echo json_encode((string) $tenant->id, 15, 512) ?>;
            const lockKey = `mfi-auto-sync-lock:${tenantId}`;
            const lastRunKey = `mfi-auto-sync-last:${tenantId}`;
            const lockTtl = Math.min(intervalMs, 4 * 60 * 1000);
            let timerId = null;

            const canRun = () => document.visibilityState === 'visible' && (!('onLine' in navigator) || navigator.onLine);

            const runSync = async () => {
                if (! csrfToken || ! canRun()) return;

                const lockAge = Date.now() - Number(localStorage.getItem(lockKey) || 0);
                if (lockAge >= 0 && lockAge < lockTtl) return;

                localStorage.setItem(lockKey, String(Date.now()));

                try {
                    const response = await fetch(endpoint, {
                        method: 'POST',
                        headers: {
                            'Accept': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': csrfToken,
                        },
                        credentials: 'same-origin',
                    });
                    const data = await response.json().catch(() => ({}));

                    localStorage.setItem(lastRunKey, String(Date.now()));

                    window.dispatchEvent(new CustomEvent('tenant:auto-sync', {
                        detail: {
                            ok: response.ok && data.ok !== false,
                            message: data.message || 'Automatic sync completed.',
                        },
                    }));
                } catch (error) {
                    localStorage.setItem(lastRunKey, String(Date.now()));
                    window.dispatchEvent(new CustomEvent('tenant:auto-sync', {
                        detail: {
                            ok: false,
                            message: 'Automatic sync could not reach the remote server.',
                        },
                    }));
                } finally {
                    localStorage.removeItem(lockKey);
                }
            };

            const scheduleSync = () => {
                clearTimeout(timerId);

                const lastRunAt = Number(localStorage.getItem(lastRunKey) || 0);
                const waitMs = Math.max(30000, intervalMs - (Date.now() - lastRunAt));

                timerId = setTimeout(async () => {
                    await runSync();
                    scheduleSync();
                }, waitMs);
            };

            document.addEventListener('visibilitychange', () => {
                if (document.visibilityState === 'visible') scheduleSync();
            });
            window.addEventListener('online', scheduleSync);
            scheduleSync();
        })();
        </script>
    <?php endif; ?>
<?php endif; ?>
</body>
</html>
<?php /**PATH C:\Users\Polite hp\Documents\Codex\2026-05-08\build-a-complete-production-ready-saas\microfinance-saas\resources\views/layouts/app.blade.php ENDPATH**/ ?>