@extends('admin.layout')

@section('title', 'E-commerce')
@section('header', 'E-commerce')

@push('head')
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
@endpush

@section('content')
{{-- Stats principales --}}
<div class="grid md:grid-cols-2 lg:grid-cols-5 gap-6 mb-8">
    <div class="bg-white rounded-2xl border border-slate-200 p-6">
        <h3 class="text-sm font-medium text-slate-500">Chiffre d'affaires total</h3>
        <p class="text-2xl font-bold text-emerald-600 mt-1">{{ number_format($totalRevenue, 2, ',', ' ') }} {{ $currencySymbol }}</p>
        <p class="text-xs text-slate-400 mt-1">Commandes payées + expédiées</p>
    </div>
    <div class="bg-white rounded-2xl border border-slate-200 p-6">
        <h3 class="text-sm font-medium text-slate-500">CA ce mois</h3>
        <p class="text-2xl font-bold text-slate-900 mt-1">{{ number_format($revenueThisMonth, 2, ',', ' ') }} {{ $currencySymbol }}</p>
        <p class="text-xs text-slate-400 mt-1">{{ $ordersThisMonth }} commande(s)</p>
    </div>
    <div class="bg-white rounded-2xl border border-slate-200 p-6">
        <h3 class="text-sm font-medium text-slate-500">Panier moyen</h3>
        <p class="text-2xl font-bold text-slate-900 mt-1">{{ number_format($avgOrderValue, 2, ',', ' ') }} {{ $currencySymbol }}</p>
    </div>
    <div class="bg-white rounded-2xl border border-slate-200 p-6">
        <h3 class="text-sm font-medium text-slate-500">Commandes</h3>
        <p class="text-3xl font-bold text-slate-900 mt-1">{{ $ordersCount }}</p>
    </div>
    <div class="bg-white rounded-2xl border border-slate-200 p-6">
        <h3 class="text-sm font-medium text-slate-500">Produits</h3>
        <p class="text-3xl font-bold text-slate-900 mt-1">{{ $productsCount }}</p>
    </div>
</div>

{{-- Graphiques --}}
<div class="grid lg:grid-cols-2 gap-6 mb-8">
    <div class="bg-white rounded-2xl border border-slate-200 p-6">
        <h3 class="font-semibold text-slate-800 mb-4">Ventes des 7 derniers jours</h3>
        <div class="h-64">
            <canvas id="chartSales7"></canvas>
        </div>
    </div>
    <div class="bg-white rounded-2xl border border-slate-200 p-6">
        <h3 class="font-semibold text-slate-800 mb-4">Répartition par statut</h3>
        <div class="h-64 flex items-center justify-center">
            <canvas id="chartStatus"></canvas>
        </div>
    </div>
</div>

<div class="bg-white rounded-2xl border border-slate-200 p-6 mb-8">
    <h3 class="font-semibold text-slate-800 mb-4">Ventes des 30 derniers jours</h3>
    <div class="h-72">
        <canvas id="chartSales30"></canvas>
    </div>
</div>

<div class="flex gap-3 flex-wrap mb-8">
    <a href="{{ route('admin.ecommerce.settings') }}" class="px-6 py-2.5 border border-slate-200 rounded-xl font-medium hover:bg-slate-50 transition text-slate-700">⚙️ Paramètres</a>
    <a href="{{ route('admin.ecommerce.categories') }}" class="px-6 py-2.5 bg-primary-500 text-white rounded-xl font-medium hover:bg-primary-600 transition">Catégories</a>
    <a href="{{ route('admin.ecommerce.products') }}" class="px-6 py-2.5 border border-slate-200 rounded-xl font-medium hover:bg-slate-50 transition text-slate-700">Produits</a>
    <a href="{{ route('admin.ecommerce.shipping-methods') }}" class="px-6 py-2.5 border border-slate-200 rounded-xl font-medium hover:bg-slate-50 transition text-slate-700">Livraison</a>
    <a href="{{ route('admin.ecommerce.coupons') }}" class="px-6 py-2.5 border border-slate-200 rounded-xl font-medium hover:bg-slate-50 transition text-slate-700">Codes promo</a>
    <a href="{{ route('admin.ecommerce.orders') }}" class="px-6 py-2.5 border border-slate-200 rounded-xl font-medium hover:bg-slate-50 transition text-slate-700">Commandes</a>
    <a href="{{ route('ecommerce.index') }}" target="_blank" class="px-6 py-2.5 border border-slate-200 rounded-xl font-medium hover:bg-slate-50 transition text-slate-700">Voir la boutique →</a>
</div>

<div class="bg-white rounded-2xl border border-slate-200 p-6 mb-8">
    <div class="flex items-center justify-between mb-3">
        <h3 class="font-semibold text-slate-800">Configuration</h3>
        <a href="{{ route('admin.ecommerce.settings') }}" class="text-sm text-primary-500 hover:underline">Configurer tout →</a>
    </div>
    @php $stripeOk = \App\Models\Setting::get('stripe_secret') ?: config('services.stripe.secret'); @endphp
    @if($stripeOk)
    <p class="text-emerald-600 font-medium">✓ Stripe configuré</p>
    <p class="text-sm text-slate-500 mt-1">Les paiements en ligne sont activés.</p>
    @else
    <p class="text-amber-600 font-medium">Stripe n'est pas configuré</p>
    <p class="text-sm text-slate-500 mt-2">Configurez Stripe dans <a href="{{ route('admin.ecommerce.settings') }}" class="text-primary-500 hover:underline">Paramètres E-commerce</a> pour activer les paiements en ligne.</p>
    @endif
</div>

@if($recentOrders->isNotEmpty())
<div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
    <h3 class="px-6 py-4 border-b border-slate-100 font-semibold text-slate-800">Dernières commandes</h3>
    <div class="overflow-x-auto">
        <table class="w-full">
            <thead class="bg-slate-50 text-left text-sm text-slate-500">
                <tr>
                    <th class="px-6 py-3 font-medium">N°</th>
                    <th class="px-6 py-3 font-medium">Client</th>
                    <th class="px-6 py-3 font-medium">Total</th>
                    <th class="px-6 py-3 font-medium">Statut</th>
                    <th class="px-6 py-3 font-medium">Date</th>
                    <th class="px-6 py-3 font-medium"></th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                @foreach($recentOrders as $order)
                <tr class="hover:bg-slate-50/50">
                    <td class="px-6 py-4 font-mono text-sm">{{ $order->number }}</td>
                    <td class="px-6 py-4">{{ $order->customer_name }}</td>
                    <td class="px-6 py-4 font-semibold">{{ number_format($order->total, 2, ',', ' ') }} {{ $currencySymbol }}</td>
                    <td class="px-6 py-4"><span class="px-2 py-1 rounded-lg text-xs font-medium {{ $order->status === 'paid' ? 'bg-emerald-100 text-emerald-700' : ($order->status === 'shipped' ? 'bg-blue-100 text-blue-700' : ($order->status === 'cancelled' ? 'bg-slate-100 text-slate-600' : 'bg-amber-100 text-amber-700')) }}">{{ $order->status }}</span></td>
                    <td class="px-6 py-4 text-sm text-slate-500">{{ $order->created_at->format('d/m/Y H:i') }}</td>
                    <td class="px-6 py-4"><a href="{{ route('admin.ecommerce.orders.show', $order) }}" class="text-primary-500 hover:underline text-sm">Voir</a></td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</div>
@endif

<p class="mt-6 text-sm text-slate-500">Ajoutez <strong>/boutique</strong> dans Apparence > Menu pour afficher le lien Boutique sur votre site.</p>

@push('scripts')
<script>
(function() {
    const currencySymbol = @json($currencySymbol);
    const sales7 = @json($salesLast7Days);
    const sales30 = @json($salesLast30Days);
    const ordersByStatus = @json($ordersByStatus);

    const statusLabels = { pending: 'En attente', paid: 'Payée', shipped: 'Expédiée', cancelled: 'Annulée' };
    const statusColors = { pending: '#f59e0b', paid: '#22c55e', shipped: '#3b82f6', cancelled: '#94a3b8' };

    if (sales7.length && document.getElementById('chartSales7')) {
        new Chart(document.getElementById('chartSales7'), {
            type: 'bar',
            data: {
                labels: sales7.map(d => d.label),
                datasets: [{
                    label: 'CA (' + currencySymbol + ')',
                    data: sales7.map(d => d.total),
                    backgroundColor: 'rgba(34, 197, 94, 0.6)',
                    borderColor: 'rgb(34, 197, 94)',
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: { beginAtZero: true }
                }
            }
        });
    }

    if (Object.keys(ordersByStatus).length && document.getElementById('chartStatus')) {
        const statusData = Object.entries(ordersByStatus).map(([k, v]) => ({ label: statusLabels[k] || k, count: v, color: statusColors[k] || '#94a3b8' }));
        new Chart(document.getElementById('chartStatus'), {
            type: 'doughnut',
            data: {
                labels: statusData.map(d => d.label + ' (' + d.count + ')'),
                datasets: [{
                    data: statusData.map(d => d.count),
                    backgroundColor: statusData.map(d => d.color),
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { position: 'bottom' } }
            }
        });
    }

    if (sales30.length && document.getElementById('chartSales30')) {
        new Chart(document.getElementById('chartSales30'), {
            type: 'line',
            data: {
                labels: sales30.map(d => d.label),
                datasets: [{
                    label: 'CA (' + currencySymbol + ')',
                    data: sales30.map(d => d.total),
                    fill: true,
                    borderColor: 'rgb(34, 197, 94)',
                    backgroundColor: 'rgba(34, 197, 94, 0.1)',
                    tension: 0.3
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: {
                    y: { beginAtZero: true }
                }
            }
        });
    }
})();
</script>
@endpush
@endsection
