<x-app-layout>
    <x-slot name="header">{{ __('Dashboard') }}</x-slot>

    @php
        $chartLabelsJson    = json_encode($chartLabels);
        $chartSalesJson     = json_encode($chartSales);
        $chartPurchasesJson = json_encode($chartPurchases);
        $chartExpensesJson  = json_encode($chartExpenses);
        $hasFinancial = Auth::user()->canAny(['sales.view', 'purchases.view', 'expenses.view']);
        $hasPeople    = Auth::user()->canAny(['employees.view', 'customers.view', 'rosters.view']);
    @endphp

    {{-- ─── Always-visible welcome strip ──────────────────────────────── --}}
    <div class="alert alert-light border mb-4 d-flex align-items-center gap-2 py-2">
        <i class="bi bi-person-circle fs-5 text-primary"></i>
        <span>{{ __('Welcome back') }}, <strong>{{ Auth::user()->name }}</strong>
            &mdash; {{ now()->format('l, d M Y') }}</span>
    </div>

    {{-- ─── Stat Cards Row ─────────────────────────────────────────────── --}}
    @if($hasFinancial)
    <div class="row g-3 mb-4">
        {{-- Today --}}
        @can('sales.view')
        <div class="col-6 col-md-4 col-xl-2">
            <div class="card text-bg-primary h-100 border-0 shadow-sm">
                <div class="card-body py-3">
                    <div class="d-flex align-items-center gap-2 mb-1">
                        <i class="bi bi-cart3 fs-5"></i>
                        <small class="fw-semibold">{{ __("Today's Sales") }}</small>
                    </div>
                    <h4 class="mb-0">{{ number_format($stats['sales'], 2) }}</h4>
                </div>
            </div>
        </div>
        @endcan
        @can('purchases.view')
        <div class="col-6 col-md-4 col-xl-2">
            <div class="card text-bg-success h-100 border-0 shadow-sm">
                <div class="card-body py-3">
                    <div class="d-flex align-items-center gap-2 mb-1">
                        <i class="bi bi-box-seam fs-5"></i>
                        <small class="fw-semibold">{{ __("Today's Purchases") }}</small>
                    </div>
                    <h4 class="mb-0">{{ number_format($stats['purchases'], 2) }}</h4>
                </div>
            </div>
        </div>
        @endcan
        @can('expenses.view')
        <div class="col-6 col-md-4 col-xl-2">
            <div class="card text-bg-warning h-100 border-0 shadow-sm">
                <div class="card-body py-3">
                    <div class="d-flex align-items-center gap-2 mb-1">
                        <i class="bi bi-receipt fs-5"></i>
                        <small class="fw-semibold">{{ __("Today's Expenses") }}</small>
                    </div>
                    <h4 class="mb-0">{{ number_format($stats['expenses'], 2) }}</h4>
                </div>
            </div>
        </div>
        @endcan
        {{-- Yesterday --}}
        @can('sales.view')
        <div class="col-6 col-md-4 col-xl-2">
            <div class="card h-100 border-0 shadow-sm" style="background:#e8f5e9">
                <div class="card-body py-3">
                    <div class="d-flex align-items-center gap-2 mb-1 text-success">
                        <i class="bi bi-cart3 fs-5"></i>
                        <small class="fw-semibold">{{ __("Yesterday Sales") }}</small>
                    </div>
                    <h4 class="mb-0 text-success">{{ number_format($stats['yesterday_sales'], 2) }}</h4>
                </div>
            </div>
        </div>
        @endcan
        @can('purchases.view')
        <div class="col-6 col-md-4 col-xl-2">
            <div class="card h-100 border-0 shadow-sm" style="background:#fce4ec">
                <div class="card-body py-3">
                    <div class="d-flex align-items-center gap-2 mb-1 text-danger">
                        <i class="bi bi-box-seam fs-5"></i>
                        <small class="fw-semibold">{{ __("Yesterday Purchases") }}</small>
                    </div>
                    <h4 class="mb-0 text-danger">{{ number_format($stats['yesterday_purchases'], 2) }}</h4>
                </div>
            </div>
        </div>
        @endcan
        @can('expenses.view')
        <div class="col-6 col-md-4 col-xl-2">
            <div class="card h-100 border-0 shadow-sm" style="background:#fff3e0">
                <div class="card-body py-3">
                    <div class="d-flex align-items-center gap-2 mb-1" style="color:#e65100">
                        <i class="bi bi-receipt fs-5"></i>
                        <small class="fw-semibold">{{ __("Yesterday Expenses") }}</small>
                    </div>
                    <h4 class="mb-0" style="color:#e65100">{{ number_format($stats['yesterday_expenses'], 2) }}</h4>
                </div>
            </div>
        </div>
        @endcan
    </div>
    @endif

    {{-- ─── Charts Row ───────────────────────────────────────────────────── --}}
    @if($hasFinancial)
    <div class="row g-4 mb-4">
        {{-- Last 7 Days Line Chart --}}
        <div class="col-12 col-xl-8">
            <div class="card shadow-sm border-0 h-100">
                <div class="card-header bg-white border-0 pt-3 pb-0">
                    <h6 class="fw-semibold mb-0"><i class="bi bi-graph-up me-2 text-primary"></i>{{ __('Last 7 Days Overview') }}</h6>
                </div>
                <div class="card-body">
                    <canvas id="weeklyChart" height="130"></canvas>
                </div>
            </div>
        </div>

        {{-- Last 30 Days Bar Chart --}}
        <div class="col-12 col-xl-4">
            <div class="card shadow-sm border-0 h-100">
                <div class="card-header bg-white border-0 pt-3 pb-0">
                    <h6 class="fw-semibold mb-0"><i class="bi bi-bar-chart-fill me-2 text-success"></i>{{ __('Last 30 Days Totals') }}</h6>
                </div>
                <div class="card-body d-flex align-items-center">
                    <canvas id="monthChart" height="200"></canvas>
                </div>
            </div>
        </div>
    </div>
    @endif

    {{-- ─── Summary & Recent Sales ───────────────────────────────────────── --}}
    @if($hasFinancial || $hasPeople)
    <div class="row g-4">
        {{-- Summary Panel --}}
        <div class="col-12 col-xl-4">
            <div class="card shadow-sm border-0 h-100">
                <div class="card-header bg-white border-0 pt-3 pb-0">
                    <h6 class="fw-semibold mb-0"><i class="bi bi-clipboard-data me-2 text-secondary"></i>{{ __('Summary') }}</h6>
                </div>
                <div class="card-body p-0">
                    <ul class="list-group list-group-flush">
                        @can('employees.view')
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-people me-2 text-primary"></i>{{ __('Employees') }}</span>
                            <span class="badge rounded-pill bg-primary">{{ $stats['employees'] }}</span>
                        </li>
                        @endcan
                        @can('customers.view')
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-person-check me-2 text-success"></i>{{ __('Customers') }}</span>
                            <span class="badge rounded-pill bg-success">{{ $stats['customers'] }}</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-exclamation-circle me-2 text-danger"></i>{{ __('Customers with Due') }}</span>
                            <span class="badge rounded-pill bg-danger">{{ $stats['due_customers'] }}</span>
                        </li>
                        @endcan
                        @can('rosters.view')
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-calendar3 me-2 text-info"></i>{{ __("Today's Rosters") }}</span>
                            <span class="badge rounded-pill bg-info">{{ $stats['rosters'] }}</span>
                        </li>
                        @endcan
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-calendar-day me-2 text-secondary"></i>{{ __('Today') }}</span>
                            <span class="text-muted small">{{ $today->toFormattedDateString() }}</span>
                        </li>
                        @if($hasFinancial)
                        <li class="list-group-item">
                            @can('sales.view')
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <small class="text-muted">{{ __('Month Sales') }}</small>
                                <strong class="text-primary">{{ number_format($stats['month_sales'], 2) }}</strong>
                            </div>
                            @endcan
                            @can('purchases.view')
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <small class="text-muted">{{ __('Month Purchases') }}</small>
                                <strong class="text-danger">{{ number_format($stats['month_purchases'], 2) }}</strong>
                            </div>
                            @endcan
                            @can('expenses.view')
                            <div class="d-flex justify-content-between align-items-center">
                                <small class="text-muted">{{ __('Month Expenses') }}</small>
                                <strong class="text-warning">{{ number_format($stats['month_expenses'], 2) }}</strong>
                            </div>
                            @endcan
                        </li>
                        @endif
                    </ul>
                </div>
            </div>
        </div>

        {{-- Latest Sales --}}
        @can('sales.view')
        <div class="col-12 col-xl-8">
            <div class="card shadow-sm border-0 h-100">
                <div class="card-header bg-white border-0 pt-3 pb-0">
                    <h6 class="fw-semibold mb-0"><i class="bi bi-clock-history me-2 text-primary"></i>{{ __('Latest 5 Sales') }}</h6>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>{{ __('Date') }}</th>
                                <th>{{ __('Customer') }}</th>
                                <th>{{ __('Source') }}</th>
                                <th class="text-end">{{ __('Amount') }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($latestSales as $sale)
                                <tr>
                                    <td>{{ $sale->sale_date ?? $sale->created_at->format('Y-m-d') }}</td>
                                    <td>{{ optional($sale->customer)->name ?? __('Walk-in') }}</td>
                                    <td><span class="badge bg-secondary">{{ str_replace('_', ' ', $sale->source ?? '') }}</span></td>
                                    <td class="text-end fw-semibold">{{ number_format($sale->amount, 2) }}</td>
                                </tr>
                            @empty
                                <tr>
                                    <td colspan="4" class="text-center text-muted py-4">{{ __('No recent sales yet.') }}</td>
                                </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        @endcan
    </div>
    @endif

    {{-- ─── No permissions fallback ─────────────────────────────────────── --}}
    @if(!$hasFinancial && !$hasPeople)
    <div class="text-center py-5 text-muted">
        <i class="bi bi-shield-lock display-3 mb-3 d-block"></i>
        <h5>{{ __('No dashboard data available for your role.') }}</h5>
        <p class="mb-0">{{ __('Please contact an administrator if you believe this is a mistake.') }}</p>
    </div>
    @endif

    {{-- Chart.js (only when financial data is visible) --}}
    @if($hasFinancial)
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2/dist/chart.umd.min.js"></script>
    <script>
    (function () {
        const labels    = {!! $chartLabelsJson !!};
        const sales     = {!! $chartSalesJson !!};
        const purchases = {!! $chartPurchasesJson !!};
        const expenses  = {!! $chartExpensesJson !!};

        // Weekly Line Chart
        new Chart(document.getElementById('weeklyChart'), {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    @can('sales.view')
                    {
                        label: '{{ __("Sales") }}',
                        data: sales,
                        borderColor: '#0d6efd',
                        backgroundColor: 'rgba(13,110,253,.1)',
                        tension: .4, fill: true, pointRadius: 4,
                    },
                    @endcan
                    @can('purchases.view')
                    {
                        label: '{{ __("Purchases") }}',
                        data: purchases,
                        borderColor: '#dc3545',
                        backgroundColor: 'rgba(220,53,69,.08)',
                        tension: .4, fill: true, pointRadius: 4,
                    },
                    @endcan
                    @can('expenses.view')
                    {
                        label: '{{ __("Expenses") }}',
                        data: expenses,
                        borderColor: '#fd7e14',
                        backgroundColor: 'rgba(253,126,20,.08)',
                        tension: .4, fill: true, pointRadius: 4,
                    },
                    @endcan
                ],
            },
            options: {
                responsive: true,
                interaction: { mode: 'index', intersect: false },
                plugins: { legend: { position: 'top' } },
                scales: { y: { beginAtZero: true } },
            },
        });

        // Monthly Bar Chart
        const barLabels = [];
        const barData   = [];
        const barColors = [];
        @can('sales.view')
        barLabels.push('{{ __("Sales") }}'); barData.push({{ $stats['month_sales'] }}); barColors.push('#0d6efd');
        @endcan
        @can('purchases.view')
        barLabels.push('{{ __("Purchases") }}'); barData.push({{ $stats['month_purchases'] }}); barColors.push('#dc3545');
        @endcan
        @can('expenses.view')
        barLabels.push('{{ __("Expenses") }}'); barData.push({{ $stats['month_expenses'] }}); barColors.push('#fd7e14');
        @endcan

        new Chart(document.getElementById('monthChart'), {
            type: 'bar',
            data: {
                labels: barLabels,
                datasets: [{
                    label: '{{ __("Last 30 Days") }}',
                    data: barData,
                    backgroundColor: barColors,
                    borderRadius: 6,
                }],
            },
            options: {
                responsive: true,
                plugins: { legend: { display: false } },
                scales: { y: { beginAtZero: true } },
            },
        });
    })();
    </script>
    @endif
</x-app-layout>
