@extends('layouts.warehouse')

@section('title', 'Warehouse Dashboard')
@section('page-title', 'Dashboard')
@section('page-subtitle', 'Welcome to the Warehouse Management System')

@section('breadcrumb')
    <li class="breadcrumb-item active">Dashboard</li>
@endsection

@section('page-actions')
    <div class="btn-group">
        <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <i class="material-icons mr-2">add</i>
            Quick Actions
        </button>
        <div class="dropdown-menu dropdown-menu-right">
            @can('warehouse.items.create')
            <a class="dropdown-item" href="{{ route('warehouse.items.create') }}">
                <i class="material-icons mr-2">inventory_2</i>
                Add New Item
            </a>
            @endcan
            @can('warehouse.incoming.create')
            <a class="dropdown-item" href="{{ route('warehouse.incoming-operations.create') }}">
                <i class="material-icons mr-2">input</i>
                New Incoming Operation
            </a>
            @endcan
            @can('warehouse.outgoing.create')
            <a class="dropdown-item" href="{{ route('warehouse.outgoing.create') }}">
                <i class="material-icons mr-2">output</i>
                New Outgoing Transaction
            </a>
            @endcan
            <div class="dropdown-divider"></div>
            @can('warehouse.inventory.adjust')
            <a class="dropdown-item" href="{{ route('warehouse.inventory.adjustments') }}">
                <i class="material-icons mr-2">tune</i>
                Adjust Inventory
            </a>
            @endcan
        </div>
    </div>
@endsection

@section('content')
    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="warehouse-stat-card">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0 mr-3">
                        <div class="rounded-circle d-flex align-items-center justify-content-center"
                             style="width: 48px; height: 48px; background-color: var(--warehouse-primary); color: white;">
                            <i class="material-icons">inventory_2</i>
                        </div>
                    </div>
                    <div class="flex-grow-1">
                        <h3 class="mb-0">{{ $stats['total_items'] ?? 0 }}</h3>
                        <p class="text-muted mb-0">Total Items</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <a href="{{ route('warehouse.inventory.low-stock') }}" class="text-decoration-none">
                <div class="warehouse-stat-card" style="cursor: pointer;">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0 mr-3">
                            <div class="rounded-circle d-flex align-items-center justify-content-center"
                                 style="width: 48px; height: 48px; background-color: var(--warehouse-warning); color: white;">
                                <i class="material-icons">warning</i>
                            </div>
                        </div>
                        <div class="flex-grow-1">
                            <h3 class="mb-0 text-warning">{{ $stats['low_stock_items'] ?? 0 }}</h3>
                            <p class="text-muted mb-0">Low Stock Items</p>
                        </div>
                    </div>
                </div>
            </a>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="warehouse-stat-card">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0 mr-3">
                        <div class="rounded-circle d-flex align-items-center justify-content-center"
                             style="width: 48px; height: 48px; background-color: var(--warehouse-success); color: white;">
                            <i class="material-icons">place</i>
                        </div>
                    </div>
                    <div class="flex-grow-1">
                        <h3 class="mb-0">{{ $stats['total_locations'] ?? 0 }}</h3>
                        <p class="text-muted mb-0">Locations</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="warehouse-stat-card">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0 mr-3">
                        <div class="rounded-circle d-flex align-items-center justify-content-center"
                             style="width: 48px; height: 48px; background-color: var(--warehouse-info); color: white;">
                            <i class="material-icons">pending</i>
                        </div>
                    </div>
                    <div class="flex-grow-1">
                        <h3 class="mb-0 text-info">{{ $stats['pending_transactions'] ?? 0 }}</h3>
                        <p class="text-muted mb-0">Pending Transactions</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Inventory Chart -->
    <div class="row mb-4">
        <div class="col-lg-8 mb-4">
            <div class="card warehouse-card">
                <div class="card-header bg-white border-bottom">
                    <h6 class="card-title mb-0">
                        <i class="material-icons mr-2" style="font-size: 18px; vertical-align: middle;">bar_chart</i>
                        Inventory Levels by Category
                    </h6>
                </div>
                <div class="card-body">
                    <canvas id="inventoryChart" height="300"></canvas>
                </div>
            </div>
        </div>
        <div class="col-lg-4 mb-4">
            <!-- Low Stock Alert -->
            @if($lowStockItems->count() > 0)
                <div class="card warehouse-card">
                    <div class="card-header d-flex align-items-center justify-content-between">
                        <h6 class="mb-0 text-warning">
                            <i class="material-icons mr-2" style="vertical-align: middle;">warning</i>
                            Low Stock Alert
                        </h6>
                        <a href="{{ route('warehouse.inventory.low-stock') }}" class="btn btn-sm btn-outline-warning">
                            View All
                        </a>
                    </div>
                    <div class="card-body">
                        @foreach($lowStockItems as $item)
                            <div class="d-flex align-items-center justify-content-between py-2 {{ !$loop->last ? 'border-bottom' : '' }}">
                                <div>
                                    <p class="mb-0 font-weight-semibold">{{ $item['item_name'] }}</p>
                                    <small class="text-muted">{{ $item['item_code'] }}</small>
                                </div>
                                <div class="text-right">
                                    <div class="small">
                                        <span class="text-danger">{{ $item['current_stock'] }}</span> /
                                        <span class="text-muted">{{ $item['reorder_point'] }}</span>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            @else
                <div class="card warehouse-card">
                    <div class="card-body text-center">
                        <i class="material-icons text-success mb-2" style="font-size: 48px;">check_circle</i>
                        <h6 class="text-success">All Items Well Stocked</h6>
                        <p class="text-muted mb-0">No items are currently below reorder point</p>
                    </div>
                </div>
            @endif
        </div>
    </div>

    <div class="row">
        <!-- Recent Activities -->
        <div class="col-lg-8 mb-4">
            <div class="card warehouse-card">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h5 class="mb-0">
                        <i class="material-icons mr-2" style="vertical-align: middle;">timeline</i>
                        Recent Activities
                    </h5>
                    <a href="{{ route('warehouse.activity-log.index') }}" class="btn btn-sm btn-outline-primary">
                        View All
                    </a>
                </div>
                <div class="card-body">
                    @if($recentActivities->count() > 0)
                        <div class="list-group list-group-flush">
                            @foreach($recentActivities as $activity)
                                <div class="list-group-item d-flex align-items-center px-0">
                                    <div class="flex-shrink-0 mr-3">
                                        <div class="rounded-circle d-flex align-items-center justify-content-center text-white"
                                             style="width: 32px; height: 32px; background-color: var(--warehouse-{{ $activity['color'] ?? 'secondary' }});">
                                            <i class="material-icons" style="font-size: 16px;">{{ $activity['icon'] ?? 'info' }}</i>
                                        </div>
                                    </div>
                                    <div class="flex-grow-1">
                                        <p class="mb-1">{{ $activity['description'] }}</p>
                                        <small class="text-muted">
                                            by {{ $activity['user'] }} • {{ $activity['created_at']->diffForHumans() }}
                                        </small>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @else
                        <div class="text-center py-4">
                            <i class="material-icons text-muted" style="font-size: 48px;">timeline</i>
                            <p class="text-muted mb-0">No recent activities</p>
                        </div>
                    @endif
                </div>
            </div>
        </div>

        <!-- Quick Links & Low Stock -->
        <div class="col-lg-4">
            <!-- Low Stock Alert -->
            @if($lowStockItems->count() > 0)
                <div class="card warehouse-card mb-4">
                    <div class="card-header d-flex align-items-center justify-content-between">
                        <h6 class="mb-0 text-warning">
                            <i class="material-icons mr-2" style="vertical-align: middle;">warning</i>
                            Low Stock Alert
                        </h6>
                        <a href="{{ route('warehouse.inventory.low-stock') }}" class="btn btn-sm btn-outline-warning">
                            View All
                        </a>
                    </div>
                    <div class="card-body">
                        @foreach($lowStockItems as $item)
                            <div class="d-flex align-items-center justify-content-between py-2 {{ !$loop->last ? 'border-bottom' : '' }}">
                                <div>
                                    <p class="mb-0 font-weight-semibold">{{ $item['item_name'] }}</p>
                                    <small class="text-muted">{{ $item['item_code'] }}</small>
                                </div>
                                <div class="text-right">
                                    <div class="small">
                                        <span class="text-danger">{{ $item['current_stock'] }}</span> /
                                        <span class="text-muted">{{ $item['reorder_point'] }}</span>
                                    </div>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            @endif

            <!-- Location Summary -->
            @if($locationSummary->count() > 0)
                <div class="card warehouse-card">
                    <div class="card-header">
                        <h6 class="mb-0">
                            <i class="material-icons mr-2" style="vertical-align: middle;">place</i>
                            Inventory by Location
                        </h6>
                    </div>
                    <div class="card-body">
                        @foreach($locationSummary->take(5) as $location)
                            <div class="d-flex align-items-center justify-content-between py-2 {{ !$loop->last ? 'border-bottom' : '' }}">
                                <div>
                                    <p class="mb-0 font-weight-semibold">{{ $location['name'] }}</p>
                                    <small class="text-muted">{{ $location['total_items'] }} items</small>
                                </div>
                                <div class="text-right">
                                    <div class="small">
                                        <span class="text-success">{{ $location['available_quantity'] }}</span> /
                                        <span class="text-muted">{{ $location['total_quantity'] }}</span>
                                    </div>
                                    @if($location['total_reserved'] > 0)
                                        <div class="small">
                                            <span class="text-info">{{ $location['total_reserved'] }} reserved</span>
                                        </div>
                                    @endif
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            @endif
        </div>
    </div>

    @if($recentMovements->count() > 0)
    <!-- Recent Stock Movements -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="card warehouse-card">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <h5 class="mb-0">
                        <i class="material-icons mr-2" style="vertical-align: middle;">swap_horiz</i>
                        Recent Stock Movements
                    </h5>
                    <a href="{{ route('warehouse.reports.stock-movements') }}" class="btn btn-sm btn-outline-primary">
                        View Report
                    </a>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Item</th>
                                    <th>Type</th>
                                    <th>Quantity</th>
                                    <th>Reason</th>
                                    <th>User</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($recentMovements as $movement)
                                    <tr>
                                        <td>
                                            <div>
                                                <span class="font-weight-semibold">{{ $movement['item_name'] }}</span>
                                                <br>
                                                <small class="text-muted">{{ $movement['item_code'] }}</small>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="badge badge-{{ $movement['type_badge_class'] ?? 'info' }}">
                                                {{ ucfirst(str_replace('_', ' ', $movement['type'])) }}
                                            </span>
                                        </td>
                                        <td>{{ $movement['quantity'] }}</td>
                                        <td>{{ $movement['reason'] }}</td>
                                        <td>{{ $movement['user_name'] }}</td>
                                        <td>
                                            <small>{{ $movement['created_at']->format('M d, H:i') }}</small>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @endif
@endsection

@push('scripts')
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <script>
        // Initialize Inventory Chart
        document.addEventListener('DOMContentLoaded', function() {
            const ctx = document.getElementById('inventoryChart').getContext('2d');
            
            const chartData = @json($categoryChartData);
            
            new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: chartData.labels,
                    datasets: [{
                        data: chartData.data,
                        backgroundColor: [
                            '#007bff',
                            '#28a745', 
                            '#ffc107',
                            '#dc3545',
                            '#6f42c1',
                            '#fd7e14',
                            '#20c997',
                            '#6c757d',
                            '#17a2b8',
                            '#e83e8c'
                        ],
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'right',
                            labels: {
                                usePointStyle: true,
                                padding: 15,
                                generateLabels: function(chart) {
                                    const data = chart.data;
                                    if (data.labels.length && data.datasets.length) {
                                        return data.labels.map((label, i) => {
                                            const value = data.datasets[0].data[i];
                                            const itemsCount = chartData.items_count[i];
                                            return {
                                                text: `${label} (${value} units, ${itemsCount} items)`,
                                                fillStyle: data.datasets[0].backgroundColor[i],
                                                strokeStyle: data.datasets[0].borderColor || '#fff',
                                                lineWidth: data.datasets[0].borderWidth || 0,
                                                pointStyle: 'circle',
                                                hidden: false
                                            };
                                        });
                                    }
                                    return [];
                                }
                            }
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.parsed;
                                    const itemsCount = chartData.items_count[context.dataIndex];
                                    return `${label}: ${value} units (${itemsCount} items)`;
                                }
                            }
                        }
                    }
                }
            });
        });

        // Auto-refresh quick stats every 30 seconds
        setInterval(function() {
            fetch('{{ route('warehouse.api.quick-stats') }}')
                .then(response => response.json())
                .then(data => {
                    // Update stats in the page if needed
                    console.log('Stats updated:', data);
                })
                .catch(error => {
                    console.error('Error fetching quick stats:', error);
                });
        }, 30000);
    </script>
@endpush