@extends('layouts.app')

@section('title', 'Expenses')
@section('page-title', 'Expenses')
@section('page-subtitle', 'Expense dashboard, approvals, categories, and operating cost reports')

@section('content')
@php
    $canCreateExpenses = auth()->user()->hasPermission('expenses.create');
    $canApproveExpenses = auth()->user()->hasPermission('expenses.approve');
    $currency = auth()->user()->tenant->settings['currency'] ?? 'NGN';
    $money = fn ($amount) => $currency.' '.number_format((float) $amount, 2);
    $compactNumber = function ($amount) {
        $amount = (float) $amount;
        $absolute = abs($amount);
        $format = fn ($value, $suffix) => rtrim(rtrim(number_format($value, 1), '0'), '.').$suffix;

        if ($absolute >= 1000000000) return $format($amount / 1000000000, 'b');
        if ($absolute >= 1000000) return $format($amount / 1000000, 'm');
        if ($absolute >= 1000) return $format($amount / 1000, 'k');

        return number_format($amount, 2);
    };
    $compactMoney = fn ($amount) => $currency.' '.$compactNumber($amount);
    $statusLabel = fn ($value) => ucfirst(str_replace('_', ' ', (string) $value));
    $statusClass = fn ($value) => match ($value) {
        'approved' => 'text-bg-success',
        'pending' => 'text-bg-warning',
        'rejected' => 'text-bg-danger',
        'canceled' => 'text-bg-secondary',
        default => 'text-bg-secondary',
    };
    $chartColors = ['#0f766e', '#2563eb', '#f59e0b', '#e11d48', '#7c3aed', '#16a34a', '#0891b2', '#ea580c', '#475569', '#db2777'];
    $conicGradient = function ($rows) use ($chartColors) {
        $rows = collect($rows)->filter(fn ($row) => (float) ($row['total'] ?? 0) > 0)->values();
        $total = (float) $rows->sum('total');

        if ($rows->isEmpty() || $total <= 0) {
            return 'conic-gradient(#e5e7eb 0 100%)';
        }

        $cursor = 0.0;
        $segments = [];

        foreach ($rows as $index => $row) {
            $start = $cursor;
            $cursor += ((float) $row['total'] / $total) * 100;
            $segments[] = $chartColors[$index % count($chartColors)].' '.round($start, 2).'% '.round($cursor, 2).'%';
        }

        return 'conic-gradient('.implode(', ', $segments).')';
    };
    $monthlyMax = max(1, (float) collect($expenseCharts['monthly'])->max('total'));
    $branchMax = max(1, (float) collect($expenseCharts['branch'])->max('total'));
    $trendMax = max(1, (float) collect($expenseCharts['trend'])->max('total'));
    $showBranchField = $showBranchField ?? $branches->count() > 1;
    $selectedExpenseBranchId = old('branch_id', $defaultBranchId ?? null);
    $trendCount = max(1, collect($expenseCharts['trend'])->count() - 1);
    $trendPoints = collect($expenseCharts['trend'])
        ->values()
        ->map(fn ($row, $index) => round(($index / $trendCount) * 100, 2).','.round(95 - (((float) $row['total'] / $trendMax) * 85), 2))
        ->implode(' ');
    $expenseMetricCards = [
        ["Today Expense", $compactMoney($expenseStats['today_total'] ?? 0), number_format($expenseStats['today_count'] ?? 0).' approved today', 'bi-calendar2-day', 'blue'],
        ['Month Expense', $compactMoney($expenseStats['month_total'] ?? 0), ($expenseStats['monthly_trend_percent'] ?? 0) >= 0 ? '+'.number_format($expenseStats['monthly_trend_percent'] ?? 0, 1).'% vs last month' : number_format($expenseStats['monthly_trend_percent'] ?? 0, 1).'% vs last month', 'bi-cash-stack', 'teal'],
        ['Pending Expense', $compactMoney($expenseStats['pending_amount'] ?? 0), number_format($expenseStats['pending'] ?? 0).' request'.(($expenseStats['pending'] ?? 0) == 1 ? '' : 's').' waiting', 'bi-hourglass-split', 'amber'],
        ['Recurring Expense', $compactMoney($expenseStats['recurring_month_total'] ?? 0), number_format($expenseStats['recurring_month_count'] ?? 0).' recurring this month', 'bi-arrow-repeat', 'purple'],
    ];
@endphp

@if($errors->any())
    <div class="alert alert-warning border-0">{{ $errors->first() }}</div>
@endif

<section class="expense-hero mb-4">
    <div class="expense-hero-copy">
        <span>Expense center</span>
        <h2>See spending clearly before it affects your cash position.</h2>
        <p>Use the tabs below to move between dashboard insight, expense capture, approvals, history, and category setup without crowding one screen.</p>
    </div>
    <div class="expense-metric-grid">
        @foreach($expenseMetricCards as [$label, $value, $hint, $icon, $tone])
            <div class="expense-metric {{ $tone }}">
                <i class="bi {{ $icon }}"></i>
                <span>{{ $label }}</span>
                <strong>{{ $value }}</strong>
                <small>{{ $hint }}</small>
            </div>
        @endforeach
    </div>
</section>

<div class="expense-tab-workspace">
    <div class="expense-tabbar">
        <ul class="nav nav-pills expense-tabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#expense-overview" type="button" role="tab">
                    <i class="bi bi-grid-1x2 me-1"></i> Overview
                </button>
            </li>
            @if($canCreateExpenses)
                <li class="nav-item" role="presentation">
                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#expense-record" type="button" role="tab">
                        <i class="bi bi-plus-circle me-1"></i> Record Expense
                    </button>
                </li>
            @endif
            @if($canApproveExpenses)
                <li class="nav-item" role="presentation">
                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#expense-approvals" type="button" role="tab">
                        <i class="bi bi-check2-circle me-1"></i> Approvals
                        @if(($expenseStats['pending'] ?? 0) > 0)
                            <span class="badge text-bg-warning ms-1">{{ number_format($expenseStats['pending']) }}</span>
                        @endif
                    </button>
                </li>
            @endif
            <li class="nav-item" role="presentation">
                <button class="nav-link" data-bs-toggle="tab" data-bs-target="#expense-history" type="button" role="tab">
                    <i class="bi bi-clock-history me-1"></i> History
                </button>
            </li>
            @if($canCreateExpenses)
                <li class="nav-item" role="presentation">
                    <button class="nav-link" data-bs-toggle="tab" data-bs-target="#expense-categories" type="button" role="tab">
                        <i class="bi bi-tags me-1"></i> Categories
                    </button>
                </li>
            @endif
        </ul>
    </div>

    <div class="tab-content">
        <div class="tab-pane fade show active" id="expense-overview" role="tabpanel" tabindex="0">
            <div class="expense-tab-pane">
                <div class="expense-pane-title">
                    <div>
                        <span>Dashboard</span>
                        <h3>Expense overview</h3>
                        <p>Charts for approved expenses in the selected reporting period.</p>
                    </div>
                </div>

                <section class="expense-chart-grid">
                    <div class="expense-chart-card">
                        <div class="expense-card-title">
                            <div><span>Pie Chart</span><h3>Expenses by Category</h3></div>
                        </div>
                        <div class="expense-pie-wrap">
                            <div class="expense-pie" style="background: {{ $conicGradient($expenseCharts['category']) }}"></div>
                            <div class="expense-chart-legend">
                                @forelse($expenseCharts['category'] as $index => $row)
                                    <div><i style="background: {{ $chartColors[$index % count($chartColors)] }}"></i><span>{{ $row['label'] }}</span><strong>{{ $compactMoney($row['total']) }}</strong></div>
                                @empty
                                    <p>No approved expenses in this period.</p>
                                @endforelse
                            </div>
                        </div>
                    </div>

                    <div class="expense-chart-card">
                        <div class="expense-card-title">
                            <div><span>Bar Chart</span><h3>Monthly Expenses Comparison</h3></div>
                        </div>
                        <div class="expense-bars">
                            @foreach($expenseCharts['monthly'] as $row)
                                @php($height = max(6, round(((float) $row['total'] / $monthlyMax) * 100)))
                                <div class="expense-bar-item">
                                    <div class="expense-bar" title="{{ $money($row['total']) }}"><span style="height: {{ $height }}%"></span></div>
                                    <strong>{{ $row['label'] }}</strong>
                                    <small>{{ $compactMoney($row['total']) }}</small>
                                </div>
                            @endforeach
                        </div>
                    </div>

                    <div class="expense-chart-card">
                        <div class="expense-card-title">
                            <div><span>Line Chart</span><h3>Expense Trend Over Time</h3></div>
                        </div>
                        <div class="expense-line-chart">
                            <svg viewBox="0 0 100 100" preserveAspectRatio="none" role="img" aria-label="Expense trend over time">
                                <polyline points="{{ $trendPoints }}" fill="none" stroke="#0f766e" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"></polyline>
                                <polygon points="0,100 {{ $trendPoints }} 100,100" fill="rgba(15,118,110,.12)"></polygon>
                            </svg>
                            <div class="expense-trend-labels">
                                <span>{{ collect($expenseCharts['trend'])->first()['label'] ?? '' }}</span>
                                <strong>14 day trend</strong>
                                <span>{{ collect($expenseCharts['trend'])->last()['label'] ?? '' }}</span>
                            </div>
                        </div>
                    </div>

                    <div class="expense-chart-card">
                        <div class="expense-card-title">
                            <div><span>Donut Chart</span><h3>Cash vs Bank Spending</h3></div>
                        </div>
                        <div class="expense-donut-wrap">
                            <div class="expense-donut" style="background: {{ $conicGradient($expenseCharts['cash_bank']) }}"></div>
                            <div class="expense-chart-legend compact">
                                @forelse($expenseCharts['cash_bank'] as $index => $row)
                                    <div><i style="background: {{ $chartColors[$index % count($chartColors)] }}"></i><span>{{ $row['label'] }}</span><strong>{{ $compactMoney($row['total']) }}</strong></div>
                                @empty
                                    <p>No payment method data yet.</p>
                                @endforelse
                            </div>
                        </div>
                    </div>

                    <div class="expense-chart-card expense-branch-card">
                        <div class="expense-card-title">
                            <div><span>Branch Chart</span><h3>Expenses by Branch</h3></div>
                        </div>
                        <div class="expense-branch-bars">
                            @forelse($expenseCharts['branch'] as $row)
                                @php($width = max(4, round(((float) $row['total'] / $branchMax) * 100)))
                                <div class="expense-branch-row">
                                    <div>
                                        <strong>{{ $row['label'] }}</strong>
                                        <small>{{ number_format($row['count']) }} record{{ $row['count'] == 1 ? '' : 's' }}</small>
                                    </div>
                                    <div class="expense-branch-track"><span style="width: {{ $width }}%"></span></div>
                                    <b>{{ $compactMoney($row['total']) }}</b>
                                </div>
                            @empty
                                <div class="expense-empty-mini">No branch expense data for this period.</div>
                            @endforelse
                        </div>
                    </div>
                </section>
            </div>
        </div>

        @if($canCreateExpenses)
            <div class="tab-pane fade" id="expense-record" role="tabpanel" tabindex="0">
                <div class="expense-tab-pane">
                    <div class="expense-pane-title">
                        <div>
                            <span>Capture</span>
                            <h3>Record expense</h3>
                            <p>Submit a new expense request for approval and accounting posting.</p>
                        </div>
                    </div>
                    @if($activeCategories->isEmpty())
                        <div class="alert alert-warning border-0">Create at least one active expense category before recording expenses.</div>
                    @endif
                    <form method="POST" action="{{ route('tenant.expenses.store') }}" class="row g-3 finance-form-panel expense-form-grid">
                        @csrf
                        <div class="col-lg-4 col-md-6">
                            <label class="form-label">Expense category</label>
                            <select name="expense_category_id" class="form-select" required @disabled($activeCategories->isEmpty())>
                                <option value="">Select category</option>
                                @foreach($activeCategories as $category)
                                    <option value="{{ $category->id }}" @selected(old('expense_category_id') == $category->id)>{{ $category->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        @if($supportsExpenseBranches && $showBranchField)
                            <div class="col-lg-4 col-md-6">
                                <label class="form-label">Branch</label>
                                <select name="branch_id" class="form-select" required>
                                    @foreach($branches as $branch)
                                        <option value="{{ $branch->id }}" @selected((string) $selectedExpenseBranchId === (string) $branch->id)>{{ $branch->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                        @elseif($supportsExpenseBranches)
                            <input type="hidden" name="branch_id" value="{{ $selectedExpenseBranchId }}">
                        @endif
                        <div class="col-lg-4 col-md-6">
                            <label class="form-label">Amount</label>
                            <input name="amount" type="number" step="0.01" min="0.01" value="{{ old('amount') }}" class="form-control" placeholder="0.00" required>
                        </div>
                        <div class="col-lg-4 col-md-6">
                            <label class="form-label">Date spent</label>
                            <input name="spent_at" type="date" value="{{ old('spent_at', now()->format('Y-m-d')) }}" class="form-control" required>
                        </div>
                        <div class="col-lg-4 col-md-6">
                            <label class="form-label">Payee</label>
                            <input name="payee" value="{{ old('payee') }}" class="form-control" placeholder="Vendor or staff">
                        </div>
                        <div class="col-lg-4 col-md-6">
                            <label class="form-label">Payment method</label>
                            <select name="method" class="form-select">
                                @foreach(['cash' => 'Cash', 'transfer' => 'Bank transfer', 'pos' => 'POS', 'cheque' => 'Cheque'] as $value => $label)
                                    <option value="{{ $value }}" @selected(old('method', 'cash') === $value)>{{ $label }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-lg-4 col-md-6">
                            <label class="form-label">Approval level</label>
                            <select name="approval_level_required" class="form-select" required>
                                @foreach([1 => 'Level 1 - one approval', 2 => 'Level 2 - two approvals', 3 => 'Level 3 - three approvals'] as $level => $label)
                                    <option value="{{ $level }}" @selected((int) old('approval_level_required', 1) === $level)>{{ $label }}</option>
                                @endforeach
                            </select>
                            <div class="form-text">Posts after the final approval level.</div>
                        </div>
                        @if($supportsRecurringExpenses)
                            <div class="col-lg-4 col-md-6">
                                <label class="form-label">Recurring</label>
                                <div class="expense-recurring-box">
                                    <label class="form-check mb-0">
                                        <input class="form-check-input" name="is_recurring" value="1" type="checkbox" @checked(old('is_recurring'))>
                                        <span class="form-check-label">Mark as recurring</span>
                                    </label>
                                </div>
                            </div>
                            <div class="col-lg-4 col-md-6">
                                <label class="form-label">Frequency</label>
                                <select name="recurrence_frequency" class="form-select">
                                    @foreach(['daily' => 'Daily', 'weekly' => 'Weekly', 'monthly' => 'Monthly', 'quarterly' => 'Quarterly', 'yearly' => 'Yearly'] as $value => $label)
                                        <option value="{{ $value }}" @selected(old('recurrence_frequency', 'monthly') === $value)>{{ $label }}</option>
                                    @endforeach
                                </select>
                            </div>
                        @endif
                        <div class="col-lg-8">
                            <label class="form-label">Notes</label>
                            <textarea name="notes" class="form-control" rows="3" placeholder="Optional details">{{ old('notes') }}</textarea>
                        </div>
                        <div class="col-12">
                            <button class="btn btn-primary" @disabled($activeCategories->isEmpty())>
                                <i class="bi bi-plus-lg me-1"></i> Save expense
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        @endif

        @if($canApproveExpenses)
            <div class="tab-pane fade" id="expense-approvals" role="tabpanel" tabindex="0">
                <div class="expense-tab-pane">
                    <div class="expense-pane-title">
                        <div>
                            <span>Approval desk</span>
                            <h3>Pending expenses</h3>
                            <p>Approve or reject submitted expenses before they post to accounting.</p>
                        </div>
                    </div>
                    @if($pendingExpenses->isNotEmpty())
                        <div class="pending-expense-list">
                            @foreach($pendingExpenses as $pendingExpense)
                                <div class="pending-expense-item">
                                    <div>
                                        <span class="finance-id-pill">{{ $pendingExpense->reference }}</span>
                                        <strong>{{ $pendingExpense->category }} - {{ $money($pendingExpense->amount) }}</strong>
                                        <small>
                                            {{ $pendingExpense->approvalProgressLabel() }} - Submitted by {{ $pendingExpense->recordedBy?->name ?? 'Unknown user' }}
                                            @if($pendingExpense->payee)
                                                - Payee: {{ $pendingExpense->payee }}
                                            @endif
                                        </small>
                                    </div>
                                    <div class="pending-expense-actions">
                                        <div class="dropdown">
                                            <button class="btn btn-sm btn-outline-primary dropdown-toggle w-100" type="button" data-bs-toggle="dropdown" aria-expanded="false">Actions</button>
                                            <ul class="dropdown-menu dropdown-menu-end">
                                                <li>
                                                    <form method="POST" action="{{ route('tenant.expenses.approve', $pendingExpense) }}">
                                                        @csrf
                                                        <button class="dropdown-item text-success" type="submit"><i class="bi bi-check2-circle me-2"></i>Approve level {{ $pendingExpense->nextApprovalLevel() }}</button>
                                                    </form>
                                                </li>
                                                <li><button class="dropdown-item text-danger" type="button" data-bs-toggle="collapse" data-bs-target="#pendingExpenseReject{{ $pendingExpense->id }}"><i class="bi bi-x-circle me-2"></i>Reject</button></li>
                                            </ul>
                                        </div>
                                        <form method="POST" action="{{ route('tenant.expenses.reject', $pendingExpense) }}" class="collapse d-flex gap-1" id="pendingExpenseReject{{ $pendingExpense->id }}">
                                            @csrf
                                            <input name="rejected_reason" class="form-control form-control-sm" placeholder="Reason" required>
                                            <button class="btn btn-sm btn-danger">Submit</button>
                                        </form>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @else
                        <div class="expense-empty-state">
                            <i class="bi bi-check2-circle"></i>
                            <h4>No pending expenses</h4>
                            <p>New expense requests will appear here when staff submit them.</p>
                        </div>
                    @endif
                </div>
            </div>
        @endif

        <div class="tab-pane fade" id="expense-history" role="tabpanel" tabindex="0">
            <div class="expense-tab-pane">
                <div class="expense-pane-title">
                    <div>
                        <span>Report</span>
                        <h3>Expense history</h3>
                        <p>Filter by category, branch, payee, reference, method, status, and date range.</p>
                    </div>
                </div>
                <form method="GET" class="row g-2 align-items-end finance-filter-panel mb-3">
                    <div class="col-lg-2">
                        <label class="form-label">Search</label>
                        <input name="search" value="{{ $search }}" class="form-control" placeholder="Payee, reference">
                    </div>
                    <div class="col-lg-2">
                        <label class="form-label">Category</label>
                        <select name="category_id" class="form-select">
                            <option value="">All categories</option>
                            @foreach($categories as $category)
                                <option value="{{ $category->id }}" @selected((string) $categoryId === (string) $category->id)>{{ $category->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    @if($supportsExpenseBranches && $showBranchField)
                        <div class="col-lg-2">
                            <label class="form-label">Branch</label>
                            <select name="branch_id" class="form-select">
                                <option value="">All branches</option>
                                @foreach($branches as $branch)
                                    <option value="{{ $branch->id }}" @selected((string) $branchId === (string) $branch->id)>{{ $branch->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    @endif
                    <div class="col-lg-2">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All status</option>
                            @foreach(['pending' => 'Pending', 'approved' => 'Approved', 'rejected' => 'Rejected', 'canceled' => 'Canceled'] as $value => $label)
                                <option value="{{ $value }}" @selected(($status ?? '') === $value)>{{ $label }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3 col-lg-2">
                        <label class="form-label">From</label>
                        <input name="from" type="date" value="{{ $from->format('Y-m-d') }}" class="form-control">
                    </div>
                    <div class="col-md-3 col-lg-2">
                        <label class="form-label">To</label>
                        <input name="to" type="date" value="{{ $to->format('Y-m-d') }}" class="form-control">
                    </div>
                    <div class="col-md-6 col-lg-1 d-grid">
                        <button class="btn btn-outline-primary"><i class="bi bi-funnel me-1"></i> Filter</button>
                    </div>
                </form>
                <div class="table-responsive finance-table-shell">
                    <table class="table mb-0 align-middle finance-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Reference</th>
                                <th>Category</th>
                                @if($supportsExpenseBranches && $showBranchField)<th>Branch</th>@endif
                                <th>Payee</th>
                                <th>Status</th>
                                <th>Approval</th>
                                <th>Initiated by</th>
                                <th>Approved by</th>
                                <th class="text-end">Amount</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                        @forelse($expenses as $expense)
                            <tr>
                                <td>{{ app_date($expense->spent_at) }}</td>
                                <td><span class="finance-id-pill">{{ $expense->reference }}</span></td>
                                <td><span class="finance-soft-badge">{{ $expense->category }}</span></td>
                                @if($supportsExpenseBranches && $showBranchField)<td>{{ $expense->branch?->name ?? 'Head Office' }}</td>@endif
                                <td>{{ $expense->payee ?: '-' }}</td>
                                <td><span class="badge {{ $statusClass($expense->status) }}">{{ $statusLabel($expense->status) }}</span></td>
                                <td>{{ $expense->approvalProgressLabel() }}</td>
                                <td>{{ $expense->recordedBy?->name ?? 'Unknown user' }}</td>
                                <td>
                                    @if($expense->status === 'canceled')
                                        {{ $expense->canceledBy?->name ?? 'Canceled' }}
                                    @else
                                        {{ $expense->approvedBy?->name ?? ($expense->status === 'pending' ? 'Not approved yet' : '-') }}
                                    @endif
                                </td>
                                <td class="text-end fw-semibold">{{ $money($expense->amount) }}</td>
                                <td class="text-end">
                                    <div class="dropdown">
                                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Actions</button>
                                        <ul class="dropdown-menu dropdown-menu-end">
                                            @if($canApproveExpenses && $expense->status === 'pending')
                                                <li>
                                                    <form method="POST" action="{{ route('tenant.expenses.approve', $expense) }}">
                                                        @csrf
                                                        <button class="dropdown-item text-success" type="submit"><i class="bi bi-check2-circle me-2"></i>Approve</button>
                                                    </form>
                                                </li>
                                                <li><button class="dropdown-item text-danger" type="button" data-bs-toggle="collapse" data-bs-target="#expenseReject{{ $expense->id }}"><i class="bi bi-x-circle me-2"></i>Reject</button></li>
                                            @elseif($canApproveExpenses && $expense->status === 'approved')
                                                <li><button class="dropdown-item text-danger" type="button" data-bs-toggle="modal" data-bs-target="#cancelExpense{{ $expense->id }}"><i class="bi bi-slash-circle me-2"></i>Cancel</button></li>
                                            @else
                                                <li><span class="dropdown-item-text text-muted small">{{ ucfirst(str_replace('_', ' ', $expense->method)) }}</span></li>
                                            @endif
                                        </ul>
                                    </div>
                                    @if($canApproveExpenses && $expense->status === 'pending')
                                        <form method="POST" action="{{ route('tenant.expenses.reject', $expense) }}" class="collapse mt-2 expense-reject-inline" id="expenseReject{{ $expense->id }}">
                                            @csrf
                                            <input name="rejected_reason" class="form-control form-control-sm" placeholder="Reason for rejection" required>
                                            <button class="btn btn-sm btn-danger">Submit</button>
                                        </form>
                                    @endif
                                </td>
                            </tr>
                        @empty
                            <tr><td colspan="{{ $supportsExpenseBranches && $showBranchField ? 11 : 10 }}" class="text-center text-muted py-5">No expenses found for this period.</td></tr>
                        @endforelse
                        </tbody>
                    </table>
                </div>
                @if($canApproveExpenses)
                    @foreach($expenses->getCollection()->where('status', 'approved') as $expense)
                        <div class="modal fade" id="cancelExpense{{ $expense->id }}" tabindex="-1" aria-labelledby="cancelExpense{{ $expense->id }}Label" aria-hidden="true">
                            <div class="modal-dialog modal-dialog-centered">
                                <div class="modal-content border-0 shadow">
                                    <form method="POST" action="{{ route('tenant.expenses.cancel', $expense) }}">
                                        @csrf
                                        <div class="modal-header">
                                            <div>
                                                <h2 class="modal-title h5" id="cancelExpense{{ $expense->id }}Label">Cancel expense</h2>
                                                <div class="text-muted small">{{ $expense->reference }} | {{ $expense->category }} | {{ $money($expense->amount) }}</div>
                                            </div>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <label class="form-label">Cancellation reason</label>
                                            <textarea name="canceled_reason" class="form-control" rows="3" required></textarea>
                                            <div class="form-text">The posted accounting entries for this expense will be reversed.</div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                                            <button class="btn btn-danger">Cancel expense</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    @endforeach
                @endif
                <div class="pt-3">{{ $expenses->links() }}</div>
            </div>
        </div>

        @if($canCreateExpenses)
            <div class="tab-pane fade" id="expense-categories" role="tabpanel" tabindex="0">
                <div class="expense-tab-pane">
                    <div class="expense-pane-title">
                        <div>
                            <span>Setup</span>
                            <h3>Expense categories</h3>
                            <p>Create more categories or edit the existing default categories.</p>
                        </div>
                    </div>
                    <div class="expense-category-layout">
                        <form method="POST" action="{{ route('tenant.expenses.categories.store') }}" class="finance-form-panel expense-category-create">
                            @csrf
                            <div class="mb-3">
                                <label class="form-label">Category name</label>
                                <input name="name" value="{{ old('name') }}" class="form-control" placeholder="e.g. Rent, Fuel, Office supplies" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Description</label>
                                <textarea name="description" class="form-control" rows="3" placeholder="Optional notes">{{ old('description') }}</textarea>
                            </div>
                            <label class="form-check mb-3">
                                <input class="form-check-input" name="is_active" value="1" type="checkbox" checked>
                                <span class="form-check-label">Active for new expenses</span>
                            </label>
                            <button class="btn btn-outline-primary"><i class="bi bi-tags me-1"></i> Create category</button>
                        </form>

                        <div class="expense-category-list">
                            @forelse($categories as $category)
                                <div class="expense-category-item">
                                    <button class="expense-category-summary" type="button" data-bs-toggle="collapse" data-bs-target="#expenseCategory{{ $category->id }}" aria-expanded="false">
                                        <span>{{ $category->name }}</span>
                                        <em>{{ $category->is_active ? 'Active' : 'Inactive' }}</em>
                                        <i class="bi bi-chevron-down"></i>
                                    </button>
                                    <form method="POST" action="{{ route('tenant.expenses.categories.update', $category) }}" class="collapse expense-category-edit" id="expenseCategory{{ $category->id }}">
                                        @csrf
                                        @method('PATCH')
                                        <label class="form-label">Name</label>
                                        <input name="name" class="form-control form-control-sm mb-2" value="{{ $category->name }}" required>
                                        <label class="form-label">Description</label>
                                        <textarea name="description" class="form-control form-control-sm mb-2" rows="2">{{ $category->description }}</textarea>
                                        <label class="form-check mb-2">
                                            <input class="form-check-input" name="is_active" value="1" type="checkbox" @checked($category->is_active)>
                                            <span class="form-check-label">Active</span>
                                        </label>
                                        <button class="btn btn-sm btn-primary">Update category</button>
                                    </form>
                                </div>
                            @empty
                                <div class="text-muted small">No categories yet.</div>
                            @endforelse
                        </div>
                    </div>
                </div>
            </div>
        @endif
    </div>
</div>

<style>
.expense-hero {
    display: grid;
    grid-template-columns: minmax(0, .78fr) minmax(0, 1.22fr);
    gap: 1rem;
    align-items: stretch;
    padding: clamp(1rem, 3vw, 1.4rem);
    border-radius: 8px;
    background:
        radial-gradient(circle at top right, rgba(251, 191, 36, .28), transparent 34%),
        linear-gradient(135deg, #7c2d12, #0f766e 56%, #172033);
    color: #fff;
    box-shadow: 0 18px 44px rgba(15, 23, 42, .16);
}
.expense-hero-copy {
    min-height: 230px;
    padding: .2rem .35rem;
    background: transparent;
    color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
}
.expense-hero-copy span,
.expense-card-title span,
.expense-pane-title span {
    text-transform: uppercase;
    letter-spacing: .08em;
    font-size: .72rem;
    font-weight: 800;
}
.expense-hero-copy h2 {
    max-width: 760px;
    margin: .4rem 0;
    font-weight: 800;
}
.expense-hero-copy p {
    margin: 0;
    max-width: 780px;
    color: rgba(255, 255, 255, .78);
}
.expense-tab-workspace {
    background: #fff;
    border: 1px solid #e5e7eb;
    border-radius: 16px;
    box-shadow: 0 14px 30px rgba(15, 23, 42, .08);
    overflow: hidden;
}
.expense-tabbar {
    padding: 1rem 1rem 0;
    border-bottom: 1px solid #eef2f7;
    overflow-x: auto;
}
.expense-tabs {
    flex-wrap: nowrap;
    gap: .5rem;
}
.expense-tabs .nav-link {
    white-space: nowrap;
    border-radius: 999px;
    color: #475569;
}
.expense-tabs .nav-link.active {
    background: #0f766e;
}
.expense-tab-pane {
    padding: 1.25rem;
}
.expense-pane-title {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    margin-bottom: 1rem;
}
.expense-pane-title span,
.expense-card-title span {
    color: #0f766e;
}
.expense-pane-title h3,
.expense-card-title h3 {
    margin: .2rem 0 0;
    font-size: 1.08rem;
    font-weight: 800;
}
.expense-pane-title p {
    margin: .25rem 0 0;
    color: #64748b;
}
.expense-metric-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: .85rem;
}
.expense-metric,
.expense-chart-card {
    border: 1px solid #e5e7eb;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 10px 24px rgba(15, 23, 42, .06);
}
.expense-metric {
    display: grid;
    gap: .25rem;
    min-height: 136px;
    padding: 1rem;
    border-color: rgba(255, 255, 255, .18);
    background: rgba(255, 255, 255, .13);
    box-shadow: none;
    backdrop-filter: blur(12px);
    min-width: 0;
}
.expense-metric i {
    width: auto;
    height: auto;
    margin-bottom: .15rem;
    color: #fed7aa;
    background: transparent !important;
    font-size: 1.35rem;
}
.expense-metric span,
.expense-metric small {
    display: block;
    color: rgba(255, 255, 255, .78);
    font-size: .8rem;
}
.expense-metric strong {
    display: block;
    color: #fff;
    font-size: clamp(1.25rem, 2.6vw, 1.8rem);
    line-height: 1.1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.expense-chart-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 1rem;
}
.expense-chart-card {
    padding: 1rem;
    min-height: 270px;
}
.expense-branch-card {
    grid-column: span 2;
    min-height: auto;
}
.expense-card-title {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    margin-bottom: 1rem;
}
.expense-pie-wrap,
.expense-donut-wrap {
    display: grid;
    grid-template-columns: auto minmax(0, 1fr);
    align-items: center;
    gap: 1rem;
}
.expense-pie,
.expense-donut {
    width: min(170px, 42vw);
    aspect-ratio: 1;
    border-radius: 50%;
    box-shadow: inset 0 0 0 1px rgba(15, 23, 42, .08);
}
.expense-donut {
    position: relative;
}
.expense-donut::after {
    content: "";
    position: absolute;
    inset: 28%;
    background: #fff;
    border-radius: 50%;
    box-shadow: inset 0 0 0 1px #e5e7eb;
}
.expense-chart-legend {
    display: grid;
    gap: .5rem;
    width: 100%;
}
.expense-chart-legend div {
    display: grid;
    grid-template-columns: auto minmax(0, 1fr) auto;
    gap: .5rem;
    align-items: center;
    font-size: .84rem;
}
.expense-chart-legend i {
    width: .75rem;
    height: .75rem;
    border-radius: 999px;
}
.expense-chart-legend span {
    color: #475569;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.expense-chart-legend strong {
    color: #0f172a;
}
.expense-chart-legend p,
.expense-empty-mini {
    color: #64748b;
    margin: 0;
}
.expense-bars {
    display: grid;
    grid-template-columns: repeat(6, minmax(0, 1fr));
    gap: .55rem;
    align-items: end;
    height: 215px;
}
.expense-bar-item {
    display: grid;
    grid-template-rows: minmax(130px, 1fr) auto auto;
    gap: .35rem;
    text-align: center;
    min-width: 0;
}
.expense-bar {
    display: flex;
    align-items: end;
    height: 100%;
    border-radius: 999px;
    background: #f1f5f9;
    overflow: hidden;
}
.expense-bar span {
    width: 100%;
    border-radius: 999px 999px 0 0;
    background: linear-gradient(180deg, #0f766e, #14b8a6);
}
.expense-bar-item strong,
.expense-bar-item small {
    font-size: .74rem;
    overflow: hidden;
    text-overflow: ellipsis;
}
.expense-bar-item small {
    color: #64748b;
}
.expense-line-chart {
    min-height: 215px;
    display: grid;
    align-content: stretch;
}
.expense-line-chart svg {
    width: 100%;
    height: 190px;
    border-radius: 14px;
    background: linear-gradient(180deg, #f8fafc, #fff);
    border: 1px solid #eef2f7;
}
.expense-trend-labels {
    display: flex;
    justify-content: space-between;
    color: #64748b;
    font-size: .8rem;
    margin-top: .5rem;
}
.expense-trend-labels strong {
    color: #0f172a;
}
.expense-branch-bars {
    display: grid;
    gap: .8rem;
}
.expense-branch-row {
    display: grid;
    grid-template-columns: minmax(150px, .7fr) minmax(0, 1.5fr) auto;
    gap: .85rem;
    align-items: center;
}
.expense-branch-row strong,
.expense-branch-row small {
    display: block;
}
.expense-branch-row small {
    color: #64748b;
}
.expense-branch-row b {
    white-space: nowrap;
}
.expense-branch-track {
    height: .75rem;
    border-radius: 999px;
    background: #f1f5f9;
    overflow: hidden;
}
.expense-branch-track span {
    display: block;
    height: 100%;
    border-radius: inherit;
    background: linear-gradient(90deg, #2563eb, #06b6d4);
}
.expense-form-grid {
    max-width: 980px;
}
.expense-recurring-box {
    min-height: 38px;
    display: flex;
    align-items: center;
    border: 1px solid #dbeafe;
    background: #eff6ff;
    border-radius: 8px;
    padding: .45rem .75rem;
}
.pending-expense-list {
    display: grid;
    gap: .75rem;
}
.pending-expense-item {
    display: grid;
    grid-template-columns: minmax(0, 1fr) minmax(280px, .72fr);
    gap: 1rem;
    align-items: center;
    padding: .9rem;
    border: 1px solid #fef3c7;
    border-radius: 8px;
    background: #fffbeb;
}
.pending-expense-item strong,
.pending-expense-item small {
    display: block;
}
.pending-expense-item strong {
    margin-top: .35rem;
}
.pending-expense-item small {
    color: #64748b;
}
.pending-expense-actions {
    display: grid;
    gap: .5rem;
}
.pending-expense-actions .d-flex,
.expense-reject-inline {
    display: flex;
    gap: .35rem;
}
.expense-row-actions {
    display: inline-flex;
    gap: .35rem;
}
.expense-reject-inline {
    min-width: 260px;
}
.expense-empty-state {
    padding: 3rem 1rem;
    text-align: center;
    color: #64748b;
}
.expense-empty-state i {
    display: inline-flex;
    width: 3.25rem;
    height: 3.25rem;
    align-items: center;
    justify-content: center;
    border-radius: 18px;
    background: #ecfeff;
    color: #0f766e;
    font-size: 1.4rem;
    margin-bottom: 1rem;
}
.expense-empty-state h4 {
    color: #0f172a;
    font-size: 1.1rem;
    font-weight: 800;
}
.expense-category-layout {
    display: grid;
    grid-template-columns: minmax(260px, .42fr) minmax(0, 1fr);
    gap: 1rem;
    align-items: start;
}
.expense-category-create {
    position: sticky;
    top: 1rem;
}
.expense-category-list {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: .65rem;
}
.expense-category-item {
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    overflow: hidden;
    background: #fff;
}
.expense-category-summary {
    width: 100%;
    border: 0;
    background: #fff;
    display: grid;
    grid-template-columns: minmax(0, 1fr) auto auto;
    gap: .6rem;
    align-items: center;
    padding: .75rem;
    text-align: left;
}
.expense-category-summary span {
    font-weight: 700;
    color: #0f172a;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.expense-category-summary em {
    font-style: normal;
    font-size: .75rem;
    color: #64748b;
}
.expense-category-edit {
    padding: .75rem;
    border-top: 1px solid #eef2f7;
    background: #f8fafc;
}
@media (max-width: 1199.98px) {
    .expense-hero,
    .expense-chart-grid,
    .expense-category-layout {
        grid-template-columns: 1fr;
    }
    .expense-branch-card {
        grid-column: auto;
    }
    .expense-category-create {
        position: static;
    }
}
@media (max-width: 991.98px) {
    .expense-metric-grid,
    .expense-category-list {
        grid-template-columns: 1fr;
    }
    .expense-pie-wrap,
    .expense-donut-wrap {
        grid-template-columns: 1fr;
        place-items: center;
    }
}
@media (max-width: 767.98px) {
    .expense-hero-copy {
        min-height: auto;
    }
    .pending-expense-item,
    .expense-branch-row {
        grid-template-columns: 1fr;
    }
}
</style>
@endsection
