{{-- resources/views/admin/dashboard.blade.php --}}
@extends('layouts.admin')

@section('title', 'Admin Dashboard - Chingu Bite')

@section('content')
<div class="container-fluid px-4">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h3 mb-0 text-gray-800">Dashboard</h1>
        <div class="d-flex align-items-center">
            <span class="me-3 text-muted">
                <i class="fas fa-calendar-alt me-1"></i>
                {{ now()->format('l, F j, Y') }}
            </span>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                Today's Revenue
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                Rp {{ number_format($todayRevenue ?? 0, 0, ',', '.') }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-money-bill-wave fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                Today's Orders
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                {{ $todayOrders ?? 0 }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-shopping-cart fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                Pending Payments
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                {{ $pendingPayments ?? 0 }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-clock fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                Career Applications
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                {{ $pendingApplications ?? 0 }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-users fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts & Recent Data -->
    <div class="row">
        <!-- Revenue Chart -->
        <div class="col-xl-8 col-lg-7">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Revenue Overview (Last 7 Days)</h6>
                </div>
                <div class="card-body">
                    <div class="chart-area">
                        <canvas id="revenueChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Stats -->
        <div class="col-xl-4 col-lg-5">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Quick Stats</h6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <div class="small text-muted mb-1">Total Menu Items</div>
                        <div class="h5">{{ $totalMenus ?? 0 }}</div>
                    </div>
                    <div class="mb-3">
                        <div class="small text-muted mb-1">Active Promotions</div>
                        <div class="h5">{{ $activePromos ?? 0 }}</div>
                    </div>
                    <div class="mb-3">
                        <div class="small text-muted mb-1">Registered Users</div>
                        <div class="h5">{{ $totalUsers ?? 0 }}</div>
                    </div>
                    <div>
                        <div class="small text-muted mb-1">System Health</div>
                        <div class="d-flex align-items-center">
                            <div class="progress flex-grow-1 me-2">
                                <div class="progress-bar bg-success" role="progressbar" 
                                     style="width: 85%" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"></div>
                            </div>
                            <span class="small">85%</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Orders -->
    <div class="row">
        <div class="col-12">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Recent Orders</h6>
                    <a href="{{ route('employee.orders.index') }}" class="btn btn-sm btn-outline-primary">
                        View All
                    </a>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Order #</th>
                                    <th>Customer</th>
                                    <th>Type</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($recentOrders as $order)
                                    <tr>
                                        <td>#{{ $order['order_number'] }}</td>
                                        <td>{{ $order['customer']['name'] ?? 'N/A' }}</td>
                                        <td>
                                            <span class="badge bg-{{ $order['order_type'] == 'dine_in' ? 'info' : ($order['order_type'] == 'takeaway' ? 'warning' : 'success') }}">
                                                {{ ucfirst(str_replace('_', ' ', $order['order_type'])) }}
                                            </span>
                                        </td>
                                        <td>Rp {{ number_format($order['final_amount'], 0, ',', '.') }}</td>
                                        <td>
                                            <span class="badge bg-{{ match($order['status']) {
                                                'completed' => 'success',
                                                'cancelled' => 'danger',
                                                'pending' => 'warning',
                                                default => 'info'
                                            } }}">
                                                {{ ucfirst($order['status']) }}
                                            </span>
                                        </td>
                                        <td>{{ \Carbon\Carbon::parse($order['created_at'])->format('M d, H:i') }}</td>
                                        <td>
                                            <a href="{{ route('employee.orders.show', $order['id']) }}" 
                                               class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                        </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="7" class="text-center py-4">
                                            <i class="fas fa-clipboard-list fa-2x text-muted mb-3"></i>
                                            <p class="text-muted">No recent orders</p>
                                        </td>
                                    </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Quick Actions -->
    <div class="row">
        <div class="col-12">
            <div class="card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Quick Actions</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3 col-6 mb-3">
                            <a href="{{ route('admin.menu.create') }}" class="btn btn-outline-primary w-100">
                                <i class="fas fa-utensils fa-2x mb-2"></i>
                                <div>Add Menu</div>
                            </a>
                        </div>
                        <div class="col-md-3 col-6 mb-3">
                            <a href="{{ route('admin.promos.create') }}" class="btn btn-outline-success w-100">
                                <i class="fas fa-tag fa-2x mb-2"></i>
                                <div>Create Promo</div>
                            </a>
                        </div>
                        <div class="col-md-3 col-6 mb-3">
                            <a href="{{ route('admin.reports.sales') }}" class="btn btn-outline-info w-100">
                                <i class="fas fa-chart-line fa-2x mb-2"></i>
                                <div>View Reports</div>
                            </a>
                        </div>
                        <div class="col-md-3 col-6 mb-3">
                            <a href="{{ route('admin.career-applications.index') }}" class="btn btn-outline-warning w-100">
                                <i class="fas fa-users fa-2x mb-2"></i>
                                <div>Applications</div>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Revenue Chart
        const ctx = document.getElementById('revenueChart').getContext('2d');
        const revenueChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5', 'Day 6', 'Today'],
                datasets: [{
                    label: 'Revenue (Rp)',
                    data: [
                        {{ $revenueData[6] ?? 0 }},
                        {{ $revenueData[5] ?? 0 }},
                        {{ $revenueData[4] ?? 0 }},
                        {{ $revenueData[3] ?? 0 }},
                        {{ $revenueData[2] ?? 0 }},
                        {{ $revenueData[1] ?? 0 }},
                        {{ $revenueData[0] ?? 0 }}
                    ],
                    backgroundColor: 'rgba(78, 115, 223, 0.05)',
                    borderColor: 'rgba(78, 115, 223, 1)',
                    borderWidth: 2,
                    pointBackgroundColor: 'rgba(78, 115, 223, 1)',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    tension: 0.3
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return 'Rp ' + value.toLocaleString('id-ID');
                            }
                        }
                    }
                }
            }
        });

        // Auto refresh data every 60 seconds
        setInterval(function() {
            fetch('{{ route("admin.dashboard.data") }}')
                .then(response => {
                                if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
                })
                .then(data => {
            console.log('Dashboard data updated:', data);
            
            // Update stats jika data ada
            if (data.stats) {
                document.querySelectorAll('[data-stat]').forEach(el => {
                    const stat = el.dataset.stat;
                    if (data.stats[stat] !== undefined) {
                        if (stat.includes('Revenue') || stat.includes('revenue')) {
                            el.textContent = 'Rp ' + data.stats[stat].toLocaleString('id-ID');
                        } else {
                            el.textContent = data.stats[stat];
                        }
                    }
                });
                }
           // Update chart jika ada salesData
            if (data.salesData && window.salesChart) {
                updateSalesChart(data.salesData);
            }
        })
        .catch(error => {
            console.error('Error fetching dashboard data:', error);
            // Nonaktifkan auto refresh jika error
            clearInterval(refreshInterval);
        });
}, 60000); // 60 seconds
});
</script>
@endsection