@extends('layouts.app')

@section('title', 'Ventes')
@section('page-title', 'Ventes')

@php
$clientsOptions = $clients->map(fn($c) => ['value' => $c->id, 'label' => $c->nom])->values()->all();
$produitsOptions = $produits->map(fn($p) => ['value' => $p->id, 'label' => $p->designation . ($p->reference ? ' (' . $p->reference . ')' : ''), 'prix_vente' => (float) ($p->prix_vente ?? 0)])->values()->all();
$produitsData = $produits->keyBy('id')->map(fn($p) => (float) ($p->prix_vente ?? 0))->all();
$magasinsOptions = $magasins->map(fn($m) => ['value' => $m->id, 'label' => $m->nom])->values()->all();
$modePaiementOptions = [
['value' => 'Espèce', 'label' => 'Espèce'],
['value' => 'OM', 'label' => 'Orange Money (OM)'],
['value' => 'Wave', 'label' => 'Wave'],
['value' => 'MTN', 'label' => 'MTN Money'],
['value' => 'Autre', 'label' => 'Autre'],
];
$statutOptions = [
['value' => 'en_attente', 'label' => 'En attente'],
['value' => 'partiellement', 'label' => 'Partiellement payé'],
['value' => 'paye', 'label' => 'Payé'],
];
@endphp

@section('content')
<script>
    window.__ventesStoreClientUrl = @json(route('ventes.store-client'));

</script>
<div x-data="venteManager(@js($clientsOptions), @js($produitsData))" id="vente-form">
    <x-page-card title="Liste des ventes" action="openModal()" actionLabel="Nouvelle vente">
        <div class="px-4 sm:px-6 pt-4">
            <div class="p-4 rounded-xl bg-slate-50 border border-slate-200">
                <form method="GET" action="{{ route('ventes.index') }}" class="space-y-4">
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <div>
                            <label for="date_debut" class="block text-xs font-medium text-slate-500 uppercase tracking-wider mb-1.5">
                                Date début
                            </label>
                            <input type="date" id="date_debut" name="date_debut" value="{{ request('date_debut') }}" class="form-input w-full text-sm">
                        </div>
                        <div>
                            <label for="date_fin" class="block text-xs font-medium text-slate-500 uppercase tracking-wider mb-1.5">
                                Date fin
                            </label>
                            <input type="date" id="date_fin" name="date_fin" value="{{ request('date_fin') }}" class="form-input w-full text-sm">
                        </div>
                        <div>
                            <label for="statut_paiement" class="block text-xs font-medium text-slate-500 uppercase tracking-wider mb-1.5">
                                Statut paiement
                            </label>
                            <select id="statut_paiement" name="statut_paiement" class="form-input w-full text-sm">
                                <option value="">Tous les statuts</option>
                                @foreach($statutOptions as $option)
                                <option value="{{ $option['value'] }}" @if(request('statut_paiement')===$option['value']) selected @endif>
                                    {{ $option['label'] }}
                                </option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="flex flex-wrap items-center gap-2">
                        <button type="submit" class="inline-flex items-center justify-center gap-2 px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition-colors">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
                            </svg>
                            Filtrer
                        </button>
                        <a href="{{ route('ventes.export', request()->only(['date_debut', 'date_fin', 'statut_paiement'])) }}" class="inline-flex items-center justify-center gap-2 px-5 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-medium rounded-lg transition-colors">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>
                            Exporter
                        </a>
                        @if(request()->hasAny(['date_debut', 'date_fin', 'statut_paiement']))
                        <a href="{{ route('ventes.index') }}" class="inline-flex items-center justify-center gap-2 px-5 py-2.5 border border-slate-300 hover:bg-slate-50 text-slate-700 text-sm font-medium rounded-lg transition-colors">
                            Réinitialiser
                        </a>
                        @endif
                    </div>
                </form>
            </div>
        </div>
        <div class="overflow-x-auto -mx-4 sm:mx-0">
            <table class="min-w-full divide-y divide-slate-200">
                <thead>
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Réf.</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Client</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Produit</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Magasin</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Montant Payé</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Montant Restant</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Mode paiement</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Statut paiement</th>
                        <th class="px-4 py-3 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Date</th>
                        <th class="px-4 py-3 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider w-24">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    @forelse($ventes as $index => $v)
                    <tr class="hover:bg-slate-50/50 transition-colors">
                        <td class="px-4 py-3 font-mono text-sm text-slate-600">{{ $v->reference }}</td>
                        <td class="px-4 py-3 font-medium text-slate-800">{{ $v->client->nom }}</td>
                        <td class="px-4 py-3 text-slate-600">{{ $v->produit?->designation ?? '—' }}</td>
                        <td class="px-4 py-3 text-slate-600">{{ $v->magasin->nom }}</td>
                        <td class="px-4 py-3 font-semibold text-slate-800">
                            {{ number_format($v->montant - (optional($v->creance)->montant_restant ?? 0), 0, ',', ' ') }} FCFA
                        </td>
                        <td class="px-4 py-3 font-semibold text-slate-800">
                            {{ number_format(optional($v->creance)->montant_restant ?? 0, 0, ',', ' ') }} FCFA
                        </td>
                        <td class="px-4 py-3 text-slate-600">
                            {{ optional($v->paiement)->mode_paiement ?? '—' }}
                        </td>
                        <td class="px-4 py-3">
                            @php
                            $statutClasses = [
                            'paye' => 'bg-emerald-100 text-emerald-700',
                            'partiellement' => 'bg-amber-100 text-amber-700',
                            'en_attente' => 'bg-slate-100 text-slate-700',
                            ];
                            $statutLabels = ['paye' => 'Payé', 'partiellement' => 'Partiellement', 'en_attente' => 'En attente'];
                            @endphp
                            <span class="inline-flex px-2 py-1 rounded-md text-xs font-medium {{ $statutClasses[$v->statut_paiement] ?? 'bg-slate-100 text-slate-600' }}">
                                {{ $statutLabels[$v->statut_paiement] ?? $v->statut_paiement }}
                            </span>
                        </td>
                        <td class="px-4 py-3 text-slate-600">{{ $v->date_vente->format('d/m/Y') }}</td>
                        <td class="px-4 py-3">
                            <x-action-buttons :viewAction="'viewVente(' . json_encode([
                                    'reference' => $v->reference,
                                    'client' => $v->client->nom,
                                    'produit' => $v->produit?->designation ?? '—',
                                    'magasin' => $v->magasin->nom,
                                    'montant' => (float) $v->montant,
                                    'montant_paye' => (float) ($v->montant - (optional($v->creance)->montant_restant ?? 0)),
                                    'mode_paiement' => optional($v->paiement)->mode_paiement ?? '—',
                                    'statut_paiement' => $v->statut_paiement,
                                    'date' => $v->date_vente->format('d/m/Y'),
                                ]) . ')'" :editUrl="null" />

                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="9" class="px-4 py-8 text-center text-slate-500">Aucune vente enregistrée</td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @if($ventes->hasPages())
        <div class="mt-4 px-4">
            {{ $ventes->links() }}
        </div>
        @endif
    </x-page-card>

    <div x-show="showModal" x-cloak class="fixed inset-0 z-50 overflow-y-auto">
        <div class="flex min-h-screen items-center justify-center p-4">
            <div x-show="showModal" @click="showModal = false" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm"></div>
            <div x-show="showModal" x-transition:enter="ease-out duration-200" x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100" class="relative bg-white rounded-2xl shadow-2xl max-w-2xl w-full overflow-hidden">
                <div class="px-6 py-5 border-b border-slate-100 bg-gradient-to-b from-slate-50 to-white">
                    <h3 class="text-lg font-semibold text-slate-800">Nouvelle vente</h3>
                    <p class="text-sm text-slate-500 mt-1">Enregistrer une vente pour un client</p>
                </div>
                <form action="{{ route('ventes.store') }}" method="POST" @create-requested="openNewClientModal()" class="p-6 space-y-6">
                    @csrf
                    <input type="hidden" name="client_id" :value="form.client_id">
                    <input type="hidden" name="produit_id" :value="form.produit_id">
                    <input type="hidden" name="magasin_id" :value="form.magasin_id">
                    <input type="hidden" name="mode_paiement" :value="form.mode_paiement">
                    <input type="hidden" name="statut_paiement" :value="form.statut_paiement">
                    <input type="hidden" name="montant_paye" :value="form.montant_paye">
                    {{-- Client & Produit --}}
                    <div>
                        <div class="flex items-center gap-2 mb-4">
                            <div class="h-px flex-1 bg-slate-200"></div>
                            <span class="text-xs font-semibold text-slate-500 uppercase tracking-wider">Client & Produit</span>
                            <div class="h-px flex-1 bg-slate-200"></div>
                        </div>
                        <div class="space-y-4">
                            <x-form-group label="Client" :required="true">
                                <x-searchable-select form-id="vente-form" model="client_id" placeholder="Sélectionner un client" :options="$clientsOptions" options-key="clientOptions" :allow-create="true" create-label="Ajouter un nouveau client" />
                            </x-form-group>
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <x-form-group label="Produit" :required="true">
                                    <x-searchable-select form-id="vente-form" model="produit_id" placeholder="Sélectionner un produit" :options="$produitsOptions" />
                                </x-form-group>
                                <x-form-group label="Magasin" :required="true">
                                    <x-searchable-select form-id="vente-form" model="magasin_id" placeholder="Sélectionner un magasin" :options="$magasinsOptions" />
                                </x-form-group>
                            </div>
                        </div>
                    </div>
                    {{-- Montant & Paiement --}}
                    <div class="space-y-5">
                        <div class="flex items-center gap-2 mb-4">
                            <div class="h-px flex-1 bg-slate-200"></div>
                            <span class="text-xs font-semibold text-slate-500 uppercase tracking-wider">Montant & Paiement</span>
                            <div class="h-px flex-1 bg-slate-200"></div>
                        </div>
                        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-12 gap-4">
                            <x-form-group label="Quantité" :required="true">
                                <input type="number" name="quantite" x-model="form.quantite" min="1" required class="form-input" placeholder="1">
                            </x-form-group>
                            <x-form-group label="Montant total (FCFA)" :required="true">
                                <input type="number" name="montant" x-model="form.montant" min="0" required class="form-input" placeholder="0">
                            </x-form-group>


                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-12 gap-4">
                            <x-form-group label="Montant payé (FCFA)" help="Pour « Partiellement », indiquez le montant perçu">
                                <input type="number" name="montant_paye" x-model="form.montant_paye" min="0" :max="form.montant" class="form-input" placeholder="0">
                            </x-form-group>
                            <x-form-group label="Mode de paiement">
                                <select name="mode_paiement" x-model="form.mode_paiement" class="form-select">
                                    <option value="" disabled>Sélectionner un mode</option>
                                    <option value="Espèce">Espèce</option>
                                    <option value="OM">Orange Money (OM)</option>
                                    <option value="Wave">Wave</option>
                                    <option value="MTN">MTN Money</option>
                                    <option value="Autre">Autre</option>
                                </select>
                            </x-form-group>


                        </div>
                    </div>
                    @if($errors->any())
                    <div class="p-3 rounded-lg bg-red-50 border border-red-100 text-red-700 text-sm">
                        @foreach($errors->all() as $error)
                        <p>{{ $error }}</p>
                        @endforeach
                    </div>
                    @endif
                    <div class="flex gap-3 pt-2 border-t border-slate-100">
                        <button type="submit" class="form-btn-primary flex-1">
                            Enregistrer
                        </button>
                        <button type="button" @click="showModal = false" class="form-btn-secondary">Annuler</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    {{-- Modal : Ajouter un nouveau client (depuis le formulaire de vente) --}}
    <div x-show="showClientModal" x-cloak class="fixed inset-0 z-[60] overflow-y-auto">
        <div class="flex min-h-screen items-center justify-center p-4">
            <div x-show="showClientModal" @click="showClientModal = false" class="fixed inset-0 bg-slate-900/60 backdrop-blur-sm"></div>
            <div x-show="showClientModal" x-transition:enter="ease-out duration-200" x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100" class="relative bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden">
                <div class="px-6 py-5 border-b border-slate-100 bg-gradient-to-b from-slate-50 to-white">
                    <h3 class="text-lg font-semibold text-slate-800">Nouveau client</h3>
                    <p class="text-sm text-slate-500 mt-1">Le client sera ajouté à la liste et sélectionné pour cette vente.</p>
                </div>
                <form @submit.prevent="saveNewClient()" class="p-6 space-y-6">
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <x-form-group label="Nom complet" :required="true">
                            <input type="text" x-model="clientForm.nom" required class="form-input" placeholder="Ex: Jean Dupont">
                        </x-form-group>
                        <x-form-group label="Téléphone" :required="true">
                            <input type="tel" x-model="clientForm.telephone" required class="form-input" placeholder="+225 07 00 00 00 00">
                        </x-form-group>
                    </div>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <x-form-group label="Adresse">
                            <input type="text" x-model="clientForm.adresse" class="form-input" placeholder="Ex: Cocody, Abidjan">
                        </x-form-group>
                        <x-form-group label="Caution (FCFA)" help="Obligatoire pour un nouveau client">
                            <input type="number" x-model="clientForm.caution" min="0" required class="form-input" placeholder="0">
                        </x-form-group>
                    </div>
                    <div class="flex gap-3 pt-2">
                        <button type="submit" class="form-btn-primary flex-1">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" /></svg>
                            Enregistrer et sélectionner
                        </button>
                        <button type="button" @click="showClientModal = false" class="form-btn-secondary">Annuler</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <x-detail-modal showVar="showDetailModal" title="Détails de la vente" subtitleVar="detailReference">
        <template x-if="selectedItem">
            <div class="space-y-1">
                <div class="flex items-center gap-3 p-4 rounded-xl bg-emerald-50 border border-emerald-100 mb-4">
                    <div class="w-12 h-12 rounded-xl bg-emerald-100 flex items-center justify-center shrink-0">
                        <svg class="w-6 h-6 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>
                        <p class="font-mono font-semibold text-emerald-800" x-text="selectedItem.reference"></p>
                        <p class="text-lg font-bold text-emerald-700" x-text="formatPrice(selectedItem.montant)"></p>
                    </div>
                </div>
                <dl class="divide-y divide-slate-100">
                    <div class="flex flex-col sm:flex-row sm:items-center py-3 border-b border-slate-100 gap-1 sm:gap-4">
                        <dt class="text-sm font-medium text-slate-500 shrink-0 sm:w-40">Référence</dt>
                        <dd class="font-mono font-semibold text-slate-800" x-text="selectedItem.reference"></dd>
                    </div>
                    <div class="flex flex-col sm:flex-row sm:items-center py-3 border-b border-slate-100 gap-1 sm:gap-4">
                        <dt class="text-sm font-medium text-slate-500 shrink-0 sm:w-40">Client</dt>
                        <dd class="font-semibold text-slate-800" x-text="selectedItem.client"></dd>
                    </div>
                    <div class="flex flex-col sm:flex-row sm:items-center py-3 border-b border-slate-100 gap-1 sm:gap-4">
                        <dt class="text-sm font-medium text-slate-500 shrink-0 sm:w-40">Produit</dt>
                        <dd class="font-semibold text-slate-800" x-text="selectedItem.produit || '—'"></dd>
                    </div>
                    <div class="flex flex-col sm:flex-row sm:items-center py-3 border-b border-slate-100 gap-1 sm:gap-4">
                        <dt class="text-sm font-medium text-slate-500 shrink-0 sm:w-40">Magasin</dt>
                        <dd class="font-semibold text-slate-800" x-text="selectedItem.magasin"></dd>
                    </div>
                    <div class="flex flex-col sm:flex-row sm:items-center py-3 border-b border-slate-100 gap-1 sm:gap-4">
                        <dt class="text-sm font-medium text-slate-500 shrink-0 sm:w-40">Montant total</dt>
                        <dd class="font-semibold text-emerald-600 text-lg" x-text="formatPrice(selectedItem.montant)"></dd>
                    </div>
                    <template x-if="selectedItem.statut_paiement === 'partiellement'">
                        <div class="space-y-2 py-3 border-b border-slate-100">
                            <div class="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-4">
                                <dt class="text-sm font-medium text-slate-500 shrink-0 sm:w-40">Montant payé</dt>
                                <dd class="font-semibold text-emerald-600" x-text="formatPrice(selectedItem.montant_paye || 0)"></dd>
                            </div>
                            <div class="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-4">
                                <dt class="text-sm font-medium text-slate-500 shrink-0 sm:w-40">Reste à payer</dt>
                                <dd class="font-semibold text-amber-600" x-text="formatPrice((selectedItem.montant || 0) - (selectedItem.montant_paye || 0))"></dd>
                            </div>
                        </div>
                    </template>
                    <div class="flex flex-col sm:flex-row sm:items-center py-3 border-b border-slate-100 gap-1 sm:gap-4">
                        <dt class="text-sm font-medium text-slate-500 shrink-0 sm:w-40">Mode de paiement</dt>
                        <dd class="font-semibold text-slate-800" x-text="selectedItem.mode_paiement || '—'"></dd>
                    </div>
                    <div class="flex flex-col sm:flex-row sm:items-center py-3 border-b border-slate-100 gap-1 sm:gap-4">
                        <dt class="text-sm font-medium text-slate-500 shrink-0 sm:w-40">Statut paiement</dt>
                        <dd><span :class="getStatutClass(selectedItem.statut_paiement)" class="inline-flex px-2 py-1 rounded-md text-xs font-medium" x-text="getStatutLabel(selectedItem.statut_paiement)"></span></dd>
                    </div>
                    <div class="flex flex-col sm:flex-row sm:items-center py-3 gap-1 sm:gap-4">
                        <dt class="text-sm font-medium text-slate-500 shrink-0 sm:w-40">Date</dt>
                        <dd class="font-semibold text-slate-800" x-text="selectedItem.date"></dd>
                    </div>
                </dl>
            </div>
        </template>
    </x-detail-modal>

    <x-delete-modal>
        Êtes-vous sûr de vouloir supprimer la vente « <span x-text="deleteLabel"></span> » ? Cette action est irréversible.
    </x-delete-modal>
</div>

<script src="{{ asset('js/ventes.js') }}"></script>
@endsection
