@extends('layouts.dashboard.superadminapp')

@section('title', 'Stock Dashboard')

@section('styles')
<style>
    /* Compact Dashboard Styles */
    .dashboard-card {
        border: none;
        border-radius: 8px;
        transition: all 0.2s ease;
        overflow: hidden;
        cursor: pointer;
        text-decoration: none;
        display: block;
    }
    .dashboard-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12) !important;
        text-decoration: none;
    }

    /* Compact KPI Cards */
    .kpi-card {
        border-radius: 8px;
        color: #fff;
        position: relative;
        overflow: hidden;
        padding: 0.75rem 1rem !important;
    }
    .kpi-card .kpi-icon {
        font-size: 2rem;
        opacity: 0.25;
        position: absolute;
        right: 0.75rem;
        top: 50%;
        transform: translateY(-50%);
    }
    .kpi-card .kpi-value {
        font-size: 1.5rem;
        font-weight: 700;
        margin-bottom: 0.1rem;
        line-height: 1.2;
    }
    .kpi-card .kpi-label {
        font-size: 0.7rem;
        text-transform: uppercase;
        letter-spacing: 0.3px;
        opacity: 0.9;
    }
    .kpi-card .kpi-info {
        font-size: 0.65rem;
        margin-top: 0.25rem;
        opacity: 0.8;
    }

    /* Gradient backgrounds */
    .bg-gradient-success { background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%); }
    .bg-gradient-primary { background: linear-gradient(135deg, #4e73df 0%, #224abe 100%); }
    .bg-gradient-warning { background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%); }
    .bg-gradient-info { background: linear-gradient(135deg, #36b9cc 0%, #258391 100%); }
    .bg-gradient-danger { background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%); }

    /* Compact Cards */
    .compact-card {
        border: none;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    }
    .compact-card .card-header {
        background: transparent;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 0.5rem 0.75rem;
    }
    .compact-card .card-body {
        padding: 0.5rem 0.75rem;
    }
    .compact-card .card-header h6 {
        font-size: 0.8rem;
        margin: 0;
    }

    /* Compact Chart Cards */
    .chart-card {
        border: none;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    }
    .chart-card .card-header {
        background: transparent;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        padding: 0.5rem 0.75rem;
    }
    .chart-card .card-body {
        padding: 0.5rem 0.75rem;
    }

    /* Compact Quick Links */
    .quick-link-card {
        background: #fff;
        border-radius: 8px;
        padding: 0.75rem;
        text-align: center;
        transition: all 0.2s;
        border: 1px solid rgba(0, 0, 0, 0.05);
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
    }
    .quick-link-card:hover {
        border-color: #4e73df;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(78, 115, 223, 0.15);
    }
    .quick-link-card i {
        font-size: 1.5rem;
        margin-bottom: 0.35rem;
    }
    .quick-link-card .link-title {
        font-weight: 600;
        color: #333;
        font-size: 0.75rem;
    }

    /* Progress Stats */
    .progress-stat {
        margin-bottom: 0.75rem;
    }
    .progress-stat .progress-label {
        display: flex;
        justify-content: space-between;
        margin-bottom: 0.25rem;
        font-weight: 500;
        font-size: 0.75rem;
    }
    .progress {
        height: 6px !important;
        border-radius: 3px;
    }

    /* Compact Page Header */
    .page-header {
        background: linear-gradient(135deg, #fff 0%, #f8f9fc 100%);
        border-radius: 8px;
        padding: 0.5rem 1rem;
        margin-bottom: 0.75rem;
        box-shadow: 0 1px 5px rgba(0, 0, 0, 0.04);
    }
    .page-header h1 {
        font-size: 1rem;
        font-weight: 600;
        color: #2d3748;
        margin: 0;
    }

    /* DateTime Display */
    .datetime-display {
        gap: 0.5rem;
    }
    .date-box, .time-box {
        display: flex;
        align-items: center;
        gap: 0.35rem;
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        padding: 0.35rem 0.65rem;
        border-radius: 6px;
        border: 1px solid #e2e8f0;
        font-size: 0.75rem;
        color: #475569;
        font-weight: 500;
    }
    .date-box i, .time-box i {
        color: #4e73df;
        font-size: 0.7rem;
    }
    .time-box {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        color: #fff;
        border: none;
        min-width: 85px;
        justify-content: center;
    }
    .time-box i {
        color: rgba(255,255,255,0.8);
    }
    .time-box .display-time {
        font-family: 'Courier New', monospace;
        font-weight: 600;
        letter-spacing: 0.5px;
    }

    /* Compact row margins */
    .row.mb-4 { margin-bottom: 0.75rem !important; }
    .row.mb-3 { margin-bottom: 0.5rem !important; }
    .col-xl-3.mb-3, .col-md-6.mb-3, .col-xl-6.mb-3, .col-lg-4.mb-3, .col-lg-8.mb-3 {
        margin-bottom: 0.5rem !important;
    }

    /* Compact table */
    .table-sm td, .table-sm th {
        padding: 0.3rem 0.5rem;
        font-size: 0.8rem;
    }

    /* Stock Health Display */
    .stock-health-display {
        text-align: center;
        padding: 0.5rem;
    }
    .stock-health-display .health-value {
        font-size: 2rem;
        font-weight: 700;
        line-height: 1;
    }
    .stock-health-display .health-label {
        font-size: 0.7rem;
        color: #6c757d;
        margin-top: 0.25rem;
    }

    /* Compact Alert */
    .alert {
        padding: 0.5rem 0.75rem;
        font-size: 0.8rem;
        margin-bottom: 0.5rem;
    }

    /* Filter buttons */
    .filter-btn {
        padding: 0.2rem 0.5rem;
        border-radius: 4px;
        font-size: 0.7rem;
    }

    /* Responsive adjustments */
    @media (max-width: 768px) {
        .kpi-card .kpi-value { font-size: 1.25rem; }
        .quick-link-card i { font-size: 1.25rem; }
    }
</style>
@endsection

@section('content')

<div class="container-fluid">

    <!-- Page Header -->
    <div class="page-header d-flex align-items-center justify-content-between flex-wrap">
        <h1><i class="fas fa-boxes mr-2 text-primary"></i>Stock Dashboard</h1>
        <div class="datetime-display d-flex align-items-center">
            <div class="date-box">
                <i class="far fa-calendar-alt"></i>
                <span id="day">{{ now()->format('l') }}</span>,
                <span id="daynum">{{ now()->format('d') }}</span>
                <span id="month">{{ now()->format('F') }}</span>
                <span id="year">{{ now()->format('Y') }}</span>
            </div>
            <div class="time-box">
                <i class="far fa-clock"></i>
                <span class="display-time"></span>
            </div>
        </div>
    </div>

    @php
        $inStockItems = $totalItems - $lowStock - $outOfStock;
        $inStockPercent = $totalItems > 0 ? round(($inStockItems / $totalItems) * 100, 1) : 0;
        $lowStockPercent = $totalItems > 0 ? round(($lowStock / $totalItems) * 100, 1) : 0;
        $outOfStockPercent = $totalItems > 0 ? round(($outOfStock / $totalItems) * 100, 1) : 0;
    @endphp

    <!-- KPI Cards Row -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="{{ route('superadmin.sku.skumaster') }}" class="dashboard-card">
                <div class="kpi-card bg-gradient-primary shadow">
                    <i class="fas fa-boxes kpi-icon"></i>
                    <div class="kpi-value">{{ number_format($totalItems) }}</div>
                    <div class="kpi-label">Total Items</div>
                    <div class="kpi-info">
                        <i class="fas fa-database mr-1"></i> All SKU items in inventory
                    </div>
                </div>
            </a>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="{{ route('superadmin.sku.skumaster') }}" class="dashboard-card">
                <div class="kpi-card bg-gradient-success shadow">
                    <i class="fas fa-check-circle kpi-icon"></i>
                    <div class="kpi-value">{{ number_format($inStockItems) }}</div>
                    <div class="kpi-label">In Stock</div>
                    <div class="kpi-info">
                        <i class="fas fa-chart-line mr-1"></i> {{ $inStockPercent }}% of total items
                    </div>
                </div>
            </a>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="{{ route('superadmin.sku.skumaster') }}" class="dashboard-card">
                <div class="kpi-card bg-gradient-warning shadow">
                    <i class="fas fa-exclamation-triangle kpi-icon"></i>
                    <div class="kpi-value">{{ number_format($lowStock) }}</div>
                    <div class="kpi-label">Low Stock</div>
                    <div class="kpi-info">
                        <i class="fas fa-arrow-down mr-1"></i> {{ $lowStockPercent }}% below minimum level
                    </div>
                </div>
            </a>
        </div>
        <div class="col-xl-3 col-md-6 mb-3">
            <a href="{{ route('superadmin.sku.skumaster') }}" class="dashboard-card">
                <div class="kpi-card bg-gradient-danger shadow">
                    <i class="fas fa-times-circle kpi-icon"></i>
                    <div class="kpi-value">{{ number_format($outOfStock) }}</div>
                    <div class="kpi-label">Out of Stock</div>
                    <div class="kpi-info">
                        <i class="fas fa-exclamation mr-1"></i> {{ $outOfStockPercent }}% requires reorder
                    </div>
                </div>
            </a>
        </div>
    </div>

    <!-- Stock Status Overview -->
    <div class="compact-card card shadow mb-3">
        <div class="card-header d-flex align-items-center justify-content-between">
            <h6 class="m-0 font-weight-bold text-primary">
                <i class="fas fa-chart-pie mr-2"></i>Stock Status Overview
            </h6>
            <a href="{{ route('superadmin.sku.skumaster') }}" class="btn btn-sm btn-outline-primary">View Details</a>
        </div>
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="progress-stat">
                        <div class="progress-label">
                            <span><i class="fas fa-circle text-success mr-1"></i> In Stock</span>
                            <span>{{ number_format($inStockItems) }} ({{ $inStockPercent }}%)</span>
                        </div>
                        <div class="progress">
                            <div class="progress-bar bg-success" style="width: {{ $inStockPercent }}%"></div>
                        </div>
                    </div>
                    <div class="progress-stat">
                        <div class="progress-label">
                            <span><i class="fas fa-circle text-warning mr-1"></i> Low Stock</span>
                            <span>{{ number_format($lowStock) }} ({{ $lowStockPercent }}%)</span>
                        </div>
                        <div class="progress">
                            <div class="progress-bar bg-warning" style="width: {{ $lowStockPercent }}%"></div>
                        </div>
                    </div>
                    <div class="progress-stat mb-0">
                        <div class="progress-label">
                            <span><i class="fas fa-circle text-danger mr-1"></i> Out of Stock</span>
                            <span>{{ number_format($outOfStock) }} ({{ $outOfStockPercent }}%)</span>
                        </div>
                        <div class="progress">
                            <div class="progress-bar bg-danger" style="width: {{ $outOfStockPercent }}%"></div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="stock-health-display">
                        <div class="health-value {{ $inStockPercent >= 70 ? 'text-success' : ($inStockPercent >= 40 ? 'text-warning' : 'text-danger') }}">
                            {{ $inStockPercent }}%
                        </div>
                        <div class="health-label">Stock Health Rate</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row -->
    <div class="row mb-4">
        <!-- Stock Movement Chart -->
        <div class="col-lg-8 mb-3">
            <div class="chart-card card shadow h-100">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-chart-area mr-2"></i>Stock Movement (Last 30 Days)
                    </h6>
                    <div>
                        <button class="btn btn-sm btn-primary filter-btn active" data-filter="daily">Daily</button>
                        <button class="btn btn-sm btn-outline-primary filter-btn" data-filter="weekly">Weekly</button>
                    </div>
                </div>
                <div class="card-body">
                    <canvas id="movementChart" height="100"></canvas>
                </div>
            </div>
        </div>

        <!-- Stock Distribution Chart -->
        <div class="col-lg-4 mb-3">
            <div class="chart-card card shadow h-100">
                <div class="card-header">
                    <h6 class="m-0 font-weight-bold text-success">
                        <i class="fas fa-chart-pie mr-2"></i>Stock by Category
                    </h6>
                </div>
                <div class="card-body d-flex align-items-center justify-content-center">
                    <canvas id="distributionChart" height="180"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="compact-card card shadow mb-3">
        <div class="card-header">
            <h6 class="m-0 font-weight-bold text-info">
                <i class="fas fa-bolt mr-2"></i>Quick Actions
            </h6>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.sku.skumaster') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-boxes text-primary"></i>
                            <div class="link-title">SKU Master</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.sku.skumovement') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-exchange-alt text-success"></i>
                            <div class="link-title">Stock Movement</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.sku.skuapproval') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-clipboard-check text-warning"></i>
                            <div class="link-title">SKU Approvals</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.grn.grnorder') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-truck-loading text-info"></i>
                            <div class="link-title">GRN</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.report.inventoryreport') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-chart-bar text-danger"></i>
                            <div class="link-title">Inventory Report</div>
                        </div>
                    </a>
                </div>
                <div class="col-xl-2 col-md-4 col-6 mb-2">
                    <a href="{{ route('superadmin.purchase.index') }}" class="text-decoration-none">
                        <div class="quick-link-card">
                            <i class="fas fa-shopping-cart text-secondary"></i>
                            <div class="link-title">Purchase</div>
                        </div>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Stock Summary Cards -->
    <div class="row mb-3">
        <div class="col-md-6 mb-3">
            <div class="compact-card card shadow h-100">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-warning">
                        <i class="fas fa-exclamation-triangle mr-2"></i>Stock Alerts
                    </h6>
                </div>
                <div class="card-body">
                    @if($outOfStock > 0)
                        <div class="alert alert-danger">
                            <i class="fas fa-times-circle mr-2"></i>
                            <strong>{{ $outOfStock }} item(s)</strong> are out of stock and need immediate reorder.
                        </div>
                    @endif

                    @if($lowStock > 0)
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle mr-2"></i>
                            <strong>{{ $lowStock }} item(s)</strong> are below minimum stock level.
                        </div>
                    @endif

                    @if($outOfStock == 0 && $lowStock == 0)
                        <div class="alert alert-success mb-0">
                            <i class="fas fa-check-circle mr-2"></i>
                            <strong>All items</strong> are adequately stocked. No alerts.
                        </div>
                    @endif

                    @if($inStockPercent < 50)
                        <div class="alert alert-info mb-0">
                            <i class="fas fa-info-circle mr-2"></i>
                            Stock health is at <strong>{{ $inStockPercent }}%</strong>. Consider reviewing inventory levels.
                        </div>
                    @endif
                </div>
            </div>
        </div>
        <div class="col-md-6 mb-3">
            <div class="compact-card card shadow h-100">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-success">
                        <i class="fas fa-list-alt mr-2"></i>Category Distribution
                    </h6>
                    <a href="{{ route('superadmin.sku.skumaster') }}" class="btn btn-sm btn-outline-success">View All</a>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-sm table-hover mb-0">
                            <thead class="thead-light">
                                <tr>
                                    <th class="pl-3">Category</th>
                                    <th class="text-center">Stock Qty</th>
                                    <th class="text-center pr-3">Percentage</th>
                                </tr>
                            </thead>
                            <tbody>
                                @php
                                    $totalStock = array_sum($distribution);
                                @endphp
                                @forelse($distribution as $category => $qty)
                                    @php
                                        $percentage = $totalStock > 0 ? round(($qty / $totalStock) * 100, 1) : 0;
                                    @endphp
                                    <tr>
                                        <td class="font-weight-bold pl-3">{{ $category ?: 'Uncategorized' }}</td>
                                        <td class="text-center">
                                            <span class="badge badge-primary">{{ number_format($qty) }}</span>
                                        </td>
                                        <td class="text-center pr-3">{{ $percentage }}%</td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="3" class="text-center text-muted py-3">No category data available</td>
                                    </tr>
                                @endforelse
                            </tbody>
                            @if(count($distribution) > 0)
                            <tfoot class="thead-light">
                                <tr class="font-weight-bold">
                                    <td class="pl-3">Total</td>
                                    <td class="text-center"><span class="badge badge-success">{{ number_format($totalStock) }}</span></td>
                                    <td class="text-center pr-3">100%</td>
                                </tr>
                            </tfoot>
                            @endif
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Pass PHP data to JS
    const movementData = @json($movementData ?? []);
    const distribution = @json($distribution ?? []);

    // Stock Movement Chart - Generate last 30 days
    const movementLabels = [];
    const movementValues = [];
    const today = new Date();

    for (let i = 29; i >= 0; i--) {
        const date = new Date(today);
        date.setDate(date.getDate() - i);
        const dateStr = date.toISOString().split('T')[0];
        const day = date.getDate();
        const month = date.toLocaleString('en-US', { month: 'short' });
        movementLabels.push(`${day} ${month}`);
        movementValues.push(movementData[dateStr] || 0);
    }

    const movementCtx = document.getElementById('movementChart').getContext('2d');
    new Chart(movementCtx, {
        type: 'line',
        data: {
            labels: movementLabels,
            datasets: [{
                label: 'Net Stock Movement',
                data: movementValues,
                fill: true,
                backgroundColor: 'rgba(78, 115, 223, 0.1)',
                borderColor: 'rgba(78, 115, 223, 1)',
                borderWidth: 2,
                tension: 0.4,
                pointBackgroundColor: 'rgba(78, 115, 223, 1)',
                pointBorderColor: '#fff',
                pointBorderWidth: 2,
                pointRadius: 2,
                pointHoverRadius: 5
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: { display: false }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: { color: 'rgba(0,0,0,0.05)' }
                },
                x: {
                    grid: { display: false },
                    ticks: { maxTicksLimit: 10 }
                }
            }
        }
    });

    // Stock Distribution Doughnut Chart
    const distLabels = Object.keys(distribution).map(c => c || 'Uncategorized');
    const distData = Object.values(distribution);

    const distCtx = document.getElementById('distributionChart').getContext('2d');
    new Chart(distCtx, {
        type: 'doughnut',
        data: {
            labels: distLabels,
            datasets: [{
                data: distData,
                backgroundColor: [
                    '#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b',
                    '#858796', '#5a5c69', '#6f42c1', '#fd7e14', '#20c9a6'
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 10,
                        usePointStyle: true,
                        font: { size: 10 }
                    }
                }
            },
            cutout: '60%'
        }
    });

    // Filter buttons functionality
    document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.filter-btn').forEach(b => {
                b.classList.remove('active', 'btn-primary');
                b.classList.add('btn-outline-primary');
            });
            this.classList.add('active', 'btn-primary');
            this.classList.remove('btn-outline-primary');
        });
    });

    // Dynamic Date/Time
    function updateDateTime() {
        const now = new Date();
        const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

        document.getElementById('day').textContent = days[now.getDay()];
        document.getElementById('daynum').textContent = now.getDate();
        document.getElementById('month').textContent = months[now.getMonth()];
        document.getElementById('year').textContent = now.getFullYear();

        const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
        document.querySelector('.display-time').textContent = timeStr;
    }
    updateDateTime();
    setInterval(updateDateTime, 1000);
});
</script>
@endsection
