@extends('backend.layout')

@section('backend_content')
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-start mb-4 flex-wrap gap-2">
            <div>
                <h4 class="fw-bold mb-1">Business Dashboard</h4>
                <small class="text-muted">Live overview of shops, products, orders, and revenue</small>

                {{-- Shop Management Dropdown for Non-Super Admin Users --}}
                @if (!$isSuperAdmin && $accessibleShops->count() > 0)
                    <div class="mt-2">
                        <small class="text-muted d-block mb-1">Your Shops:</small>
                        <div class="btn-group" role="group">
                            @foreach ($accessibleShops as $shop)
                                <a href="{{ route('admin.shops.show', $shop->id) }}"
                                    class="btn btn-sm btn-outline-primary{{ request()->route('shop')?->id == $shop->id ? ' active' : '' }}">
                                    <i class="bx bx-store me-1"></i>{{ $shop->name }}
                                </a>
                            @endforeach
                            @if ($accessibleShops->count() > 1)
                                <a href="{{ route('admin.shops.index') }}" class="btn btn-sm btn-outline-secondary">
                                    <i class="bx bx-list-ul me-1"></i> All Shops
                                </a>
                            @endif
                        </div>
                    </div>
                @elseif ($isSuperAdmin && $accessibleShops->count() > 0)
                    <div class="mt-2">
                        <small class="text-muted d-block mb-1">Total Shops: {{ $accessibleShops->count() }}</small>
                        <a href="{{ route('admin.shops.index') }}" class="btn btn-sm btn-outline-primary">
                            <i class="bx bx-list-ul me-1"></i> Manage All Shops
                        </a>
                    </div>
                @endif
            </div>
            <a href="{{ route('admin.orders.index') }}" class="btn btn-primary btn-sm">
                <i class="bx bx-receipt me-1"></i> Manage Orders
            </a>
        </div>

        <div class="row g-3 mb-4">
            <div class="col-12 col-sm-6 col-xl-3">
                <div class="card border-0 shadow-sm h-100 metric-card">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <small class="text-muted text-uppercase">Shops</small>
                            <h4 class="mb-0 fw-700">{{ $stats['shops'] }}</h4>
                        </div>
                        <span class="metric-chip bg-label-primary"><i class="bx bx-store"></i></span>
                    </div>
                </div>
            </div>
            <div class="col-12 col-sm-6 col-xl-3">
                <div class="card border-0 shadow-sm h-100 metric-card">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <small class="text-muted text-uppercase">Products</small>
                            <h4 class="mb-0 fw-700">{{ $stats['products'] }}</h4>
                            <small class="text-warning">Low stock: {{ $stats['low_stock_products'] }}</small>
                        </div>
                        <span class="metric-chip bg-label-warning"><i class="bx bx-package"></i></span>
                    </div>
                </div>
            </div>
            <div class="col-12 col-sm-6 col-xl-3">
                <div class="card border-0 shadow-sm h-100 metric-card">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <small class="text-muted text-uppercase">Orders</small>
                            <h4 class="mb-0 fw-700">{{ $stats['orders'] }}</h4>
                            <small class="text-muted">Pending: {{ $stats['pending_orders'] }}</small>
                        </div>
                        <span class="metric-chip bg-label-info"><i class="bx bx-cart"></i></span>
                    </div>
                </div>
            </div>
            <div class="col-12 col-sm-6 col-xl-3">
                <div class="card border-0 shadow-sm h-100 metric-card">
                    <div class="card-body d-flex justify-content-between align-items-center">
                        <div>
                            <small class="text-muted text-uppercase">Gross Sales</small>
                            <h4 class="mb-0 fw-700">৳{{ number_format($stats['gross_sales'], 0) }}</h4>
                            <small class="text-success">Completed: {{ $stats['completed_orders'] }}</small>
                        </div>
                        <span class="metric-chip bg-label-success"><i class="bx bx-line-chart"></i></span>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-4 mb-4">
            <div class="col-lg-8">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-white border-bottom d-flex justify-content-between align-items-center">
                        <h6 class="mb-0 fw-600">Revenue Trend (Last 6 Months)</h6>
                        <span class="badge bg-label-success">Total:
                            ৳{{ number_format(array_sum($monthlyRevenueSeries), 0) }}</span>
                    </div>
                    <div class="card-body">
                        <div id="revenueChart" style="min-height: 320px;"></div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-white border-bottom">
                        <h6 class="mb-0 fw-600">Order Status Split</h6>
                    </div>
                    <div class="card-body">
                        <div id="orderStatusChart" style="min-height: 280px;"></div>
                        <div class="d-flex flex-wrap gap-2 mt-2">
                            <span class="badge bg-warning text-dark">Pending: {{ $stats['pending_orders'] }}</span>
                            <span class="badge bg-success">Completed: {{ $stats['completed_orders'] }}</span>
                            <span class="badge bg-danger">Cancelled: {{ $stats['cancelled_orders'] }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row g-4">
            <div class="col-lg-5">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-white border-bottom d-flex justify-content-between align-items-center">
                        <h6 class="mb-0 fw-600">Top Shops by Revenue</h6>
                        <small class="text-muted">Top 5</small>
                    </div>
                    <div class="table-responsive">
                        <table class="table align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Shop</th>
                                    <th class="text-end">Qty</th>
                                    <th class="text-end">Revenue</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse ($topShops as $row)
                                    <tr>
                                        <td class="fw-600">{{ $row->shop_name ?: 'Unknown' }}</td>
                                        <td class="text-end">{{ (int) $row->qty_sold }}</td>
                                        <td class="text-end">৳{{ number_format((float) $row->revenue, 0) }}</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="3" class="text-center py-4 text-muted">No sales data yet.</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="col-lg-7">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-white border-bottom d-flex justify-content-between align-items-center">
                        <h6 class="mb-0 fw-600">Recent Orders</h6>
                        <a href="{{ route('admin.orders.index') }}" class="small">View all</a>
                    </div>
                    <div class="table-responsive">
                        <table class="table align-middle mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Order</th>
                                    <th>Customer</th>
                                    <th>Status</th>
                                    <th class="text-end">Amount</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse ($recentOrders as $order)
                                    <tr>
                                        <td>
                                            <a href="{{ route('admin.orders.show', $order) }}"
                                                class="fw-600 text-decoration-none">
                                                {{ $order->order_number }}
                                            </a>
                                        </td>
                                        <td>{{ $order->customer_name }}</td>
                                        <td>
                                            @if ($order->status === 'pending')
                                                <span class="badge bg-warning text-dark">Pending</span>
                                            @elseif ($order->status === 'completed')
                                                <span class="badge bg-success">Completed</span>
                                            @elseif ($order->status === 'cancelled')
                                                <span class="badge bg-danger">Cancelled</span>
                                            @else
                                                <span class="badge bg-secondary">{{ ucfirst($order->status) }}</span>
                                            @endif
                                        </td>
                                        <td class="text-end">৳{{ number_format((float) $order->total_amount, 0) }}</td>
                                        <td>{{ \Illuminate\Support\Carbon::parse($order->created_at)->format('M d, Y') }}
                                        </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="5" class="text-center py-4 text-muted">No orders found yet.</td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('backend_css')
    <style>
        .fw-600 {
            font-weight: 600;
        }

        .fw-700 {
            font-weight: 700;
        }

        .metric-chip {
            width: 44px;
            height: 44px;
            border-radius: 12px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 1.3rem;
        }

        .metric-card {
            border-radius: 14px;
            transition: transform .2s ease, box-shadow .2s ease;
        }

        .metric-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 24px rgba(0, 0, 0, .08) !important;
        }
    </style>
@endpush

@push('backend_js')
    <script>
        (function() {
            const monthLabels = @json($monthLabels);
            const monthlyRevenueSeries = @json($monthlyRevenueSeries);
            const orderStatusSeries = @json($orderStatusSeries);

            const revenueChartEl = document.querySelector('#revenueChart');
            if (revenueChartEl) {
                const revenueChart = new ApexCharts(revenueChartEl, {
                    chart: {
                        type: 'area',
                        height: 320,
                        toolbar: {
                            show: false
                        }
                    },
                    series: [{
                        name: 'Revenue',
                        data: monthlyRevenueSeries
                    }],
                    xaxis: {
                        categories: monthLabels
                    },
                    stroke: {
                        curve: 'smooth',
                        width: 3
                    },
                    colors: ['#696cff'],
                    fill: {
                        type: 'gradient',
                        gradient: {
                            shadeIntensity: 1,
                            opacityFrom: 0.35,
                            opacityTo: 0.05,
                        }
                    },
                    dataLabels: {
                        enabled: false
                    },
                    yaxis: {
                        labels: {
                            formatter: function(value) {
                                return '৳' + Number(value).toLocaleString();
                            }
                        }
                    },
                    tooltip: {
                        y: {
                            formatter: function(value) {
                                return '৳' + Number(value).toLocaleString();
                            }
                        }
                    },
                    grid: {
                        borderColor: '#eceef1'
                    }
                });
                revenueChart.render();
            }

            const statusChartEl = document.querySelector('#orderStatusChart');
            if (statusChartEl) {
                const statusChart = new ApexCharts(statusChartEl, {
                    chart: {
                        type: 'donut',
                        height: 280
                    },
                    labels: ['Pending', 'Completed', 'Cancelled'],
                    series: orderStatusSeries,
                    colors: ['#ffab00', '#71dd37', '#ff3e1d'],
                    legend: {
                        position: 'bottom'
                    },
                    dataLabels: {
                        enabled: true
                    },
                    stroke: {
                        width: 0
                    }
                });
                statusChart.render();
            }
        })();
    </script>
@endpush
