@extends('admin.layout.dashboard_master')

@section('content')
    <main id="main" class="main">

        <div class="pagetitle d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="fw-bold text-dark">Overview Dashboard</h1>
                <nav>
                    <ol class="breadcrumb mb-0">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item active">Dashboard Analytics</li>
                    </ol>
                </nav>
            </div>
            <div class="text-end">
                <span class="badge bg-white text-dark shadow-sm px-3 py-2 border">
                    <i class="bi bi-clock text-primary me-2"></i> {{ now()->format('M d, Y H:i A') }}
                </span>
            </div>
        </div>

        <section class="section dashboard">
            <style>
                .premium-card {
                    border: none;
                    border-radius: 16px;
                    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.04);
                    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
                    overflow: hidden;
                    background: #fff;
                    border: 1px solid rgba(0, 0, 0, 0.03);
                }
                .premium-card:hover {
                    transform: translateY(-5px);
                    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.08);
                }
                .icon-box {
                    width: 52px;
                    height: 52px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    border-radius: 14px;
                    font-size: 26px;
                    transition: all 0.3s ease;
                }
                .premium-card:hover .icon-box {
                    transform: scale(1.1);
                }
                .bg-primary-light { background-color: rgba(65, 84, 241, 0.1); color: #4154f1; }
                .bg-success-light { background-color: rgba(46, 202, 106, 0.1); color: #2eca6a; }
                .bg-warning-light { background-color: rgba(255, 119, 29, 0.1); color: #ff771d; }
                .bg-info-light { background-color: rgba(13, 202, 240, 0.1); color: #0dcaf0; }
                .bg-danger-light { background-color: rgba(220, 53, 69, 0.1); color: #dc3545; }
                .bg-purple-light { background-color: rgba(111, 66, 193, 0.1); color: #6f42c1; }
                .bg-dark-light { background-color: rgba(33, 37, 41, 0.1); color: #212529; }
                
                .chart-container { min-height: 380px; }
                .trend-indicator { font-size: 0.8rem; font-weight: 600; }
                
                .table-premium thead th {
                    background-color: #f8f9fa;
                    border-bottom: 2px solid #f1f3f5;
                    font-weight: 600;
                    text-transform: uppercase;
                    font-size: 0.72rem;
                    letter-spacing: 0.5px;
                    color: #6c757d;
                    padding: 12px 16px;
                }
                .table-premium tbody td {
                    padding: 14px 16px;
                    border-bottom: 1px solid #f1f3f5;
                    color: #495057;
                }
                .product-img {
                    width: 44px;
                    height: 44px;
                    object-fit: cover;
                    border-radius: 10px;
                    border: 1px solid #eee;
                }
                .card-title {
                    font-size: 1.15rem;
                    font-weight: 700;
                    color: #012970;
                    margin-bottom: 1.25rem;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                }
                .nav-pills-premium .nav-link {
                    border-radius: 8px;
                    padding: 8px 18px;
                    font-weight: 600;
                    font-size: 0.82rem;
                    background: #f1f3f9;
                    color: #495057;
                    margin-left: 8px;
                    border: none;
                    transition: all 0.2s ease;
                }
                .nav-pills-premium .nav-link.active {
                    background: #4154f1;
                    color: #fff;
                    box-shadow: 0 4px 12px rgba(65, 84, 241, 0.2);
                }
                .stat-label {
                    font-size: 0.8rem;
                    font-weight: 600;
                    color: #899bbd;
                    text-transform: uppercase;
                    letter-spacing: 0.5px;
                }
                .avatar-initials {
                    width: 38px;
                    height: 38px;
                    border-radius: 50%;
                    background: #e9ecef;
                    color: #495057;
                    font-weight: 600;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 0.85rem;
                }
            </style>

            <!-- 1. Overview Dashboard Row 1 -->
            <div class="row g-4 mb-4">
                <!-- Total Sales Today -->
                <div class="col-xl-3 col-md-6">
                    <div class="card premium-card h-100 p-4">
                        <div class="d-flex align-items-center justify-content-between mb-3">
                            <div>
                                <span class="stat-label">Sales Today</span>
                                <h3 class="mb-0 fw-bold mt-1 text-dark">LKR {{ number_format($salesToday, 0) }}</h3>
                            </div>
                            <div class="icon-box bg-primary-light">
                                <i class="bi bi-cash-stack"></i>
                            </div>
                        </div>
                        <div class="pt-2 border-top d-flex justify-content-between align-items-center">
                            <span class="text-muted small">Est. Profit (25%)</span>
                            <span class="fw-semibold text-primary">LKR {{ number_format($profitToday, 0) }}</span>
                        </div>
                    </div>
                </div>

                <!-- Total Sales Month -->
                <div class="col-xl-3 col-md-6">
                    <div class="card premium-card h-100 p-4">
                        <div class="d-flex align-items-center justify-content-between mb-3">
                            <div>
                                <span class="stat-label">Sales Month</span>
                                <h3 class="mb-0 fw-bold mt-1 text-dark">LKR {{ number_format($salesMonth, 0) }}</h3>
                            </div>
                            <div class="icon-box bg-success-light">
                                <i class="bi bi-calendar3"></i>
                            </div>
                        </div>
                        <div class="pt-2 border-top d-flex justify-content-between align-items-center">
                            <span class="text-muted small">Est. Profit (25%)</span>
                            <span class="fw-semibold text-success">LKR {{ number_format($profitMonth, 0) }}</span>
                        </div>
                    </div>
                </div>

                <!-- Total Orders & Pending -->
                <div class="col-xl-3 col-md-6">
                    <div class="card premium-card h-100 p-4">
                        <div class="d-flex align-items-center justify-content-between mb-3">
                            <div>
                                <span class="stat-label">Total Orders</span>
                                <h3 class="mb-0 fw-bold mt-1 text-dark">{{ number_format($totalOrdersCount) }}</h3>
                            </div>
                            <div class="icon-box bg-warning-light">
                                <i class="bi bi-cart-check"></i>
                            </div>
                        </div>
                        <div class="pt-2 border-top d-flex justify-content-between align-items-center">
                            <span class="text-muted small">Pending Orders</span>
                            <span class="badge bg-warning text-white">{{ $pendingOrdersCount }}</span>
                        </div>
                    </div>
                </div>

                <!-- Total Customers -->
                <div class="col-xl-3 col-md-6">
                    <div class="card premium-card h-100 p-4">
                        <div class="d-flex align-items-center justify-content-between mb-3">
                            <div>
                                <span class="stat-label">Total Customers</span>
                                <h3 class="mb-0 fw-bold mt-1 text-dark">{{ number_format($totalCustomersCount) }}</h3>
                            </div>
                            <div class="icon-box bg-info-light">
                                <i class="bi bi-people"></i>
                            </div>
                        </div>
                        <div class="pt-2 border-top d-flex justify-content-between align-items-center">
                            <span class="text-muted small">Total Products</span>
                            <span class="fw-semibold text-info">{{ $totalProductsCount }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Overview Dashboard Row 2 -->
            <div class="row g-4 mb-4">
                <!-- Year Sales -->
                <div class="col-xl-3 col-md-6">
                    <div class="card premium-card h-100 p-4">
                        <div class="d-flex align-items-center justify-content-between mb-3">
                            <div>
                                <span class="stat-label">Sales Year</span>
                                <h3 class="mb-0 fw-bold mt-1 text-dark">LKR {{ number_format($salesYear, 0) }}</h3>
                            </div>
                            <div class="icon-box bg-purple-light">
                                <i class="bi bi-calendar-range-fill"></i>
                            </div>
                        </div>
                        <div class="pt-2 border-top d-flex justify-content-between align-items-center">
                            <span class="text-muted small">Est. Profit (25%)</span>
                            <span class="fw-semibold text-purple">LKR {{ number_format($profitYear, 0) }}</span>
                        </div>
                    </div>
                </div>

                <!-- Average Order Value (AOV) -->
                <div class="col-xl-3 col-md-6">
                    <div class="card premium-card h-100 p-4">
                        <div class="d-flex align-items-center justify-content-between mb-3">
                            <div>
                                <span class="stat-label">Average Order Value</span>
                                <h3 class="mb-0 fw-bold mt-1 text-dark">LKR {{ number_format($averageOrderValue, 2) }}</h3>
                            </div>
                            <div class="icon-box bg-dark-light">
                                <i class="bi bi-calculator"></i>
                            </div>
                        </div>
                        <div class="pt-2 border-top d-flex justify-content-between align-items-center">
                            <span class="text-muted small">Conversion Rate</span>
                            <span class="fw-bold text-dark">{{ $conversionRate }}%</span>
                        </div>
                    </div>
                </div>

                <!-- Refund Amount -->
                <div class="col-xl-3 col-md-6">
                    <div class="card premium-card h-100 p-4">
                        <div class="d-flex align-items-center justify-content-between mb-3">
                            <div>
                                <span class="stat-label">Refund Amount</span>
                                <h3 class="mb-0 fw-bold mt-1 text-danger">LKR {{ number_format($refundAmount, 2) }}</h3>
                            </div>
                            <div class="icon-box bg-danger-light">
                                <i class="bi bi-arrow-left-right"></i>
                            </div>
                        </div>
                        <div class="pt-2 border-top d-flex justify-content-between align-items-center">
                            <span class="text-muted small">Refunded Cancelled</span>
                            <span class="text-danger small fw-semibold">Estimated</span>
                        </div>
                    </div>
                </div>

                <!-- Conversion & Traffic -->
                <div class="col-xl-3 col-md-6">
                    <div class="card premium-card h-100 p-4">
                        <div class="d-flex align-items-center justify-content-between mb-3">
                            <div>
                                <span class="stat-label">Conversion & Traffic</span>
                                <h3 class="mb-0 fw-bold mt-1 text-dark">{{ $conversionRate }}%</h3>
                            </div>
                            <div class="icon-box bg-warning-light">
                                <i class="bi bi-graph-up-arrow"></i>
                            </div>
                        </div>
                        <div class="pt-2 border-top d-flex justify-content-between align-items-center">
                            <span class="text-muted small">Total Visitors</span>
                            <span class="fw-semibold text-warning">{{ number_format($totalVisitorsCount) }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 2. Sales Analytics Main Section -->
            <div class="row g-4">
                <!-- Sales Charts by Day/Month/Year -->
                <div class="col-lg-8">
                    <div class="card premium-card h-100">
                        <div class="card-body p-4">
                            <div class="d-flex justify-content-between align-items-center flex-wrap mb-4">
                                <h5 class="card-title mb-0"><i class="bi bi-bar-chart-line text-primary me-2"></i>Sales Analytics Charts</h5>
                                <ul class="nav nav-pills nav-pills-premium mt-2 mt-md-0" id="sales-chart-tab" role="tablist">
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link active" id="pills-day-tab" data-bs-toggle="pill" data-bs-target="#pills-day" type="button" role="tab">Daily</button>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" id="pills-month-tab" data-bs-toggle="pill" data-bs-target="#pills-month" type="button" role="tab">Monthly</button>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" id="pills-year-tab" data-bs-toggle="pill" data-bs-target="#pills-year" type="button" role="tab">Yearly</button>
                                    </li>
                                </ul>
                            </div>

                            <div class="tab-content" id="sales-chart-tabContent">
                                <div class="tab-pane fade show active" id="pills-day" role="tabpanel">
                                    <div id="dailySalesChart" class="chart-container"></div>
                                </div>
                                <div class="tab-pane fade" id="pills-month" role="tabpanel">
                                    <div id="monthlySalesChart" class="chart-container"></div>
                                </div>
                                <div class="tab-pane fade" id="pills-year" role="tabpanel">
                                    <div id="yearlySalesChart" class="chart-container"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Revenue Comparisons -->
                <div class="col-lg-4">
                    <div class="card premium-card h-100">
                        <div class="card-body p-4 d-flex flex-column">
                            <h5 class="card-title mb-4"><i class="bi bi-lightning text-warning me-2"></i>Revenue Comparison</h5>
                            
                            <!-- MoM Comparison -->
                            <div class="flex-grow-1 mb-4 p-4 rounded-4 border bg-light d-flex flex-column justify-content-center">
                                <span class="stat-label text-secondary mb-1">Month-over-Month (MoM)</span>
                                <div class="d-flex align-items-baseline justify-content-between mt-2">
                                    <h4 class="mb-0 fw-bold">LKR {{ number_format($salesMonth, 0) }}</h4>
                                    @if($monthGrowthPercent >= 0)
                                        <span class="badge bg-success-light text-success trend-indicator">
                                            <i class="bi bi-arrow-up-right me-1"></i> +{{ $monthGrowthPercent }}%
                                        </span>
                                    @else
                                        <span class="badge bg-danger-light text-danger trend-indicator">
                                            <i class="bi bi-arrow-down-left me-1"></i> {{ $monthGrowthPercent }}%
                                        </span>
                                    @endif
                                </div>
                                <p class="text-muted small mt-2 mb-0">vs. Last Month (LKR {{ number_format($salesLastMonth, 0) }})</p>
                            </div>

                            <!-- YoY Comparison -->
                            <div class="flex-grow-1 p-4 rounded-4 border bg-light d-flex flex-column justify-content-center">
                                <span class="stat-label text-secondary mb-1">Year-over-Year (YoY)</span>
                                <div class="d-flex align-items-baseline justify-content-between mt-2">
                                    <h4 class="mb-0 fw-bold">LKR {{ number_format($salesYear, 0) }}</h4>
                                    @if($yearGrowthPercent >= 0)
                                        <span class="badge bg-success-light text-success trend-indicator">
                                            <i class="bi bi-arrow-up-right me-1"></i> +{{ $yearGrowthPercent }}%
                                        </span>
                                    @else
                                        <span class="badge bg-danger-light text-danger trend-indicator">
                                            <i class="bi bi-arrow-down-left me-1"></i> {{ $yearGrowthPercent }}%
                                        </span>
                                    @endif
                                </div>
                                <p class="text-muted small mt-2 mb-0">vs. Last Year (LKR {{ number_format($salesLastYear, 0) }})</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Row 3: Best-Selling & Payment Method Statistics -->
            <div class="row g-4 mt-2">
                <!-- Payment Method Stats -->
                <div class="col-lg-5">
                    <div class="card premium-card h-100">
                        <div class="card-body p-4">
                            <h5 class="card-title mb-4"><i class="bi bi-credit-card text-success me-2"></i>Payment Statistics</h5>
                            <div id="paymentStatsChart" style="height: 250px;"></div>
                            <div class="table-responsive mt-3">
                                <table class="table table-sm table-borderless table-premium">
                                    <thead>
                                        <tr>
                                            <th>Method</th>
                                            <th class="text-center">Orders</th>
                                            <th class="text-end">Revenue</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @php
                                            $methodNames = [
                                                'cod' => 'Cash on Delivery',
                                                'visa' => 'Card Payment',
                                                'card' => 'Card Payment',
                                                'koko' => 'Koko',
                                                'mintpay' => 'Mintpay'
                                            ];
                                        @endphp
                                        @forelse($paymentStats as $stat)
                                            <tr>
                                                <td class="fw-semibold">
                                                    {{ $methodNames[strtolower($stat->payment_method)] ?? ucfirst($stat->payment_method) }}
                                                </td>
                                                <td class="text-center fw-bold">{{ $stat->count }}</td>
                                                <td class="text-end text-primary fw-semibold">LKR {{ number_format($stat->total_sales, 2) }}</td>
                                            </tr>
                                        @empty
                                            <tr>
                                                <td colspan="3" class="text-center text-muted">No data available</td>
                                            </tr>
                                        @endforelse
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Sales by Category -->
                <div class="col-lg-7">
                    <div class="card premium-card h-100">
                        <div class="card-body p-4">
                            <h5 class="card-title mb-4"><i class="bi bi-tags text-info me-2"></i>Sales by Category</h5>
                            <div id="categorySalesChart" style="height: 250px;"></div>
                            <div class="table-responsive mt-3" style="max-height: 250px; overflow-y: auto;">
                                <table class="table table-borderless table-premium align-middle mb-0">
                                    <thead>
                                        <tr>
                                            <th>Category</th>
                                            <th class="text-center">Units Sold</th>
                                            <th class="text-end">Revenue</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @forelse($salesByCategory as $cat)
                                            <tr>
                                                <td class="fw-bold">{{ $cat->category_name }}</td>
                                                <td class="text-center">{{ number_format($cat->count) }}</td>
                                                <td class="text-end text-success fw-semibold">LKR {{ number_format($cat->sales, 2) }}</td>
                                            </tr>
                                        @empty
                                            <tr>
                                                <td colspan="3" class="text-center text-muted">No category sales found</td>
                                            </tr>
                                        @endforelse
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Row 4: Sales by Location & Top Customers -->
            <div class="row g-4 mt-2">
                <!-- Sales by Location (City / District) -->
                <div class="col-lg-6">
                    <div class="card premium-card h-100">
                        <div class="card-body p-4">
                            <div class="d-flex justify-content-between align-items-center flex-wrap mb-4">
                                <h5 class="card-title mb-0"><i class="bi bi-geo-alt text-danger me-2"></i>Sales by Location</h5>
                                <ul class="nav nav-pills nav-pills-premium mt-2 mt-md-0" id="location-tab" role="tablist">
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link active" id="pills-city-tab" data-bs-toggle="pill" data-bs-target="#pills-city" type="button" role="tab">Cities</button>
                                    </li>
                                    <li class="nav-item" role="presentation">
                                        <button class="nav-link" id="pills-district-tab" data-bs-toggle="pill" data-bs-target="#pills-district" type="button" role="tab">Districts</button>
                                    </li>
                                </ul>
                            </div>

                            <div class="tab-content" id="location-tabContent">
                                <div class="tab-pane fade show active" id="pills-city" role="tabpanel">
                                    <div id="citySalesChart" class="chart-container" style="min-height: 250px;"></div>
                                    <div class="table-responsive mt-3" style="max-height: 220px; overflow-y: auto;">
                                        <table class="table table-borderless table-premium align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>City</th>
                                                    <th class="text-center">Orders</th>
                                                    <th class="text-end">Sales Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @forelse($salesByCity as $city)
                                                    <tr>
                                                        <td>{{ $city->city }}</td>
                                                        <td class="text-center">{{ $city->count }}</td>
                                                        <td class="text-end fw-semibold text-primary">LKR {{ number_format($city->sales, 2) }}</td>
                                                    </tr>
                                                @empty
                                                    <tr>
                                                        <td colspan="3" class="text-center text-muted">No data available</td>
                                                    </tr>
                                                @endforelse
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                <div class="tab-pane fade" id="pills-district" role="tabpanel">
                                    <div id="districtSalesChart" class="chart-container" style="min-height: 250px;"></div>
                                    <div class="table-responsive mt-3" style="max-height: 220px; overflow-y: auto;">
                                        <table class="table table-borderless table-premium align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>District</th>
                                                    <th class="text-center">Orders</th>
                                                    <th class="text-end">Sales Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @forelse($salesByDistrict as $dist)
                                                    <tr>
                                                        <td>{{ $dist->district }}</td>
                                                        <td class="text-center">{{ $dist->count }}</td>
                                                        <td class="text-end fw-semibold text-primary">LKR {{ number_format($dist->sales, 2) }}</td>
                                                    </tr>
                                                @empty
                                                    <tr>
                                                        <td colspan="3" class="text-center text-muted">No data available</td>
                                                    </tr>
                                                @endforelse
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Top Customers -->
                <div class="col-lg-6">
                    <div class="card premium-card h-100">
                        <div class="card-body p-4">
                            <h5 class="card-title mb-4"><i class="bi bi-award text-warning me-2"></i>Top Spending Customers</h5>
                            <div class="table-responsive" style="max-height: 520px; overflow-y: auto;">
                                <table class="table table-borderless table-premium align-middle mb-0">
                                    <thead>
                                        <tr>
                                            <th>Customer Details</th>
                                            <th class="text-center">Orders</th>
                                            <th class="text-end">Total Spent</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @forelse($topCustomers as $customer)
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <div class="avatar-initials me-3">
                                                            {{ strtoupper(substr($customer->first_name, 0, 1)) }}{{ strtoupper(substr($customer->last_name, 0, 1)) }}
                                                        </div>
                                                        <div>
                                                            <div class="fw-bold text-dark">{{ $customer->first_name }} {{ $customer->last_name }}</div>
                                                            <div class="text-muted small">{{ $customer->email }}</div>
                                                            <div class="text-muted small" style="font-size: 0.75rem;">{{ $customer->telephone }}</div>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td class="text-center fw-bold">{{ $customer->orders_count }}</td>
                                                <td class="text-end text-primary font-monospace fw-bold">LKR {{ number_format($customer->total_spent, 2) }}</td>
                                            </tr>
                                        @empty
                                            <tr>
                                                <td colspan="3" class="text-center text-muted py-4">No top customers record yet</td>
                                            </tr>
                                        @endforelse
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Row 4.5: Web Traffic & SEO Analytics -->
            <div class="row g-4 mt-2">
                <!-- Website Traffic History (Line/Area Chart) -->
                <div class="col-lg-8">
                    <div class="card premium-card h-100">
                        <div class="card-body p-4">
                            <h5 class="card-title mb-4"><i class="bi bi-graph-up text-primary me-2"></i>Website Traffic History (Last 30 Days)</h5>
                            <div id="trafficSourceHistoryChart" class="chart-container" style="min-height: 300px;"></div>
                        </div>
                    </div>
                </div>

                <!-- Top Referring Websites & SEO Verification -->
                <div class="col-lg-4">
                    <div class="card premium-card h-100">
                        <div class="card-body p-4 d-flex flex-column justify-content-between">
                            <div>
                                <h5 class="card-title mb-3"><i class="bi bi-link-45deg text-success me-2"></i>Top Referring Domains</h5>
                                <div class="table-responsive">
                                    <table class="table table-sm table-borderless table-premium mb-4">
                                        <thead>
                                            <tr>
                                                <th>Referrer Domain</th>
                                                <th class="text-end">Visits</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @forelse($topReferrers as $ref)
                                                <tr>
                                                    <td class="fw-semibold">
                                                        <i class="bi bi-globe2 text-secondary me-2"></i>{{ $ref->host }}
                                                    </td>
                                                    <td class="text-end fw-bold text-success">{{ $ref->count }}</td>
                                                </tr>
                                            @empty
                                                <tr>
                                                    <td colspan="2" class="text-center text-muted small py-3">No external referrer logs</td>
                                                </tr>
                                            @endforelse
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <!-- SEO Health Summary -->
                            <div class="p-3 rounded-4 border bg-light">
                                <span class="stat-label text-secondary mb-3 d-block">SEO Indexing Files</span>
                                <div class="d-flex align-items-center justify-content-between mb-2">
                                    <span class="small text-muted"><i class="bi bi-file-earmark-code me-2"></i>robots.txt</span>
                                    @if($robotsExists)
                                        <span class="badge bg-success-light text-success"><i class="bi bi-check-circle me-1"></i>Active</span>
                                    @else
                                        <span class="badge bg-danger-light text-danger"><i class="bi bi-x-circle me-1"></i>Missing</span>
                                    @endif
                                </div>
                                <div class="d-flex align-items-center justify-content-between">
                                    <span class="small text-muted"><i class="bi bi-file-earmark-xml me-2"></i>sitemap.xml</span>
                                    @if($sitemapExists)
                                        <span class="badge bg-success-light text-success"><i class="bi bi-check-circle me-1"></i>Active</span>
                                    @else
                                        <span class="badge bg-warning-light text-warning"><i class="bi bi-exclamation-circle me-1"></i>Pending</span>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Row 4.6: Search Engine Ranking Analytics -->
            <div class="row g-4 mt-2">
                <!-- Google Search Console Query Ranking Simulator -->
                <div class="col-12">
                    <div class="card premium-card">
                        <div class="card-body p-4">
                            <h5 class="card-title mb-4"><i class="bi bi-search text-warning me-2"></i>Organic SEO Search Rankings (Google Search Console Simulator)</h5>
                            <div class="table-responsive">
                                <table class="table table-borderless table-premium align-middle mb-0">
                                    <thead>
                                        <tr>
                                            <th>Search Query Keyword</th>
                                            <th class="text-center">Clicks</th>
                                            <th class="text-center">Impressions</th>
                                            <th class="text-center">Average CTR</th>
                                            <th class="text-center">Avg. Position</th>
                                            <th class="text-end">SEO Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @foreach($seoKeywords as $keyword)
                                            <tr>
                                                <td class="fw-bold text-dark"><i class="bi bi-key-fill text-muted me-2"></i>{{ $keyword['keyword'] }}</td>
                                                <td class="text-center">{{ number_format($keyword['clicks']) }}</td>
                                                <td class="text-center">{{ number_format($keyword['impressions']) }}</td>
                                                <td class="text-center text-primary fw-semibold">{{ $keyword['ctr'] }}%</td>
                                                <td class="text-center text-warning fw-bold">{{ $keyword['position'] }}</td>
                                                <td class="text-end">
                                                    @if($keyword['position'] <= 2.0)
                                                        <span class="badge bg-success-light text-success"><i class="bi bi-star-fill me-1"></i>Top Ranking</span>
                                                    @elseif($keyword['position'] <= 4.0)
                                                        <span class="badge bg-primary-light text-primary"><i class="bi bi-arrow-up-right me-1"></i>Page 1</span>
                                                    @else
                                                        <span class="badge bg-warning-light text-warning">Good Growth</span>
                                                    @endif
                                                </td>
                                            </tr>
                                        @endforeach
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Row 5: Best Selling Products & System Logs -->
            <div class="row g-4 mt-2 mb-4">
                <!-- Best Selling Products -->
                <div class="col-lg-8">
                    <div class="card premium-card h-100">
                        <div class="card-body p-4">
                            <h5 class="card-title mb-4"><i class="bi bi-box-seam text-primary me-2"></i>Best Selling Products</h5>
                            <div class="table-responsive" style="max-height: 480px; overflow-y: auto;">
                                <table class="table table-borderless table-premium align-middle mb-0">
                                    <thead>
                                        <tr>
                                            <th>Product Details</th>
                                            <th class="text-center">Units Sold</th>
                                            <th class="text-end">Revenue Generated</th>
                                            <th class="text-center">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        @forelse($topsellingproduct as $product)
                                            @php
                                                $images = explode(',', $product->product_image);
                                                $firstImg = count($images) > 0 ? $images[0] : '';
                                                $displayImg = !empty($product->color_image) ? $product->color_image : $firstImg;
                                            @endphp
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        @if(!empty($displayImg))
                                                            <img src="{{ asset('admin/assets/img/product/' . $displayImg) }}" class="product-img me-3" alt="">
                                                        @else
                                                            <div class="product-img me-3 bg-light d-flex align-items-center justify-content-center text-muted" style="border: 1px solid #ddd;"><i class="bi bi-image"></i></div>
                                                        @endif
                                                        <div>
                                                            <div class="fw-bold text-dark small">{{ $product->product_name }}</div>
                                                            <div class="d-flex align-items-center gap-2 mt-1">
                                                                <span class="text-muted" style="font-size: 0.7rem;">SKU: {{ $product->sku }}</span>
                                                                @if($product->color)
                                                                    <span style="display: inline-block; width: 10px; height: 10px; background-color: {{ $product->color }}; border: 1px solid #ddd; border-radius: 50%;" title="{{ $product->color }}"></span>
                                                                @endif
                                                            </div>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td class="text-center fw-bold">{{ number_format($product->units_sold) }}</td>
                                                <td class="text-end text-primary font-monospace fw-semibold">LKR {{ number_format($product->revenue, 2) }}</td>
                                                <td class="text-center"><span class="badge bg-success-light text-success">Active</span></td>
                                            </tr>
                                        @empty
                                            <tr>
                                                <td colspan="4" class="text-center text-muted py-4">No best sellers yet</td>
                                            </tr>
                                        @endforelse
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Recent Activity Logs -->
                <div class="col-lg-4">
                    <div class="card premium-card h-100">
                        <div class="card-body p-4">
                            <h5 class="card-title mb-4"><i class="bi bi-clock-history text-secondary me-2"></i>System Log Activity</h5>
                            <div class="activity">
                                @php
                                    $notifications = App\Models\Systemlog::orderBy('created_at', 'desc')->take(6)->get();
                                @endphp
                                @forelse($notifications as $notification)
                                    <div class="activity-item d-flex mb-3">
                                        <div class="activite-label text-muted small" style="width: 75px; flex-shrink: 0;">{{ $notification->created_at->diffForHumans(null, true) }}</div>
                                        <i class='bi bi-circle-fill activity-badge text-primary align-self-start mx-2' style="font-size: 8px; margin-top: 6px;"></i>
                                        <div class="activity-content small">
                                            <span class="text-dark">{{ $notification->message }}</span>
                                        </div>
                                    </div>
                                @empty
                                    <p class="text-muted small text-center py-4">No recent activity logs</p>
                                @endforelse
                            </div>
                            <div class="text-center mt-3 pt-3 border-top">
                                <a href="{{ route('american.plastic.admin.system.log') }}" class="btn btn-sm btn-outline-primary">View All System Logs</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Charts Initialization -->
        <script>
            document.addEventListener("DOMContentLoaded", () => {
                // ApexCharts Shared Theme Options
                const chartTheme = {
                    fontFamily: "'Poppins', sans-serif"
                };

                // 1. Daily Sales Chart (Area Chart)
                new ApexCharts(document.querySelector("#dailySalesChart"), {
                    series: [
                        { name: 'Revenue (LKR)', data: @json($dailyRevenue) },
                        { name: 'Orders Count', data: @json($dailyOrders) }
                    ],
                    chart: { 
                        height: 350, 
                        type: 'area', 
                        fontFamily: chartTheme.fontFamily,
                        toolbar: { show: true }, 
                        zoom: { enabled: false } 
                    },
                    colors: ['#4154f1', '#2eca6a'],
                    fill: { 
                        type: 'gradient', 
                        gradient: { 
                            shadeIntensity: 1, 
                            opacityFrom: [0.4, 0.2], 
                            opacityTo: [0.1, 0.05], 
                            stops: [0, 90, 100] 
                        } 
                    },
                    dataLabels: { enabled: false },
                    stroke: { curve: 'smooth', width: [3, 2] },
                    xaxis: { 
                        categories: @json($dailyLabels),
                        axisBorder: { show: false } 
                    },
                    yaxis: [
                        {
                            title: { text: 'Revenue (LKR)', style: { color: '#4154f1' } },
                            labels: { 
                                formatter: (val) => 'Rs.' + val.toLocaleString(),
                                style: { colors: '#4154f1' }
                            }
                        },
                        {
                            opposite: true,
                            title: { text: 'Orders Count', style: { color: '#2eca6a' } },
                            labels: { 
                                formatter: (val) => Math.round(val),
                                style: { colors: '#2eca6a' }
                            }
                        }
                    ],
                    tooltip: { x: { format: 'dd MMM' } }
                }).render();

                // 2. Monthly Sales Chart (Bar Chart)
                new ApexCharts(document.querySelector("#monthlySalesChart"), {
                    series: [
                        { name: 'Revenue (LKR)', data: @json($monthlyRevenue) },
                        { name: 'Orders Count', data: @json($monthlyOrders) }
                    ],
                    chart: { 
                        height: 350, 
                        type: 'bar', 
                        fontFamily: chartTheme.fontFamily,
                        toolbar: { show: true } 
                    },
                    colors: ['#4154f1', '#ff771d'],
                    plotOptions: { 
                        bar: { 
                            horizontal: false, 
                            columnWidth: '55%', 
                            borderRadius: 4 
                        } 
                    },
                    dataLabels: { enabled: false },
                    xaxis: { categories: @json($monthlyLabels) },
                    yaxis: [
                        {
                            title: { text: 'Revenue (LKR)', style: { color: '#4154f1' } },
                            labels: { formatter: (val) => 'Rs.' + val.toLocaleString() }
                        },
                        {
                            opposite: true,
                            title: { text: 'Orders Count', style: { color: '#ff771d' } },
                            labels: { formatter: (val) => Math.round(val) }
                        }
                    ],
                    tooltip: { y: { formatter: (val) => val.toLocaleString() } }
                }).render();

                // 3. Yearly Sales Chart (Line/Area Chart)
                new ApexCharts(document.querySelector("#yearlySalesChart"), {
                    series: [
                        { name: 'Revenue (LKR)', data: @json($yearlyRevenue) },
                        { name: 'Orders Count', data: @json($yearlyOrders) }
                    ],
                    chart: { 
                        height: 350, 
                        type: 'line', 
                        fontFamily: chartTheme.fontFamily,
                        toolbar: { show: true } 
                    },
                    colors: ['#6f42c1', '#0dcaf0'],
                    stroke: { width: [4, 3], curve: 'smooth' },
                    dataLabels: { enabled: false },
                    xaxis: { categories: @json($yearlyLabels) },
                    yaxis: [
                        {
                            title: { text: 'Revenue (LKR)', style: { color: '#6f42c1' } },
                            labels: { formatter: (val) => 'Rs.' + val.toLocaleString() }
                        },
                        {
                            opposite: true,
                            title: { text: 'Orders Count', style: { color: '#0dcaf0' } },
                            labels: { formatter: (val) => Math.round(val) }
                        }
                    ],
                    tooltip: { y: { formatter: (val) => val.toLocaleString() } }
                }).render();

                // 4. Payment Methods Stats Donut Chart
                @php
                    $payLabels = [];
                    $paySales = [];
                    foreach($paymentStats as $st) {
                        $method = strtolower($st->payment_method);
                        $lbl = $methodNames[$method] ?? ucfirst($st->payment_method);
                        $payLabels[] = $lbl;
                        $paySales[] = (float)$st->total_sales;
                    }
                @endphp
                new ApexCharts(document.querySelector("#paymentStatsChart"), {
                    series: @json($paySales),
                    labels: @json($payLabels),
                    chart: { 
                        type: 'donut', 
                        height: 250, 
                        fontFamily: chartTheme.fontFamily 
                    },
                    colors: ['#4154f1', '#2eca6a', '#ff771d', '#0dcaf0', '#6f42c1'],
                    legend: { position: 'bottom' },
                    plotOptions: { 
                        pie: { 
                            donut: { 
                                size: '65%', 
                                labels: { 
                                    show: true, 
                                    total: { 
                                        show: true, 
                                        label: 'Total Sales', 
                                        formatter: (w) => {
                                            const total = w.globals.seriesTotals.reduce((a, b) => a + b, 0);
                                            return 'Rs.' + total.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
                                        }
                                    } 
                                } 
                            } 
                        } 
                    },
                    tooltip: {
                        y: {
                            formatter: (val) => 'Rs.' + val.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})
                        }
                    },
                    dataLabels: { enabled: false }
                }).render();

                // 5. Category Sales Pie/Donut Chart
                new ApexCharts(document.querySelector("#categorySalesChart"), {
                    series: @json($salesByCategory->pluck('sales')),
                    labels: @json($salesByCategory->pluck('category_name')),
                    chart: { 
                        type: 'pie', 
                        height: 250,
                        fontFamily: chartTheme.fontFamily 
                    },
                    colors: ['#0dcaf0', '#6f42c1', '#ff771d', '#4154f1', '#2eca6a', '#343a40'],
                    legend: { position: 'bottom' },
                    dataLabels: { enabled: false }
                }).render();

                // 6. City Sales Bar Chart
                new ApexCharts(document.querySelector("#citySalesChart"), {
                    series: [{
                        name: 'Sales (LKR)',
                        data: @json($salesByCity->pluck('sales'))
                    }],
                    chart: {
                        type: 'bar',
                        height: 230,
                        fontFamily: chartTheme.fontFamily,
                        toolbar: { show: false }
                    },
                    colors: ['#dc3545'],
                    plotOptions: {
                        bar: {
                            borderRadius: 4,
                            horizontal: true,
                        }
                    },
                    dataLabels: { enabled: false },
                    xaxis: {
                        categories: @json($salesByCity->pluck('city')),
                        labels: { formatter: (val) => 'Rs.' + Math.round(val).toLocaleString() }
                    }
                }).render();

                // 7. District Sales Bar Chart
                new ApexCharts(document.querySelector("#districtSalesChart"), {
                    series: [{
                        name: 'Sales (LKR)',
                        data: @json($salesByDistrict->pluck('sales'))
                    }],
                    chart: {
                        type: 'bar',
                        height: 230,
                        fontFamily: chartTheme.fontFamily,
                        toolbar: { show: false }
                    },
                    colors: ['#6f42c1'],
                    plotOptions: {
                        bar: {
                            borderRadius: 4,
                            horizontal: true,
                        }
                    },
                    dataLabels: { enabled: false },
                    xaxis: {
                        categories: @json($salesByDistrict->pluck('district')),
                        labels: { formatter: (val) => 'Rs.' + Math.round(val).toLocaleString() }
                    }
                }).render();

                // 8. Website Traffic History Line Chart
                new ApexCharts(document.querySelector("#trafficSourceHistoryChart"), {
                    series: [
                        { name: 'Direct Traffic', data: @json($directSeries) },
                        { name: 'Search Engine', data: @json($searchSeries) },
                        { name: 'Social/Video', data: @json($videoSeries) },
                        { name: 'Paid Ads', data: @json($adSeries) }
                    ],
                    chart: {
                        height: 300,
                        type: 'line',
                        fontFamily: chartTheme.fontFamily,
                        toolbar: { show: true }
                    },
                    colors: ['#4154f1', '#2eca6a', '#ff771d', '#012970'],
                    stroke: { curve: 'smooth', width: 3 },
                    xaxis: {
                        categories: @json($trafficSourceLabels)
                    },
                    yaxis: {
                        title: { text: 'Visitor Count' }
                    },
                    tooltip: { y: { formatter: (val) => val + " visits" } }
                }).render();
            });
        </script>

    </main><!-- End #main -->
@endsection
