

<?php $__env->startSection('title', 'Dashboard'); ?>

<?php $__env->startSection('content'); ?>
<div class="admin-page-header d-flex justify-content-between align-items-center">
    <div>
        <h1>Dashboard</h1>
        <p class="admin-page-subtitle mb-0">Welcome back. Here's what's happening today.</p>
    </div>
    <div>
        <span class="text-muted">Last updated: <?php echo e(now()->format('M d, Y h:i A')); ?></span>
    </div>
</div>
<?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('dashboard.view-kpis')): ?>
<!-- Key Performance Indicators -->
<div class="row g-4 mb-4">
    <!-- Orders Today -->
    <div class="col-md-6 col-lg-4 col-xl-3">
        <div class="kpi-card">
            <div class="kpi-card-icon kpi-card-icon-primary">
                <i class="bi bi-cart-check"></i>
            </div>
            <div class="kpi-card-content-wrapper">
                <div class="kpi-card-value">₹<?php echo e(number_format($todaySales, 2)); ?></div>
                <div class="kpi-card-label">Orders Today</div>
                <div class="kpi-card-trend kpi-card-trend-up">
                    <i class="bi bi-arrow-up"></i>
                    <span><?php echo e($todayOrders); ?> orders</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Pending Orders -->
    <div class="col-md-6 col-lg-4 col-xl-3">
        <div class="kpi-card">
            <div class="kpi-card-icon kpi-card-icon-warning">
                <i class="bi bi-clock-history"></i>
            </div>
            <div class="kpi-card-content-wrapper">
                <div class="kpi-card-value"><?php echo e($pendingOrders ?? 0); ?></div>
                <div class="kpi-card-label">Placed Orders</div>
                <div class="kpi-card-trend kpi-card-trend-warning">
                    <i class="bi bi-exclamation-circle"></i>
                    <span>Needs attention</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Revenue -->
    <div class="col-md-6 col-lg-4 col-xl-3">
        <div class="kpi-card">
            <div class="kpi-card-icon kpi-card-icon-success">
                <i class="bi bi-currency-rupee"></i>
            </div>
            <div class="kpi-card-content-wrapper">
                <div class="kpi-card-value">₹<?php echo e(number_format($monthSales, 2)); ?></div>
                <div class="kpi-card-label">Revenue (MTD)</div>
                <div class="kpi-card-trend <?php echo e($salesGrowth > 0 ? 'kpi-card-trend-up' : ($salesGrowth < 0 ? 'kpi-card-trend-down' : 'kpi-card-trend-neutral')); ?>">
                    <?php if($salesGrowth > 0): ?>
                        <i class="bi bi-arrow-up"></i>
                        <span>+<?php echo e(number_format($salesGrowth, 1)); ?>% vs last month</span>
                    <?php elseif($salesGrowth < 0): ?>
                        <i class="bi bi-arrow-down"></i>
                        <span><?php echo e(number_format($salesGrowth, 1)); ?>% vs last month</span>
                    <?php else: ?>
                        <span>No change</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Low Stock Items -->
    <div class="col-md-6 col-lg-4 col-xl-3">
        <div class="kpi-card">
            <div class="kpi-card-icon kpi-card-icon-warning">
                <i class="bi bi-box-seam"></i>
            </div>
            <div class="kpi-card-content-wrapper">
                <div class="kpi-card-value"><?php echo e($lowStockProducts ?? 0); ?></div>
                <div class="kpi-card-label">Low Stock Items</div>
                <div class="kpi-card-trend kpi-card-trend-warning">
                    <i class="bi bi-exclamation-circle"></i>
                    <span>Restock needed</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Today's Profit -->
    <div class="col-md-6 col-lg-4 col-xl-3">
        <div class="kpi-card">
            <div class="kpi-card-icon kpi-card-icon-success">
                <i class="bi bi-graph-up-arrow"></i>
            </div>
            <div class="kpi-card-content-wrapper">
                <div class="kpi-card-value">₹<?php echo e(number_format($todayProfitData['total_profit'] ?? 0, 2)); ?></div>
                <div class="kpi-card-label">Today's Profit</div>
                <div class="kpi-card-trend <?php echo e(($todayProfitData['profit_margin_percent'] ?? 0) > 0 ? 'kpi-card-trend-up' : 'kpi-card-trend-neutral'); ?>">
                    <?php if(($todayProfitData['profit_margin_percent'] ?? 0) > 0): ?>
                        <i class="bi bi-check-circle"></i>
                        <span><?php echo e(number_format($todayProfitData['profit_margin_percent'] ?? 0, 1)); ?>% margin</span>
                    <?php else: ?>
                        <span>No profit data</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Monthly Profit -->
    <div class="col-md-6 col-lg-4 col-xl-3">
        <div class="kpi-card">
            <div class="kpi-card-icon kpi-card-icon-info">
                <i class="bi bi-trophy"></i>
            </div>
            <div class="kpi-card-content-wrapper">
                <div class="kpi-card-value">₹<?php echo e(number_format($monthProfitData['total_profit'] ?? 0, 2)); ?></div>
                <div class="kpi-card-label">This Month Profit</div>
                <div class="kpi-card-trend <?php echo e(($monthProfitData['profit_margin_percent'] ?? 0) > 0 ? 'kpi-card-trend-up' : 'kpi-card-trend-neutral'); ?>">
                    <?php if(($monthProfitData['profit_margin_percent'] ?? 0) > 0): ?>
                        <i class="bi bi-check-circle"></i>
                        <span><?php echo e(number_format($monthProfitData['profit_margin_percent'] ?? 0, 1)); ?>% margin</span>
                    <?php else: ?>
                        <span>Add purchase prices</span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php
        $totalWhatsAppCount = $whatsApp->total_credits ?? 0;
        $usedWhatsAppCount = $whatsApp->used_credits ?? 0;
        $RemainingWhatsAppCount = max($totalWhatsAppCount - $usedWhatsAppCount, 0);

        $whatsAppbgcolor =  $RemainingWhatsAppCount < 500 ? ($RemainingWhatsAppCount < 100 ? 'danger' : 'warning') : 'white';
        $whatsAppcolor =  $RemainingWhatsAppCount < 100 ? 'white' : 'black';
    ?>
    <!-- fast 2 sms count -->
    <div class="col-md-6 col-lg-4 col-xl-3">
        <a href="<?php echo e(route('admin.whatsapp.credits')); ?>" target="_blank">
            <div class="kpi-card bg-<?php echo e($whatsAppbgcolor); ?>">
                <div class="kpi-card-icon kpi-card-icon-<?php echo e($RemainingWhatsAppCount < 100 ? 'info' : 'success'); ?>">
                    <i class="bi bi-whatsapp"></i>
                </div>
                <div class="kpi-card-content-wrapper">
                    <div class="kpi-card-value" style="color: <?php echo e($whatsAppcolor); ?>;"><?php echo e(number_format($RemainingWhatsAppCount ?? 0)); ?></div>
                    <div class="kpi-card-label" style="color: <?php echo e($whatsAppcolor); ?>;">WhatsApp Credits</div>
                    <div class="kpi-card-trend kpi-card-trend-neutral" style="color: <?php echo e($whatsAppcolor); ?>;">
                        <i class="bi bi-info-circle"></i>
                        <span>Used Credits: <?php echo e($usedWhatsAppCount); ?></span>
                    </div>
                </div>
            </div>
        </a>
    </div>
    <?php
        $SMScount = $SMScount ?? 0;
        $smsbgcolor =  $SMScount < 2000 ? ($SMScount < 500 ? 'danger' : 'warning') : 'white';
        $smscolor =  $SMScount < 500 ? 'white' : 'black';
    ?>
    <!-- fast 2 sms count -->
    <div class="col-md-6 col-lg-4 col-xl-3">
        <a href="<?php echo e($smsUrl); ?>" target="_blank">
            <div class="kpi-card bg-<?php echo e($smsbgcolor); ?>">
                <div class="kpi-card-icon kpi-card-icon-<?php echo e($SMScount < 500 ? 'info' : 'warning'); ?>">
                    <i class="bi bi-envelope"></i>
                </div>
                <div class="kpi-card-content-wrapper">
                    <div class="kpi-card-value" style="color: <?php echo e($smscolor); ?>;"><?php echo e(number_format($SMScount ?? 0)); ?></div>
                    <div class="kpi-card-label" style="color: <?php echo e($smscolor); ?>;">SMS Credits</div>
                    <div class="kpi-card-trend kpi-card-trend-neutral" style="color: <?php echo e($smscolor); ?>;">
                        <i class="bi bi-info-circle"></i>
                        <span>Wallet: ₹<?php echo e($SmsWallet); ?></span>
                    </div>
                </div>
            </div>
        </a>
    </div>
</div>

<!-- Business Overview Cards -->
<div class="row g-4 mb-4">
    <!-- Total Revenue -->
    <div class="col-md-4 col-lg-4 col-xl-4 col-6">
        <div class="admin-stat-card stat-secondary">
            <div class="stat-icon">
                <i class="bi bi-cash-stack"></i>
            </div>
            <div class="stat-label"><div class="stat-value">₹<?php echo e(number_format($totalRevenue, 0)); ?></div>Total Revenue</div>
            <!-- <div class="stat-meta"><?php echo e($totalOrders); ?> orders</div> -->
        </div>
    </div>

    <!-- Total COGS -->
    <div class="col-md-4 col-lg-4 col-xl-4 col-6">
        <div class="admin-stat-card stat-danger">
            <div class="stat-icon">
                <i class="bi bi-box"></i>
            </div>
            <div class="stat-label"><div class="stat-value">₹<?php echo e(number_format($totalProfitData['total_cogs'] ?? 0, 0)); ?></div>Total COGS</div>            
            <!-- <div class="stat-meta">Cost of goods sold</div> -->
        </div>
    </div>

    <!-- Total Profit -->
    <div class="col-md-4 col-lg-4 col-xl-4 col-6">
        <div class="admin-stat-card stat-success">
            <div class="stat-icon">
                <i class="bi bi-graph-up-arrow"></i>
            </div>
            <div class="stat-label"><div class="stat-value">₹<?php echo e(number_format($totalProfitData['total_profit'] ?? 0, 0)); ?></div>Total Profit</div>            
            <!-- <div class="stat-meta">
                <?php if(($totalProfitData['profit_margin_percent'] ?? 0) > 0): ?>
                    <?php echo e(number_format($totalProfitData['profit_margin_percent'] ?? 0, 1)); ?>% margin
                <?php else: ?>
                    <span class="text-muted">-</span>
                <?php endif; ?>
            </div> -->
        </div>
    </div>

    <!-- Average Order Value -->
    <div class="col-md-4 col-lg-4 col-xl-4 col-6">
        <div class="admin-stat-card stat-primary">
            <div class="stat-icon">
                <i class="bi bi-calculator"></i>
            </div>
            <div class="stat-label"><div class="stat-value">₹<?php echo e(number_format($avgOrderValue, 0)); ?></div>Avg Order Value</div>
            <!-- <div class="stat-meta">Per order</div> -->
        </div>
    </div>

    <!-- Total Customers -->
    <div class="col-md-4 col-lg-4 col-xl-4 col-6">
        <div class="admin-stat-card stat-info">
            <div class="stat-icon">
                <i class="bi bi-people"></i>
            </div>
            <div class="stat-label"><div class="stat-value"><?php echo e(number_format($totalCustomers)); ?></div>Total Customers</div>            
            <!-- <div class="stat-meta">Active users</div> -->
        </div>
    </div>

    <!-- Products -->
    <div class="col-md-4 col-lg-4 col-xl-4 col-6">
        <div class="admin-stat-card stat-warning">
            <div class="stat-icon">
                <i class="bi bi-box-seam"></i>
            </div>
            <div class="stat-label"><div class="stat-value"><?php echo e(number_format($totalProducts)); ?></div>Products</div>            
            <!-- <div class="stat-meta"><?php echo e($activeProducts); ?> active</div> -->
        </div>
    </div>
</div>
<?php endif; ?>
<?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('dashboard.view-dashlets')): ?>
<!-- Purchase Price Coverage Alert -->
<?php if($purchasePriceCoverage < 100): ?>
<div class="alert alert-warning mb-4">
    <div class="row align-items-center">
        <div class="col-md-8">
            <i class="bi bi-exclamation-triangle"></i>
            <strong>Purchase Price Coverage: <?php echo e($purchasePriceCoverage); ?>%</strong>
            <span class="ms-2"><?php echo e($productsMissingPurchasePrice); ?> products are missing purchase prices, affecting profit calculations.</span>
        </div>
        <div class="col-md-4 text-end">
            <a href="<?php echo e(route('admin.reports.missing-purchase-price')); ?>" class="btn btn-warning btn-sm">
                <i class="bi bi-plus"></i> Add Purchase Prices
            </a>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Charts Section -->
<div class="row mb-4">
    <!-- Revenue & Profit Trend -->
    <div class="col-md-8">
        <div class="admin-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Revenue & Profit Trend (Last 7 Days)</h5>
                <div class="btn-group btn-group-sm" role="group">
                    <button type="button" class="btn btn-outline-primary active" onclick="switchChart('7')">7 Days</button>
                    <button type="button" class="btn btn-outline-primary" onclick="switchChart('30')">30 Days</button>
                </div>
            </div>
            <div class="card-body">
                <div style="height: 400px; position: relative;">
                    <canvas id="businessChart"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions & Alerts -->
    <div class="col-md-4">
        <div class="admin-card">
            <div class="card-header">
                <h5 class="mb-0">Quick Actions</h5>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <a href="<?php echo e(route('admin.reports.profit')); ?>" class="btn btn-success">
                        <i class="bi bi-graph-up"></i> View Profit Reports
                    </a>
                    <a href="<?php echo e(route('admin.products.purchase-prices.import')); ?>" class="btn btn-warning">
                        <i class="bi bi-upload"></i> Import Purchase Prices
                    </a>
                    <a href="<?php echo e(route('admin.orders.index')); ?>" class="btn btn-primary">
                        <i class="bi bi-receipt"></i> Manage Orders
                    </a>
                    <?php if($lowStockProducts > 0): ?>
                        <a href="<?php echo e(route('admin.products.restock')); ?>" class="btn btn-danger">
                            <i class="bi bi-exclamation-triangle"></i> Restock (<?php echo e($lowStockProducts); ?>)
                        </a>
                    <?php endif; ?>
                </div>

                <!-- Alerts -->
                <div class="mt-3">
                    <h6 class="text-muted">Alerts</h6>
                    <?php if($pendingOrders > 0): ?>
                        <div class="alert alert-warning alert-sm">
                            <i class="bi bi-clock"></i> <?php echo e($pendingOrders); ?> pending orders
                        </div>
                    <?php endif; ?>
                    <?php if($lowStockProducts > 0): ?>
                        <div class="alert alert-danger alert-sm">
                            <i class="bi bi-box"></i> <?php echo e($lowStockProducts); ?> low stock items
                        </div>
                    <?php endif; ?>
                    <?php if($productsMissingPurchasePrice > 0): ?>
                        <div class="alert alert-info alert-sm">
                            <i class="bi bi-info-circle"></i> <?php echo e($productsMissingPurchasePrice); ?> products need purchase prices
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Salesman Performance Line Chart -->
<?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('reports.salesman')): ?>
<div class="row mb-4">
    <div class="col-12">
        <div class="admin-card">
            <div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
                <h5 class="mb-0"><i class="bi bi-people"></i> Salesman Performance (POS Sales)</h5>
                <div class="d-flex flex-wrap align-items-center gap-2">
                    <div class="btn-group btn-group-sm" role="group" id="salesmanPeriodGroup">
                        <button type="button" class="btn btn-outline-primary" data-period="day">Day</button>
                        <button type="button" class="btn btn-outline-primary active" data-period="week">Week</button>
                        <button type="button" class="btn btn-outline-primary" data-period="month">Month</button>
                        <button type="button" class="btn btn-outline-primary" data-period="year">Year</button>
                        <button type="button" class="btn btn-outline-primary" data-period="custom">Custom</button>
                    </div>
                    <div id="salesmanCustomRange" class="d-none d-flex align-items-end gap-2 flex-wrap">
                        <div>
                            <label class="form-label small mb-0">Start</label>
                            <input type="date" id="salesmanStartDate" class="form-control form-control-sm" style="width: 140px;">
                        </div>
                        <div>
                            <label class="form-label small mb-0">End</label>
                            <input type="date" id="salesmanEndDate" class="form-control form-control-sm" style="width: 140px;">
                        </div>
                        <button type="button" class="btn btn-sm btn-primary" id="salesmanApplyCustom">Apply</button>
                    </div>
                    <a href="<?php echo e(route('admin.reports.salesman')); ?>" class="btn btn-sm btn-outline-secondary">Full Report</a>
                </div>
            </div>
            <div class="card-body">
                <div style="height: 360px; position: relative;">
                    <canvas id="salesmanChart"></canvas>
                </div>
                <div id="salesmanChartEmpty" class="text-center py-5 text-muted d-none">
                    <i class="bi bi-graph-up" style="font-size: 2.5rem;"></i>
                    <p class="mb-0 mt-2">No POS sales data for the selected period.</p>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Business Insights -->
<div class="row mb-4">
    <!-- Top Profitable Products -->
    <div class="col-md-6">
        <div class="admin-card">
            <div class="card-header">
                <h5 class="mb-0">Top Profitable Products (Last 30 Days)</h5>
            </div>
            <div class="card-body">
                <?php if(isset($topProfitableProducts['most_profitable']) && $topProfitableProducts['most_profitable']->count() > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-sm table-hover mb-0">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>Sold</th>
                                    <th>Profit</th>
                                    <th>Margin</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $__currentLoopData = $topProfitableProducts['most_profitable']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo e($item['product_name'] ?? 'Unknown Product'); ?></strong><br>
                                            <small class="text-muted"><?php echo e($item['sku'] ?? 'N/A'); ?></small>
                                        </td>
                                        <td><span class="badge bg-secondary"><?php echo e($item['units_sold'] ?? 0); ?></span></td>
                                        <td class="text-success"><strong>₹<?php echo e(number_format($item['gross_profit'] ?? 0, 0)); ?></strong></td>
                                        <td>
                                            <span class="badge bg-success"><?php echo e(number_format($item['margin_percent'] ?? 0, 1)); ?>%</span>
                                        </td>
                                    </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <div class="text-center py-4">
                        <i class="bi bi-graph-down text-muted" style="font-size: 2.5rem;"></i>
                        <h6 class="text-muted mt-3 mb-2">No Profitable Products Data</h6>
                        <p class="text-muted small mb-3">
                            <?php if($purchasePriceCoverage < 100): ?>
                                <?php echo e($productsMissingPurchasePrice); ?> products are missing purchase prices.
                            <?php else: ?>
                                No sales with profit data found in the last 30 days.
                            <?php endif; ?>
                        </p>
                        <div class="d-flex gap-2 justify-content-center">
                            <?php if($purchasePriceCoverage < 100): ?>
                                <a href="<?php echo e(route('admin.products.purchase-prices.import')); ?>" class="btn btn-sm btn-warning">
                                    <i class="bi bi-upload"></i> Add Purchase Prices
                                </a>
                            <?php endif; ?>
                            <a href="<?php echo e(route('admin.reports.profit')); ?>" class="btn btn-sm btn-outline-primary">
                                <i class="bi bi-graph-up"></i> View Full Report
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Top Selling Products -->
    <div class="col-md-6">
        <div class="admin-card">
            <div class="card-header">
                <h5 class="mb-0">Top Selling Products (Last 30 Days)</h5>
            </div>
            <div class="card-body">
                <?php if($topProducts->count() > 0): ?>
                    <div class="table-responsive">
                        <table class="table table-sm table-hover mb-0">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>Sold</th>
                                    <th>Revenue</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $__currentLoopData = $topProducts; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <?php if($item->product && ($item->product->image_path || $item->product->image)): ?>
                                                    <?php if (isset($component)) { $__componentOriginala58dde406db9207f2e2c58e1c4a3d690 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginala58dde406db9207f2e2c58e1c4a3d690 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'components.product-image','data' => ['product' => $item->product,'context' => 'listing','alt' => ''.e($item->product->name).'','class' => 'me-2','style' => 'width: 30px; height: 30px; object-fit: cover; border-radius: 4px;']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('product-image'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['product' => \Illuminate\View\Compilers\BladeCompiler::sanitizeComponentAttribute($item->product),'context' => 'listing','alt' => ''.e($item->product->name).'','class' => 'me-2','style' => 'width: 30px; height: 30px; object-fit: cover; border-radius: 4px;']); ?>
<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginala58dde406db9207f2e2c58e1c4a3d690)): ?>
<?php $attributes = $__attributesOriginala58dde406db9207f2e2c58e1c4a3d690; ?>
<?php unset($__attributesOriginala58dde406db9207f2e2c58e1c4a3d690); ?>
<?php endif; ?>
<?php if (isset($__componentOriginala58dde406db9207f2e2c58e1c4a3d690)): ?>
<?php $component = $__componentOriginala58dde406db9207f2e2c58e1c4a3d690; ?>
<?php unset($__componentOriginala58dde406db9207f2e2c58e1c4a3d690); ?>
<?php endif; ?>
                                                <?php endif; ?>
                                                <span><?php echo e($item->product->name ?? 'N/A'); ?></span>
                                            </div>
                                        </td>
                                        <td><strong><?php echo e($item->total_sold); ?></strong></td>
                                        <td>₹<?php echo e(number_format($item->total_revenue, 0)); ?></td>
                                    </tr>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </tbody>
                        </table>
                    </div>
                <?php else: ?>
                    <p class="text-muted mb-0">No sales data available</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script src="<?php echo e(asset('js/vendor/chart.umd.min.js')); ?>"></script>
<script>
let businessChart = null;
const businessCtx = document.getElementById('businessChart');

// Data for charts
const revenueData7 = <?php echo json_encode($revenueData ?? [], 15, 512) ?>;
const revenueData30 = <?php echo json_encode($monthlyRevenueData ?? [], 15, 512) ?>;
const profitTrendData = <?php echo json_encode($profitTrendData ?? [], 15, 512) ?>;

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
}

function createBusinessChart(days) {
    if (!businessCtx) {
        console.error('Business chart canvas not found');
        return;
    }
    if (typeof Chart === 'undefined') {
        console.error('Chart.js not loaded');
        const ctx = businessCtx.getContext('2d');
        ctx.font = '14px Arial';
        ctx.fillStyle = '#6b7280';
        ctx.textAlign = 'center';
        ctx.fillText('Chart library failed to load', businessCtx.width / 2, businessCtx.height / 2);
        return;
    }

    try {
        if (businessChart) {
            businessChart.destroy();
        }
        
        let revenueData, profitData;
        const rev7 = Array.isArray(revenueData7) ? revenueData7 : [];
        const rev30 = Array.isArray(revenueData30) ? revenueData30 : [];
        const profitArr = Array.isArray(profitTrendData) ? profitTrendData : [];
        
        if (days === '7') {
            revenueData = rev7;
            profitData = profitArr.length ? profitArr.slice(-7) : [];
        } else {
            revenueData = rev30;
            profitData = profitArr;
        }

        // Ensure we have data to display
        if (revenueData.length === 0 && profitData.length === 0) {
            // Show empty state
            businessCtx.getContext('2d').clearRect(0, 0, businessCtx.width, businessCtx.height);
            const ctx = businessCtx.getContext('2d');
            ctx.font = '16px Arial';
            ctx.fillStyle = '#6b7280';
            ctx.textAlign = 'center';
            ctx.fillText('No data available for the selected period', businessCtx.width / 2, businessCtx.height / 2);
            return;
        }

        // Create a unified date range from both datasets
        const allDates = new Set();
        revenueData.forEach(d => allDates.add(d.date));
        profitData.forEach(d => allDates.add(d.date));
        const sortedDates = Array.from(allDates).sort();

        // Create data maps for easy lookup
        const revenueMap = new Map(revenueData.map(d => [d.date, d]));
        const profitMap = new Map(profitData.map(d => [d.date, d]));

        // Build aligned datasets
        const labels = sortedDates.map(date => formatDate(date));
        const revenueValues = sortedDates.map(date => {
            const item = revenueMap.get(date);
            return item ? parseFloat(item.revenue || 0) : 0;
        });
        const profitValues = sortedDates.map(date => {
            const item = profitMap.get(date);
            return item ? parseFloat(item.profit || 0) : 0;
        });
        const cogsValues = sortedDates.map(date => {
            const item = profitMap.get(date);
            return item ? parseFloat(item.cogs || 0) : 0;
        });
        
        businessChart = new Chart(businessCtx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'Revenue (₹)',
                        data: revenueValues,
                        borderColor: 'rgb(59, 130, 246)',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        tension: 0.4,
                        fill: false,
                        yAxisID: 'y'
                    },
                    {
                        label: 'Profit (₹)',
                        data: profitValues,
                        borderColor: 'rgb(16, 185, 129)',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        tension: 0.4,
                        fill: false,
                        yAxisID: 'y'
                    },
                    {
                        label: 'COGS (₹)',
                        data: cogsValues,
                        borderColor: 'rgb(239, 68, 68)',
                        backgroundColor: 'rgba(239, 68, 68, 0.1)',
                        tension: 0.4,
                        fill: false,
                        yAxisID: 'y'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    intersect: false,
                    mode: 'index'
                },
                plugins: {
                    legend: {
                        display: true,
                        position: 'top'
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const value = parseFloat(context.parsed.y || 0);
                                return context.dataset.label + ': ₹' + value.toLocaleString('en-IN', {
                                    minimumFractionDigits: 0,
                                    maximumFractionDigits: 0
                                });
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return '₹' + value.toLocaleString('en-IN');
                            }
                        }
                    },
                    x: {
                        display: true,
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    } catch (error) {
        console.error('Error creating business chart:', error);
        try {
            const ctx = businessCtx.getContext('2d');
            const w = businessCtx.width || 300;
            const h = businessCtx.height || 150;
            ctx.clearRect(0, 0, w, h);
            ctx.font = '14px Arial';
            ctx.fillStyle = '#ef4444';
            ctx.textAlign = 'center';
            ctx.fillText('Error loading chart data', w / 2, h / 2);
        } catch (e) {
            console.error('Could not draw error message:', e);
        }
    }
}

// Initialize charts when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    createBusinessChart('7');
});

function switchChart(days) {
    const buttons = document.querySelectorAll('.btn-group button');
    buttons.forEach(btn => btn.classList.remove('active'));
    event.target.classList.add('active');
    
    createBusinessChart(days);
}

// Salesman Performance Line Chart
const salesmanChartUrl = "<?php echo e(route('admin.dashboard.salesman-chart-data')); ?>";
let salesmanChartInstance = null;

function renderSalesmanChart(res) {
    const canvas = document.getElementById('salesmanChart');
    const emptyEl = document.getElementById('salesmanChartEmpty');
    if (!canvas) return;

    if (!res || !res.datasets || res.datasets.length === 0) {
        if (emptyEl) emptyEl.classList.remove('d-none');
        canvas.closest('div').style.display = 'none';
        return;
    }
    if (emptyEl) emptyEl.classList.add('d-none');
    canvas.closest('div').style.display = 'block';

    if (salesmanChartInstance) salesmanChartInstance.destroy();

    salesmanChartInstance = new Chart(canvas, {
        type: 'line',
        data: {
            labels: res.labels || [],
            datasets: (res.datasets || []).map(function(d) {
                return {
                    label: d.staff_name,
                    data: d.data || [],
                    borderColor: d.borderColor || 'rgb(59, 130, 246)',
                    backgroundColor: (d.backgroundColor || 'rgba(59, 130, 246, 0.1)'),
                    tension: 0.35,
                    fill: false
                };
            })
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: { intersect: false, mode: 'index' },
            plugins: {
                legend: { display: true, position: 'top' },
                tooltip: {
                    callbacks: {
                        label: function(ctx) {
                            const v = parseFloat(ctx.parsed?.y ?? 0);
                            return (ctx.dataset.label || '') + ': ₹' + v.toLocaleString('en-IN', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(v) { return '₹' + Number(v).toLocaleString('en-IN'); }
                    }
                },
                x: { grid: { display: false } }
            }
        }
    });
}

function loadSalesmanChart(period, startDate, endDate) {
    const params = new URLSearchParams({ period: period || 'week' });
    if (startDate) params.set('start_date', startDate);
    if (endDate) params.set('end_date', endDate);
    fetch(salesmanChartUrl + '?' + params.toString(), {
        headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' }
    })
        .then(function(r) { return r.json(); })
        .then(function(data) { renderSalesmanChart(data); })
        .catch(function() { renderSalesmanChart(null); });
}

function initSalesmanChart() {
    const group = document.getElementById('salesmanPeriodGroup');
    const customRange = document.getElementById('salesmanCustomRange');
    const startInput = document.getElementById('salesmanStartDate');
    const endInput = document.getElementById('salesmanEndDate');
    const applyBtn = document.getElementById('salesmanApplyCustom');

    if (!group) return;

    var today = new Date();
    var weekAgo = new Date(today);
    weekAgo.setDate(weekAgo.getDate() - 6);
    if (startInput) startInput.value = weekAgo.toISOString().slice(0, 10);
    if (endInput) endInput.value = today.toISOString().slice(0, 10);

    group.querySelectorAll('[data-period]').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var period = this.getAttribute('data-period');
            group.querySelectorAll('[data-period]').forEach(function(b) { b.classList.remove('active'); });
            this.classList.add('active');
            if (period === 'custom') {
                if (customRange) customRange.classList.remove('d-none');
                if (startInput && endInput) loadSalesmanChart('custom', startInput.value, endInput.value);
            } else {
                if (customRange) customRange.classList.add('d-none');
                loadSalesmanChart(period);
            }
        });
    });

    if (applyBtn && startInput && endInput) {
        applyBtn.addEventListener('click', function() {
            loadSalesmanChart('custom', startInput.value, endInput.value);
        });
    }

    loadSalesmanChart('week');
}

document.addEventListener('DOMContentLoaded', function() {
    if (document.getElementById('salesmanChart')) initSalesmanChart();
});
</script>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('styles'); ?>
<style>
.admin-stat-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    border: 1px solid #e5e7eb;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.admin-stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.25rem;
    margin-bottom: 1rem;
}

.stat-primary .stat-icon { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-success .stat-icon { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-info .stat-icon { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.stat-warning .stat-icon { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.stat-danger .stat-icon { background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%); }
.stat-secondary .stat-icon { background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); }

.stat-label {
    font-size: 0.875rem;
    color: #6b7280;
    font-weight: 500;
    margin-bottom: 0.5rem;
}

.stat-value {
    font-size: 1.5rem;
    font-weight: 700;
    color: #111827;
    margin-bottom: 0.25rem;
}

.stat-meta {
    font-size: 0.75rem;
    color: #9ca3af;
}

.alert-sm {
    padding: 0.5rem 0.75rem;
    font-size: 0.8rem;
    margin-bottom: 0.5rem;
}

.admin-card {
    border: 1px solid #e5e7eb;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.admin-card .card-header {
    background: #f9fafb;
    border-bottom: 1px solid #e5e7eb;
    border-radius: 12px 12px 0 0;
    padding: 1rem 1.5rem;
}

.admin-card .card-body {
    padding: 1.5rem;
}

@media (max-width: 768px) {
    .stat-value {
        font-size: 1.25rem;
    }
    
    .admin-stat-card {
        padding: 1rem;
    }
}
</style>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.admin', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /var/www/html/shaa_jewels/live/resources/views/admin/dashboard.blade.php ENDPATH**/ ?>