@extends('layouts.app')

@section('title', 'Tableau de bord')
@section('page-title', 'Tableau de bord')

@section('content')
<div x-data="dashboardManager(@json($stats), @json($ventesParMagasin))" x-init="initChart()" class="space-y-6">
    {{-- Stats cards --}}
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4">
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-slate-500">Total ventes</p>
                    <p class="text-xl font-bold text-emerald-600 mt-1"
                       x-text="formatPrice(stats.totalVentes)">
                       {{ @dump($stats['totalVentes']) }}
                        {{ number_format((int) ($stats['totalVentes'] ?? 0), 0, ',', ' ') }} FCFA
                    </p>
                </div>
                <div class="w-11 h-11 rounded-lg bg-emerald-100 flex items-center justify-center">
                    <svg class="w-5 h-5 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-slate-500">Total achats</p>
                    <p class="text-xl font-bold text-amber-600 mt-1"
                       x-text="formatPrice(stats.totalAchats)">
                        {{ number_format((int) ($stats['totalAchats'] ?? 0), 0, ',', ' ') }} FCFA
                    </p>
                </div>
                <div class="w-11 h-11 rounded-lg bg-amber-100 flex items-center justify-center">
                    <svg class="w-5 h-5 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"/></svg>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-slate-500">Net</p>
                    <p class="text-xl font-bold mt-1"
                       :class="stats.net >= 0 ? 'text-emerald-600' : 'text-red-600'"
                       x-text="formatPrice(stats.net)">
                        {{ number_format((int) ($stats['net'] ?? 0), 0, ',', ' ') }} FCFA
                    </p>
                </div>
                <div class="w-11 h-11 rounded-lg bg-blue-100 flex items-center justify-center">
                    <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-slate-500">Achats impayés</p>
                    <p class="text-xl font-bold text-orange-600 mt-1"
                       x-text="formatPrice(stats.achatsImpayes)">
                        {{ number_format((int) ($stats['achatsImpayes'] ?? 0), 0, ',', ' ') }} FCFA
                    </p>
                </div>
                <div class="w-11 h-11 rounded-lg bg-orange-100 flex items-center justify-center">
                    <svg class="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-slate-500">Retours d'achat</p>
                    <p class="text-xl font-bold text-slate-700 mt-1"
                       x-text="formatPrice(stats.retoursAchat)">
                        {{ number_format((int) ($stats['retoursAchat'] ?? 0), 0, ',', ' ') }} FCFA
                    </p>
                </div>
                <div class="w-11 h-11 rounded-lg bg-slate-100 flex items-center justify-center">
                    <svg class="w-5 h-5 text-slate-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"/></svg>
                </div>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 p-5">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-sm font-medium text-slate-500">Factures impayées</p>
                    <p class="text-xl font-bold text-red-600 mt-1"
                       x-text="formatPrice(stats.facturesImpayees)">
                        {{ number_format((int) ($stats['facturesImpayees'] ?? 0), 0, ',', ' ') }} FCFA
                    </p>
                </div>
                <div class="w-11 h-11 rounded-lg bg-red-100 flex items-center justify-center">
                    <svg class="w-5 h-5 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                </div>
            </div>
        </div>
    </div>

    {{-- Chart: Évolution des ventes sur 30 jours par magasin --}}
    <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
        <div class="px-6 py-4 border-b border-slate-200">
            <h2 class="font-semibold text-slate-800">Évolution des ventes sur les 30 derniers jours</h2>
            <p class="text-sm text-slate-500 mt-0.5">Par magasin</p>
        </div>
        <div class="p-6">
            <div class="h-80">
                <canvas id="ventesChart"></canvas>
            </div>
        </div>
    </div>

    {{-- Quick actions & Recent activity --}}
    <div class="grid lg:grid-cols-2 gap-6">
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
            <div class="px-6 py-4 border-b border-slate-200">
                <h2 class="font-semibold text-slate-800">Actions rapides</h2>
            </div>
            <div class="p-6 grid sm:grid-cols-2 gap-3">
                <a href="{{ route('transferts.index') }}" class="flex items-center gap-3 p-4 rounded-lg border border-slate-200 hover:border-blue-300 hover:bg-blue-50/50 transition-colors">
                    <div class="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center shrink-0">
                        <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"/></svg>
                    </div>
                    <span class="font-medium text-slate-700">Nouveau transfert</span>
                </a>
                <a href="{{ route('ventes.index') }}" class="flex items-center gap-3 p-4 rounded-lg border border-slate-200 hover:border-emerald-300 hover:bg-emerald-50/50 transition-colors">
                    <div class="w-10 h-10 rounded-lg bg-emerald-100 flex items-center justify-center shrink-0">
                        <svg class="w-5 h-5 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
                    </div>
                    <span class="font-medium text-slate-700">Enregistrer une vente</span>
                </a>
                <a href="{{ route('clients.index') }}" class="flex items-center gap-3 p-4 rounded-lg border border-slate-200 hover:border-violet-300 hover:bg-violet-50/50 transition-colors">
                    <div class="w-10 h-10 rounded-lg bg-violet-100 flex items-center justify-center shrink-0">
                        <svg class="w-5 h-5 text-violet-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"/></svg>
                    </div>
                    <span class="font-medium text-slate-700">Ajouter un client</span>
                </a>
                <a href="{{ route('achats.index') }}" class="flex items-center gap-3 p-4 rounded-lg border border-slate-200 hover:border-amber-300 hover:bg-amber-50/50 transition-colors">
                    <div class="w-10 h-10 rounded-lg bg-amber-100 flex items-center justify-center shrink-0">
                        <svg class="w-5 h-5 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"/></svg>
                    </div>
                    <span class="font-medium text-slate-700">Nouvel achat</span>
                </a>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden">
            <div class="px-6 py-4 border-b border-slate-200 flex items-center justify-between">
                <h2 class="font-semibold text-slate-800">Activité récente</h2>
                <a href="{{ route('transferts.index') }}" class="text-sm text-blue-600 hover:text-blue-700 font-medium">Voir tout</a>
            </div>
            <div class="divide-y divide-slate-100">
                {{-- Dernier transfert --}}
                @if(($recentTransferts ?? null) && $recentTransferts->isNotEmpty())
                    @php $transfert = $recentTransferts->first(); @endphp
                    <div class="px-6 py-4 flex items-center gap-4 hover:bg-slate-50/50">
                        <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center shrink-0">
                            <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4"/></svg>
                        </div>
                        <div class="min-w-0 flex-1">
                            <p class="font-medium text-slate-800">Transfert {{ $transfert->reference }}</p>
                            <p class="text-sm text-slate-500">
                                {{ optional($transfert->magasinOrigine)->nom ?? 'N/A' }}
                                →
                                {{ optional($transfert->magasinDestination)->nom ?? 'N/A' }}
                                • {{ $transfert->quantite }} unités
                                @if($transfert->produit)
                                    • {{ $transfert->produit->designation ?? $transfert->produit->reference }}
                                @endif
                            </p>
                        </div>
                        <span class="text-sm text-slate-500 shrink-0">
                            {{ optional($transfert->date_transfert)->diffForHumans() }}
                        </span>
                    </div>
                @endif

                {{-- Dernière vente --}}
                @if(($recentVentes ?? null) && $recentVentes->isNotEmpty())
                    @php $vente = $recentVentes->first(); @endphp
                    <div class="px-6 py-4 flex items-center gap-4 hover:bg-slate-50/50">
                        <div class="w-10 h-10 rounded-full bg-emerald-100 flex items-center justify-center shrink-0">
                            <svg class="w-5 h-5 text-emerald-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
                        </div>
                        <div class="min-w-0 flex-1">
                            <p class="font-medium text-slate-800">Vente {{ $vente->reference }}</p>
                            <p class="text-sm text-slate-500">
                                Client : {{ optional($vente->client)->nom ?? 'N/A' }}
                                • {{ number_format((float) $vente->montant, 0, ',', ' ') }} FCFA
                            </p>
                        </div>
                        <span class="text-sm text-slate-500 shrink-0">
                            {{ optional($vente->date_vente)->diffForHumans() }}
                        </span>
                    </div>
                @endif

                {{-- Dernière caution / nouveau client --}}
                @if(($recentCautions ?? null) && $recentCautions->isNotEmpty())
                    @php $caution = $recentCautions->first(); @endphp
                    <div class="px-6 py-4 flex items-center gap-4 hover:bg-slate-50/50">
                        <div class="w-10 h-10 rounded-full bg-violet-100 flex items-center justify-center shrink-0">
                            <svg class="w-5 h-5 text-violet-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z"/></svg>
                        </div>
                        <div class="min-w-0 flex-1">
                            <p class="font-medium text-slate-800">Nouvelle caution client</p>
                            <p class="text-sm text-slate-500">
                                {{ optional($caution->client)->nom ?? 'Client inconnu' }}
                                • Caution :
                                {{ number_format((float) $caution->montant, 0, ',', ' ') }} FCFA
                            </p>
                        </div>
                        <span class="text-sm text-slate-500 shrink-0">
                            {{ optional($caution->date_depot)->diffForHumans() }}
                        </span>
                    </div>
                @endif

                @if(
                    (!isset($recentTransferts) || $recentTransferts->isEmpty()) &&
                    (!isset($recentVentes) || $recentVentes->isEmpty()) &&
                    (!isset($recentCautions) || $recentCautions->isEmpty())
                )
                    <div class="px-6 py-8 text-center text-sm text-slate-500">
                        Aucune activité récente pour le moment.
                    </div>
                @endif
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
<script>
function dashboardManager(initialStats, initialVentesParMagasin) {
    const magasins = Object.keys(initialVentesParMagasin || {});
    const today = new Date();

    return {
        stats: initialStats || {
            totalVentes: 0,
            totalAchats: 0,
            net: 0,
            achatsImpayes: 0,
            retoursAchat: 0,
            facturesImpayees: 0,
        },
        ventesParMagasin: initialVentesParMagasin || {},
        magasins,
        chartInstance: null,
        formatPrice(n) { return new Intl.NumberFormat('fr-FR').format(n) + ' FCFA'; },
        initChart() {
            if (typeof Chart === 'undefined') return;
            const ctx = document.getElementById('ventesChart');
            if (!ctx) return;

            const labels = [];
            for (let d = 29; d >= 0; d--) {
                const date = new Date(today);
                date.setDate(date.getDate() - d);
                labels.push(date.toLocaleDateString('fr-FR', { day: '2-digit', month: 'short' }));
            }

            const colors = [
                { border: 'rgb(16, 185, 129)', fill: 'rgba(16, 185, 129, 0.1)' },
                { border: 'rgb(59, 130, 246)', fill: 'rgba(59, 130, 246, 0.1)' },
                { border: 'rgb(245, 158, 11)', fill: 'rgba(245, 158, 11, 0.1)' }
            ];
            const datasets = this.magasins.map((mag, i) => ({
                label: mag,
                data: this.ventesParMagasin[mag].map(v => v.montant),
                borderColor: colors[i].border,
                backgroundColor: colors[i].fill,
                fill: true,
                tension: 0.3
            }));

            this.chartInstance = new Chart(ctx, {
                type: 'line',
                data: { labels, datasets },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'top' },
                        tooltip: {
                            callbacks: {
                                label: (item) => item.dataset.label + ': ' + new Intl.NumberFormat('fr-FR').format(item.raw) + ' FCFA'
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: (v) => new Intl.NumberFormat('fr-FR', { notation: 'compact' }).format(v) + ' F'
                            }
                        }
                    }
                }
            });
        }
    };
}
</script>
@endsection
