<?php
use function Laravel\Folio\{middleware, name};
use App\Models\Client;
use App\Models\Payment;
use App\Models\Order;
use App\Models\FibreType;
use App\Models\Discount;
use Livewire\Attributes\Validate;
use Livewire\Volt\Component;
middleware('auth');

name('client.payments');

new class extends Component {
    public $client;
    public $payments;
    public $discounts;
    public $clientId;

    // Order form fields
    #[Validate('required|exists:fibre_types,id')]
    public $fibre_type_id = '';

    #[Validate('required|numeric|min:0.01')]
    public $quantity = '';

    #[Validate('required|numeric|min:0.01')]
    public $unit_price = '';

    #[Validate('required|numeric|min:0.01')]
    public $total_price = '';

    #[Validate('required|date')]
    public $creation_date = '';

    // Edit order fields
    public $editingOrderId = null;
    public $oldFibreTypeId = null;
    public $oldQuantity = 0;

    public $fibreTypes;
    public $availableStock = 0;

    // Payment form fields
    #[Validate('required|numeric|min:0.01')]
    public $amount = '';

    #[Validate('required|in:cash,trait,cheque')]
    public $payment_mode = 'cash';

    #[Validate('nullable|date')]
    public $date_entree = '';

    #[Validate('nullable|date')]
    public $date_activation = '';

    #[Validate('nullable|string|max:255')]
    public $instrument_owner = '';

    #[Validate('nullable|string|max:255')]
    public $instrument_number = '';

    // Edit payment fields
    public $editingPaymentId = null;
    public $payment_creation_date = '';

    // Discount form fields
    #[Validate('required|numeric|min:0.01')]
    public $discount_amount = '';

    #[Validate('nullable|string|max:255')]
    public $discount_reason = '';

    #[Validate('nullable|date')]
    public $discount_date = '';

    public function mount()
    {
        $this->clientId = request()->route('id');
        $this->client = Client::with(['orders.fibreType', 'payments', 'discounts'])->findOrFail($this->clientId);
        $this->payments = $this->client->payments()->latest()->get();
        $this->discounts = $this->client->discounts()->latest()->get();
        $this->fibreTypes = FibreType::all();
        $this->creation_date = now()->toDateString();
        $this->payment_creation_date = now()->toDateString();
        $this->discount_date = now()->toDateString();
    }

    public function openCreateModal()
    {
        $this->reset(['fibre_type_id', 'quantity', 'unit_price', 'total_price', 'availableStock']);
        $this->creation_date = now()->toDateString();
        $this->availableStock = 0;
        $this->total_price = '';
    }

    public function openEditModal($orderId)
    {
        $order = Order::findOrFail($orderId);
        $this->editingOrderId = $orderId;
        $this->fibre_type_id = $order->fibre_type_id;
        $this->quantity = $order->quantity;
        $this->unit_price = $order->unit_price;
        $this->total_price = $order->total_price;
        $this->creation_date = optional($order->creation_date)->format('Y-m-d') ?? now()->toDateString();
        
        $this->oldFibreTypeId = $order->fibre_type_id;
        $this->oldQuantity = $order->quantity;

        // Calculate available stock
        $stock = \App\Models\Stock::where('fibre_type_id', $order->fibre_type_id)->first();
        if ($stock) {
            $this->availableStock = $stock->quantity + $order->quantity; // Add back the order quantity
        } else {
            $this->availableStock = 0;
        }
    }

    public function updatedFibreTypeId()
    {
        if ($this->fibre_type_id) {
            $stock = \App\Models\Stock::where('fibre_type_id', $this->fibre_type_id)->first();
            if ($this->editingOrderId && $this->fibre_type_id == $this->oldFibreTypeId) {
                // Same fibre type: add back the old order quantity
                $this->availableStock = $stock ? ($stock->quantity + $this->oldQuantity) : 0;
            } else {
                $this->availableStock = $stock ? $stock->quantity : 0;
            }
            $this->recalculateTotal();
        } else {
            $this->availableStock = 0;
        }
    }

    public function updatedQuantity()
    {
        $this->recalculateTotal();
    }

    public function updatedUnitPrice()
    {
        $this->recalculateTotal();
    }

    protected function recalculateTotal()
    {
        if ($this->quantity && $this->unit_price) {
            $this->total_price = (float)$this->unit_price * (float)$this->quantity;
        }
    }

    public function saveOrder()
    {
        try {
            // Recalculate total before validation
            $this->recalculateTotal();
            
            $validated = $this->validate([
                'fibre_type_id' => 'required|exists:fibre_types,id',
                'quantity' => 'required|numeric|min:0.01',
                'unit_price' => 'required|numeric|min:0.01',
                'total_price' => 'required|numeric|min:0.01',
                'creation_date' => 'required|date',
            ]);

            // Check if there's enough stock
            $stock = \App\Models\Stock::where('fibre_type_id', $validated['fibre_type_id'])->first();
            
            if (!$stock) {
                $this->dispatch('toast', type: 'error', message: 'Aucun stock disponible pour ce type de fil.');
                return;
            }

            $availableStock = $stock->quantity;
            if ($availableStock < $validated['quantity']) {
                $this->dispatch('toast', type: 'error', message: 'Stock insuffisant. Disponible: ' . number_format($availableStock, 2) . ' kg, Demandé: ' . number_format($validated['quantity'], 2) . ' kg');
                return;
            }

            // Create the order
            $order = Order::create([
                'client_id' => $this->clientId,
                'fibre_type_id' => $validated['fibre_type_id'],
                'quantity' => $validated['quantity'],
                'unit_price' => $validated['unit_price'],
                'total_price' => (float)$validated['unit_price'] * (float)$validated['quantity'],
                'creation_date' => $validated['creation_date'],
            ]);

            // Record the stock movement
            $quantityBefore = $stock->quantity;
            $stock->quantity -= $validated['quantity'];
            $stock->save();

            \App\Models\StockMovement::create([
                'fibre_type_id' => $validated['fibre_type_id'],
                'type' => 'out',
                'quantity' => $validated['quantity'],
                'quantity_before' => $quantityBefore,
                'quantity_after' => $stock->quantity,
                'reason' => 'Order #' . $order->id,
                'reference_type' => 'order',
                'reference_id' => $order->id,
                'notes' => 'Stock reduction for order',
            ]);

            $this->refreshData();
            $this->reset(['fibre_type_id', 'quantity', 'unit_price', 'total_price', 'availableStock']);
            $this->dispatch('close-create-modal');
            $this->dispatch('toast', type: 'success', message: 'Commande créée avec succès.');
        } catch (\Illuminate\Validation\ValidationException $e) {
            // Les erreurs de validation seront affichées automatiquement par Livewire
            $this->dispatch('toast', type: 'error', message: 'Veuillez remplir tous les champs requis.');
        } catch (\Exception $e) {
            $this->dispatch('toast', type: 'error', message: 'Une erreur est survenue: ' . $e->getMessage());
        }
    }

    public function updateOrder()
    {
        try {
            // Recalculate total before validation
            $this->recalculateTotal();
            
            $validated = $this->validate([
                'fibre_type_id' => 'required|exists:fibre_types,id',
                'quantity' => 'required|numeric|min:0.01',
                'unit_price' => 'required|numeric|min:0.01',
                'total_price' => 'required|numeric|min:0.01',
                'creation_date' => 'required|date',
            ]);
            
            $order = Order::findOrFail($this->editingOrderId);

            // Restore stock for old fibre type
            if ($this->oldFibreTypeId && $this->oldQuantity > 0) {
                $oldStock = \App\Models\Stock::where('fibre_type_id', $this->oldFibreTypeId)->first();
                if ($oldStock) {
                    $quantityBefore = $oldStock->quantity;
                    $oldStock->quantity += $this->oldQuantity;
                    $oldStock->save();
                    
                    \App\Models\StockMovement::create([
                        'fibre_type_id' => $this->oldFibreTypeId,
                        'type' => 'in',
                        'quantity' => $this->oldQuantity,
                        'quantity_before' => $quantityBefore,
                        'quantity_after' => $oldStock->quantity,
                        'reason' => 'Order #' . $order->id . ' updated - restoring original stock',
                        'reference_type' => 'order',
                        'reference_id' => $order->id,
                        'notes' => 'Stock restoration before order modification',
                    ]);
                }
            }

            // Check and reduce stock for new fibre type
            $newStock = \App\Models\Stock::where('fibre_type_id', $validated['fibre_type_id'])->first();
            if (!$newStock) {
                $this->dispatch('toast', type: 'error', message: 'Aucun stock disponible pour ce type de fil.');
                return;
            }

            if ($newStock->quantity < $validated['quantity']) {
                $this->dispatch('toast', type: 'error', message: 'Stock insuffisant. Disponible: ' . number_format($newStock->quantity, 2) . ' kg, Demandé: ' . number_format($validated['quantity'], 2) . ' kg');
                return;
            }

            $quantityBefore = $newStock->quantity;
            $newStock->quantity -= $validated['quantity'];
            $newStock->save();

            \App\Models\StockMovement::create([
                'fibre_type_id' => $validated['fibre_type_id'],
                'type' => 'out',
                'quantity' => $validated['quantity'],
                'quantity_before' => $quantityBefore,
                'quantity_after' => $newStock->quantity,
                'reason' => 'Order #' . $order->id . ' updated',
                'reference_type' => 'order',
                'reference_id' => $order->id,
                'notes' => 'Stock reduction for updated order',
            ]);

            // Update the order
            $order->update([
                'fibre_type_id' => $validated['fibre_type_id'],
                'quantity' => $validated['quantity'],
                'unit_price' => $validated['unit_price'],
                'total_price' => (float)$validated['unit_price'] * (float)$validated['quantity'],
                'creation_date' => $validated['creation_date'],
            ]);

            $this->refreshData();
            $this->reset(['editingOrderId', 'oldFibreTypeId', 'oldQuantity', 'fibre_type_id', 'quantity', 'unit_price', 'total_price', 'availableStock']);
            $this->dispatch('close-edit-modal');
            $this->dispatch('toast', type: 'success', message: 'Commande mise à jour avec succès.');
        } catch (\Illuminate\Validation\ValidationException $e) {
            // Les erreurs de validation seront affichées automatiquement par Livewire
            $this->dispatch('toast', type: 'error', message: 'Veuillez remplir tous les champs requis.');
        } catch (\Exception $e) {
            $this->dispatch('toast', type: 'error', message: 'Une erreur est survenue: ' . $e->getMessage());
        }
    }

    protected function refreshData()
    {
        $this->client->refresh();
        $this->client->load(['orders.fibreType', 'payments', 'discounts']);
        $this->payments = $this->client->payments()->latest()->get();
        $this->discounts = $this->client->discounts()->latest()->get();
    }

    public function openCreatePaymentModal()
    {
        $this->reset(['amount', 'payment_mode', 'date_entree', 'date_activation', 'instrument_owner', 'instrument_number']);
        $this->payment_mode = 'cash';
        $this->payment_creation_date = now()->toDateString();
    }

    public function openEditPaymentModal($paymentId)
    {
        $payment = Payment::findOrFail($paymentId);
        $this->editingPaymentId = $paymentId;
        $this->amount = $payment->amount;
        $this->payment_mode = $payment->payment_mode;
        $this->payment_creation_date = $payment->creation_date?->format('Y-m-d') ?? now()->toDateString();
        $this->date_entree = $payment->date_entree?->format('Y-m-d') ?? '';
        $this->date_activation = $payment->date_activation?->format('Y-m-d') ?? '';
        $this->instrument_owner = $payment->instrument_owner ?? '';
        $this->instrument_number = $payment->instrument_number ?? '';
    }

    public function savePayment()
    {
        $validated = $this->validate([
            'amount' => 'required|numeric|min:0.01',
            'payment_mode' => 'required|in:cash,trait,cheque',
            'payment_creation_date' => 'required|date',
            'date_entree' => 'nullable|date',
            'date_activation' => 'nullable|date',
            'instrument_owner' => 'nullable|string|max:255',
            'instrument_number' => 'nullable|string|max:255',
        ]);

        $isInstrument = in_array($validated['payment_mode'], ['cheque', 'trait']);
        
        $paymentData = [
            'client_id' => $this->clientId,
            'amount' => $validated['amount'],
            'payment_mode' => $validated['payment_mode'],
            'status' => 'validated',
            'creation_date' => $validated['payment_creation_date'],
        ];

        if ($isInstrument) {
            $paymentData['date_entree'] = !empty($validated['date_entree']) ? $validated['date_entree'] : null;
            $paymentData['date_activation'] = !empty($validated['date_activation']) ? $validated['date_activation'] : null;
            $paymentData['instrument_owner'] = !empty($validated['instrument_owner']) ? $validated['instrument_owner'] : null;
            $paymentData['instrument_number'] = !empty($validated['instrument_number']) ? $validated['instrument_number'] : null;
        } else {
            $paymentData['date_entree'] = null;
            $paymentData['date_activation'] = null;
            $paymentData['instrument_owner'] = null;
            $paymentData['instrument_number'] = null;
        }

        Payment::create($paymentData);

        $this->refreshData();
        $this->reset(['amount', 'payment_mode', 'date_entree', 'date_activation', 'instrument_owner', 'instrument_number']);
        $this->dispatch('close-create-payment-modal');
        $this->dispatch('toast', type: 'success', message: 'Paiement créé avec succès.');
    }

    public function updatePayment()
    {
        $validated = $this->validate([
            'amount' => 'required|numeric|min:0.01',
            'payment_mode' => 'required|in:cash,trait,cheque',
            'payment_creation_date' => 'required|date',
            'date_entree' => 'nullable|date',
            'date_activation' => 'nullable|date',
            'instrument_owner' => 'nullable|string|max:255',
            'instrument_number' => 'nullable|string|max:255',
        ]);

        $payment = Payment::findOrFail($this->editingPaymentId);
        $isInstrument = in_array($validated['payment_mode'], ['cheque', 'trait']);
        
        $paymentData = [
            'amount' => $validated['amount'],
            'payment_mode' => $validated['payment_mode'],
            'status' => 'validated',
            'creation_date' => $validated['payment_creation_date'],
        ];

        if ($isInstrument) {
            $paymentData['date_entree'] = !empty($validated['date_entree']) ? $validated['date_entree'] : null;
            $paymentData['date_activation'] = !empty($validated['date_activation']) ? $validated['date_activation'] : null;
            $paymentData['instrument_owner'] = !empty($validated['instrument_owner']) ? $validated['instrument_owner'] : null;
            $paymentData['instrument_number'] = !empty($validated['instrument_number']) ? $validated['instrument_number'] : null;
        } else {
            $paymentData['date_entree'] = null;
            $paymentData['date_activation'] = null;
            $paymentData['instrument_owner'] = null;
            $paymentData['instrument_number'] = null;
        }

        $payment->update($paymentData);

        $this->refreshData();
        $this->reset(['editingPaymentId', 'amount', 'payment_mode', 'date_entree', 'date_activation', 'instrument_owner', 'instrument_number']);
        $this->dispatch('close-edit-payment-modal');
        $this->dispatch('toast', type: 'success', message: 'Paiement mis à jour avec succès.');
    }

    public function deletePayment($paymentId)
    {
        Payment::find($paymentId)->delete();
        $this->refreshData();
        $this->dispatch('toast', type: 'success', message: 'Paiement supprimé avec succès.');
    }

    public function deleteOrder($orderId)
    {
        $order = Order::findOrFail($orderId);
        
        // Restore stock before deleting the order
        $stock = \App\Models\Stock::where('fibre_type_id', $order->fibre_type_id)->first();
        
        if ($stock) {
            $quantityBefore = $stock->quantity;
            $stock->quantity += $order->quantity; // Restore the stock
            $stock->save();
            
            // Record the stock movement (restoration)
            \App\Models\StockMovement::create([
                'fibre_type_id' => $order->fibre_type_id,
                'type' => 'in',
                'quantity' => $order->quantity,
                'quantity_before' => $quantityBefore,
                'quantity_after' => $stock->quantity,
                'reason' => 'Order #' . $order->id . ' deleted',
                'reference_type' => 'order',
                'reference_id' => $order->id,
                'notes' => 'Stock restoration for deleted order',
            ]);
        }
        
        // Delete the order
        $order->delete();
        
        $this->refreshData();
        $this->dispatch('toast', type: 'success', message: 'Commande supprimée avec succès. Le stock a été restauré.');
    }

    public function openCreateDiscountModal()
    {
        $this->reset(['discount_amount', 'discount_reason', 'discount_date']);
        $this->discount_date = now()->toDateString();
    }

    public function saveDiscount()
    {
        $validated = $this->validate([
            'discount_amount' => 'required|numeric|min:0.01',
            'discount_reason' => 'nullable|string|max:255',
            'discount_date' => 'nullable|date',
        ]);

        $discount = $this->client->applyDiscount(
            $validated['discount_amount'],
            $validated['discount_reason'] ?? null
        );

        // Set date if provided
        if (isset($validated['discount_date'])) {
            $discount->date = $validated['discount_date'];
            $discount->save();
        }

        $this->refreshData();
        $this->reset(['discount_amount', 'discount_reason', 'discount_date']);
        $this->dispatch('close-create-discount-modal');
        $this->dispatch('toast', type: 'success', message: 'Remise appliquée avec succès.');
    }

    public function deleteDiscount($discountId)
    {
        Discount::findOrFail($discountId)->delete();
        $this->refreshData();
        $this->dispatch('toast', type: 'success', message: 'Remise supprimée avec succès.');
    }
};
?>

<x-layouts.app>
    @volt('client.payments')
        <x-app.container class="max-w-full">
            <x-elements.back-button
                class="max-w-full mx-auto mb-3"
                text="Retour à la liste des clients"
                :href="route('clients')"
            />
            
            @if(session()->has('message'))
                <div class="mb-4 p-4 bg-green-100 border border-green-400 text-green-700 rounded">
                    {{ session('message') }}
                </div>
            @endif

            @if(session()->has('error'))
                <div class="mb-4 p-4 bg-red-100 border border-red-400 text-red-700 rounded">
                    {{ session('error') }}
                </div>
            @endif

            <div class="flex items-center justify-between mb-5">
                <x-app.heading
                    title="Paiements de {{ $this->client->firstname }} {{ $this->client->lastname }}"
                    description="Historique des paiements et crédit restant du client"
                    :border="false"
                />
            </div>

            <!-- Résumé du client -->
            <div class="mb-6">
                <div class="flex flex-col md:flex-row gap-6">
                    <!-- Carte Total des commandes -->
                    <div class="flex-1 text-center p-4 bg-gray-50 rounded-lg border border-gray-200">
                        <div class="text-2xl font-bold text-gray-900 mb-1">{{ number_format($this->client->total_orders, 2) }} DT</div>
                        <div class="text-sm text-gray-500">Total des commandes</div>
                    </div>
                    
                    <!-- Carte Total des paiements -->
                    <div class="flex-1 text-center p-4 bg-gray-50 rounded-lg border border-gray-200">
                        <div class="text-2xl font-bold text-gray-900 mb-1">{{ number_format($this->client->total_payments, 2) }} DT</div>
                        <div class="text-sm text-gray-500">Total des paiements</div>
                    </div>
                    
                    <!-- Carte Total des remises -->
                    <div class="flex-1 text-center p-4 bg-gray-50 rounded-lg border border-gray-200">
                        <div class="text-2xl font-bold text-orange-600 mb-1">{{ number_format($this->client->total_discounts, 2) }} DT</div>
                        <div class="text-sm text-gray-500">Total des remises</div>
                    </div>
                    
                    <!-- Carte Crédit restant -->
                    <div class="flex-1 text-center p-4 bg-gray-50 rounded-lg border border-gray-200">
                        <div class="text-2xl font-bold mb-1 {{ $this->client->remaining_credit > 0 ? 'text-red-600' : ($this->client->remaining_credit < 0 ? 'text-green-600' : 'text-gray-600') }}">
                            {{ number_format($this->client->remaining_credit, 2) }} DT
                        </div>
                        <div class="text-sm text-gray-500">Crédit restant</div>
                    </div>
                </div>
            </div>

            <!-- Résumé des commandes -->
            <div class="mb-6">
            <div class="flex items-center justify-between mb-5 ">
                <h3 class="text-lg font-medium text-gray-900 mb-3">Résumé des commandes</h3>
                <button 
                    type="button" 
                    wire:click="openCreateModal"
                    x-on:click="$dispatch('open-create-modal')"
                    class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 border border-transparent rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                    Nouvelle commande
                </button>
            </div>
                @if($this->client->orders->isEmpty())
                    <p class="text-gray-500">Aucune commande trouvée pour ce client.</p>
                @else
                    <div class="overflow-x-auto border rounded-lg">
                        <table class="min-w-full bg-white">
                            <thead class="text-sm bg-gray-200">
                                <tr>
                                    <th class="px-4 py-2 text-left">Commande #</th>
                                    <th class="px-4 py-2 text-left">Type de fibre</th>
                                    <th class="px-4 py-2 text-left">Quantité (kg)</th>
                                    <th class="px-4 py-2 text-left">Prix total</th>
                                    <th class="px-4 py-2 text-left">Date de la commande</th>
                                    <th class="px-4 py-2 text-left">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($this->client->orders as $order)
                                    <tr>
                                        <td class="px-4 py-2">#{{ $order->id }}</td>
                                        <td class="px-4 py-2">
                                            <div class="flex items-center">
                                                <span>{{ $order->fibreType->name }} ({{ $order->fibreType->color }})</span>
                                            </div>
                                        </td>
                                        <td class="px-4 py-2">{{ number_format($order->quantity, 2) }}</td>
                                        <td class="px-4 py-2">{{ number_format($order->total_price, 2) }} DT</td>
                                        <td class="px-4 py-2">{{ $order->creation_date ? $order->creation_date->format('d/m/Y') : '-' }}</td>
                                        <td class="px-4 py-2 text-left">
                                            <div class="flex space-x-2">
                                                <button 
                                                    type="button"
                                                    wire:click="openEditModal({{ $order->id }})"
                                                    x-on:click="$dispatch('open-edit-modal')"
                                                    class="p-2 text-white bg-blue-600 rounded hover:bg-blue-700 transition-colors"
                                                    title="Modifier la commande"
                                                >
                                                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                                    </svg>
                                                </button>
                                                <x-button 
                                                    tag="a" 
                                                    href="/order/{{ $order->id }}/pdf"
                                                    class="p-2 text-white bg-green-600 rounded hover:bg-green-700 transition-colors"
                                                    title="Générer le PDF"
                                                >
                                                    <svg class="h-4 w-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"></path>
                                                    </svg>
                                                </x-button>
                                                <button 
                                                    type="button" 
                                                    wire:click="deleteOrder({{ $order->id }})"
                                                    wire:confirm="Êtes-vous sûr de vouloir supprimer cette commande ?"
                                                    class="p-2 text-white bg-red-600 rounded hover:bg-red-700 transition-colors"
                                                    title="Supprimer la commande"
                                                >
                                                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                                    </svg>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                @endif
            </div>

            <!-- Historique des paiements -->
            <div class="mb-6">
            <div class="flex items-center justify-between mb-5 ">
                <h3 class="text-lg font-medium text-gray-900 mb-3">Historique des paiements</h3>
                <button 
                    type="button" 
                    wire:click="openCreatePaymentModal"
                    x-on:click="$dispatch('open-create-payment-modal')"
                    class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 border border-transparent rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                >
                    Nouveau paiement
                </button>
            </div>
                @if($this->payments->isEmpty())
                    <div class="w-full p-20 text-center bg-gray-100 rounded-xl">
                        <p class="text-gray-500">Aucun paiement trouvé pour ce client.</p>
                    </div>
                @else
                    <div class="overflow-x-auto border rounded-lg">
                        <table class="min-w-full bg-white">
                            <thead class="text-sm bg-gray-200">
                                <tr>
                                    <th class="px-4 py-2 text-left">Montant</th>
                                    <th class="px-4 py-2 text-left">Mode de paiement</th>
                                    <th class="px-4 py-2 text-left">Date du paiement</th>
                                    <th class="px-4 py-2 text-left">Date de création de l'instrument</th>
                                    <th class="px-4 py-2 text-left">Date d'échéance</th>
                                    <th class="px-4 py-2 text-left">Propriétaire</th>
                                    <th class="px-4 py-2 text-left">N° instrument</th>
                                    <th class="px-4 py-2 text-left">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($this->payments as $payment)
                                    <tr>
                                        <td class="px-4 py-2">{{ number_format($payment->amount, 2) }} DT</td>
                                        <td class="px-4 py-2">
                                            <span class="px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-800">
                                                {{ ucfirst(str_replace('_', ' ', $payment->payment_mode)) }}
                                            </span>
                                        </td>
                                        <td class="px-4 py-2">{{ $payment->creation_date ? $payment->creation_date->format('d/m/Y') : '-' }}</td>
                                        <td class="px-4 py-2">{{ $payment->date_entree ? $payment->date_entree->format('d/m/Y') : '-' }}</td>
                                        <td class="px-4 py-2">{{ $payment->date_activation ? $payment->date_activation->format('d/m/Y') : '-' }}</td>
                                        <td class="px-4 py-2">{{ $payment->instrument_owner ?? '-' }}</td>
                                        <td class="px-4 py-2">{{ $payment->instrument_number ?? '-' }}</td>
                                        <td class="px-4 py-2 text-left">
                                            <div class="flex space-x-2">
                                                <button 
                                                    type="button"
                                                    wire:click="openEditPaymentModal({{ $payment->id }})"
                                                    x-on:click="$dispatch('open-edit-payment-modal')"
                                                    class="p-2 text-white bg-blue-600 rounded hover:bg-blue-700 transition-colors"
                                                    title="Modifier le paiement"
                                                >
                                                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                                    </svg>
                                                </button>
                                                <x-button 
                                                    tag="a" 
                                                    href="/payment/{{ $payment->id }}/pdf"
                                                    class="p-2 text-white bg-green-600 rounded hover:bg-green-700 transition-colors"
                                                    title="Générer le PDF du paiement"
                                                >
                                                    <svg class="h-4 w-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"></path>
                                                    </svg>
                                                </x-button>
                                                <button 
                                                    type="button" 
                                                    wire:click="deletePayment({{ $payment->id }})"
                                                    wire:confirm="Êtes-vous sûr de vouloir supprimer ce paiement ?"
                                                    class="p-2 text-white bg-red-600 rounded hover:bg-red-700 transition-colors"
                                                    title="Supprimer le paiement"
                                                >
                                                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                                    </svg>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                @endif
            </div>

            <!-- Historique des remises -->
            <div class="mb-6">
            <div class="flex items-center justify-between mb-5 ">
                <h3 class="text-lg font-medium text-gray-900 mb-3">Historique des remises</h3>
                <button 
                    type="button" 
                    wire:click="openCreateDiscountModal"
                    x-on:click="$dispatch('open-create-discount-modal')"
                    class="px-4 py-2 text-sm font-medium text-white bg-indigo-600 border border-transparent rounded-md hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"

                >
                    Nouvelle remise
                </button>
            </div>
                @if($this->discounts->isEmpty())
                    <div class="w-full p-20 text-center bg-gray-100 rounded-xl">
                        <p class="text-gray-500">Aucune remise trouvée pour ce client.</p>
                    </div>
                @else
                    <div class="overflow-x-auto border rounded-lg">
                        <table class="min-w-full bg-white">
                            <thead class="text-sm bg-gray-200">
                                <tr>
                                    <th class="px-4 py-2 text-left">Montant</th>
                                    <th class="px-4 py-2 text-left">Raison</th>
                                    <th class="px-4 py-2 text-left">Date</th>
                                    <th class="px-4 py-2 text-left">Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($this->discounts as $discount)
                                    <tr>
                                        <td class="px-4 py-2 font-semibold text-orange-600">{{ number_format($discount->amount, 2) }} DT</td>
                                        <td class="px-4 py-2">{{ $discount->reason ?? '-' }}</td>
                                        <td class="px-4 py-2">{{ $discount->date ? $discount->date->format('d/m/Y') : ($discount->created_at ? $discount->created_at->format('d/m/Y') : '-') }}</td>
                                        <td class="px-4 py-2 text-left">
                                            <div class="flex space-x-2">
                                                <button 
                                                    type="button" 
                                                    wire:click="deleteDiscount({{ $discount->id }})"
                                                    wire:confirm="Êtes-vous sûr de vouloir supprimer cette remise ?"
                                                    class="p-2 text-white bg-red-600 rounded hover:bg-red-700 transition-colors"
                                                    title="Supprimer la remise"
                                                >
                                                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                                    </svg>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                @endif
            </div>

            <!-- Modal pour créer une commande -->
            <div 
                x-data="{ show: false }"
                @open-create-modal.window="show = true"
                @close-create-modal.window="show = false"
                @keydown.escape.window="show = false"
                x-show="show"
                x-cloak
                class="fixed inset-0 z-50 overflow-y-auto"
                aria-labelledby="modal-title"
                role="dialog"
                aria-modal="true"
            >
                <div class="flex items-center justify-center min-h-screen px-4 py-4 text-center sm:p-0">
                    <!-- Background overlay -->
                    <div 
                        x-show="show"
                        x-transition:enter="ease-out duration-300"
                        x-transition:enter-start="opacity-0"
                        x-transition:enter-end="opacity-100"
                        x-transition:leave="ease-in duration-200"
                        x-transition:leave-start="opacity-100"
                        x-transition:leave-end="opacity-0"
                        class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75"
                        @click="show = false"
                        aria-hidden="true"
                    ></div>

                    <!-- Modal panel -->
                    <div 
                        x-show="show"
                        x-transition:enter="ease-out duration-300"
                        x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                        x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
                        x-transition:leave="ease-in duration-200"
                        x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
                        x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                        class="relative inline-block overflow-hidden text-left align-middle transition-all transform bg-white rounded-lg shadow-xl w-full max-w-2xl"
                    >
                        <div class="px-4 pt-5 pb-4 bg-white sm:p-6 sm:pb-4">
                            <div class="flex items-center justify-between mb-4">
                                <h3 class="text-lg font-medium leading-6 text-gray-900" id="modal-title">
                                    Nouvelle commande
                                </h3>
                                <button 
                                    type="button"
                                    @click="show = false"
                                    class="text-gray-400 hover:text-gray-500"
                                >
                                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                    </svg>
                                </button>
                            </div>

                            <form wire:submit.prevent="saveOrder" class="space-y-4">
                                <div>
                                    <label for="fibre_type_id" class="block mb-2 text-sm font-medium text-gray-700">Type de fil</label>
                                    <div x-data="{ 
                                        open: false, 
                                        search: '',
                                        fibreTypes: @js($this->fibreTypes->map(fn($ft) => ['id' => $ft->id, 'name' => $ft->name . ' (' . $ft->color . ')'])),
                                        get selectedFibreType() {
                                            return $wire.get('fibre_type_id') || '';
                                        },
                                        set selectedFibreType(value) {
                                            $wire.set('fibre_type_id', value);
                                        },
                                        get filteredFibreTypes() {
                                            if (!this.search) return this.fibreTypes;
                                            const searchLower = this.search.toLowerCase();
                                            return this.fibreTypes.filter(fibreType => 
                                                fibreType.name.toLowerCase().includes(searchLower)
                                            );
                                        },
                                        get selectedFibreTypeName() {
                                            const fibreType = this.fibreTypes.find(ft => ft.id == this.selectedFibreType);
                                            return fibreType ? fibreType.name : 'Sélectionner un type de fil';
                                        }
                                    }" 
                                    x-on:click.outside="open = false"
                                    class="relative">
                                        <input type="hidden" wire:model.live="fibre_type_id" />
                                        <button type="button" 
                                            x-on:click="open = !open"
                                            class="block w-full mt-1 px-3 py-2 text-left bg-white border border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                            <span x-text="selectedFibreTypeName" class="block truncate"></span>
                                        </button>
                                        
                                        <div x-show="open" 
                                            x-transition
                                            x-cloak
                                            class="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-auto">
                                            <div class="p-2 sticky top-0 bg-white border-b border-gray-200">
                                                <input type="text" 
                                                    x-model="search"
                                                    x-on:click.stop
                                                    placeholder="Rechercher un type de fil..."
                                                    class="block w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                            </div>
                                            <ul class="py-1">
                                                <li>
                                                    <button type="button"
                                                        x-on:click="selectedFibreType = ''; open = false"
                                                        :class="selectedFibreType == '' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-900 hover:bg-gray-50'"
                                                        class="block w-full px-4 py-2 text-left text-sm">
                                                        Sélectionner un type de fil
                                                    </button>
                                                </li>
                                                <template x-for="fibreType in filteredFibreTypes" :key="fibreType.id">
                                                    <li>
                                                        <button type="button"
                                                            x-on:click="selectedFibreType = fibreType.id; open = false"
                                                            :class="selectedFibreType == fibreType.id ? 'bg-indigo-50 text-indigo-700' : 'text-gray-900 hover:bg-gray-50'"
                                                            class="block w-full px-4 py-2 text-left text-sm">
                                                            <span x-text="fibreType.name"></span>
                                                        </button>
                                                    </li>
                                                </template>
                                                <li x-show="filteredFibreTypes.length === 0" class="px-4 py-2 text-sm text-gray-500">
                                                    Aucun type de fil trouvé
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                    @error('fibre_type_id') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                    
                                    @if($this->fibre_type_id && $this->availableStock > 0)
                                        <div class="mt-2 p-2 bg-green-100 border border-green-200 rounded-md">
                                            <p class="text-sm text-green-800">
                                                <strong>Stock disponible:</strong> {{ number_format($this->availableStock, 2) }} kg
                                            </p>
                                        </div>
                                    @elseif($this->fibre_type_id && $this->availableStock == 0)
                                        <div class="mt-2 p-2 bg-red-100 border border-red-200 rounded-md">
                                            <p class="text-sm text-red-800">
                                                <strong>Aucun stock disponible</strong> pour ce type de fil
                                            </p>
                                        </div>
                                    @endif
                                </div>

                                <div>
                                    <label for="unit_price" class="block mb-2 text-sm font-medium text-gray-700">Prix unitaire (DT/kg)</label>
                                    <input type="number" id="unit_price" wire:model.live="unit_price" step="0.01" min="0.01" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                    @error('unit_price') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div>
                                    <label for="quantity" class="block mb-2 text-sm font-medium text-gray-700">Quantité (kg)</label>
                                    <input type="number" id="quantity" wire:model.live="quantity" step="0.01" min="0.01" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                    @error('quantity') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                    @if($this->fibre_type_id && $this->availableStock > 0)
                                        <p class="mt-1 text-xs text-gray-500">Maximum: {{ number_format($this->availableStock, 2) }} kg</p>
                                    @endif
                                </div>

                                <div>
                                    <label for="total_price" class="block mb-2 text-sm font-medium text-gray-700">Total Prix</label>
                                    <input type="number" id="total_price" wire:model="total_price" step="0.01" min="0.01" readonly class="block w-full mt-1 border-gray-300 rounded-md shadow-sm bg-gray-100 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                    @error('total_price') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div>
                                    <label for="creation_date" class="block mb-2 text-sm font-medium text-gray-700">Date de création</label>
                                    <input type="date" id="creation_date" wire:model="creation_date" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                    @error('creation_date') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div class="flex justify-end space-x-3 mt-6">
                                    <button 
                                        type="button"
                                        @click="show = false"
                                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                                    >
                                        Annuler
                                    </button>
                                    <x-button type="submit">
                                        Créer
                                    </x-button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal pour éditer une commande -->
            <div 
                x-data="{ show: false }"
                @open-edit-modal.window="show = true"
                @close-edit-modal.window="show = false"
                @keydown.escape.window="show = false"
                x-show="show"
                x-cloak
                class="fixed inset-0 z-50 overflow-y-auto"
                aria-labelledby="modal-title"
                role="dialog"
                aria-modal="true"
            >
                <div class="flex items-center justify-center min-h-screen px-4 py-4 text-center sm:p-0">
                    <!-- Background overlay -->
                    <div 
                        x-show="show"
                        x-transition:enter="ease-out duration-300"
                        x-transition:enter-start="opacity-0"
                        x-transition:enter-end="opacity-100"
                        x-transition:leave="ease-in duration-200"
                        x-transition:leave-start="opacity-100"
                        x-transition:leave-end="opacity-0"
                        class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75"
                        @click="show = false"
                        aria-hidden="true"
                    ></div>

                    <!-- Modal panel -->
                    <div 
                        x-show="show"
                        x-transition:enter="ease-out duration-300"
                        x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                        x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
                        x-transition:leave="ease-in duration-200"
                        x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
                        x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                        class="relative inline-block overflow-hidden text-left align-middle transition-all transform bg-white rounded-lg shadow-xl w-full max-w-2xl"
                    >
                        <div class="px-4 pt-5 pb-4 bg-white sm:p-6 sm:pb-4">
                            <div class="flex items-center justify-between mb-4">
                                <h3 class="text-lg font-medium leading-6 text-gray-900" id="modal-title">
                                    Modifier la commande
                                </h3>
                                <button 
                                    type="button"
                                    @click="show = false"
                                    class="text-gray-400 hover:text-gray-500"
                                >
                                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                    </svg>
                                </button>
                            </div>

                            <form wire:submit.prevent="updateOrder" class="space-y-4">
                                <div>
                                    <label for="edit_fibre_type_id" class="block mb-2 text-sm font-medium text-gray-700">Type de fil</label>
                                    <div x-data="{ 
                                        open: false, 
                                        search: '',
                                        fibreTypes: @js($this->fibreTypes->map(fn($ft) => ['id' => $ft->id, 'name' => $ft->name . ' (' . $ft->color . ')'])),
                                        get selectedFibreType() {
                                            return $wire.get('fibre_type_id') || '';
                                        },
                                        set selectedFibreType(value) {
                                            $wire.set('fibre_type_id', value);
                                        },
                                        get filteredFibreTypes() {
                                            if (!this.search) return this.fibreTypes;
                                            const searchLower = this.search.toLowerCase();
                                            return this.fibreTypes.filter(fibreType => 
                                                fibreType.name.toLowerCase().includes(searchLower)
                                            );
                                        },
                                        get selectedFibreTypeName() {
                                            const fibreType = this.fibreTypes.find(ft => ft.id == this.selectedFibreType);
                                            return fibreType ? fibreType.name : 'Sélectionner un type de fil';
                                        }
                                    }" 
                                    x-on:click.outside="open = false"
                                    class="relative">
                                        <input type="hidden" wire:model.live="fibre_type_id" />
                                        <button type="button" 
                                            x-on:click="open = !open"
                                            class="block w-full mt-1 px-3 py-2 text-left bg-white border border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                            <span x-text="selectedFibreTypeName" class="block truncate"></span>
                                        </button>
                                        
                                        <div x-show="open" 
                                            x-transition
                                            x-cloak
                                            class="absolute z-50 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-auto">
                                            <div class="p-2 sticky top-0 bg-white border-b border-gray-200">
                                                <input type="text" 
                                                    x-model="search"
                                                    x-on:click.stop
                                                    placeholder="Rechercher un type de fil..."
                                                    class="block w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                            </div>
                                            <ul class="py-1">
                                                <li>
                                                    <button type="button"
                                                        x-on:click="selectedFibreType = ''; open = false"
                                                        :class="selectedFibreType == '' ? 'bg-indigo-50 text-indigo-700' : 'text-gray-900 hover:bg-gray-50'"
                                                        class="block w-full px-4 py-2 text-left text-sm">
                                                        Sélectionner un type de fil
                                                    </button>
                                                </li>
                                                <template x-for="fibreType in filteredFibreTypes" :key="fibreType.id">
                                                    <li>
                                                        <button type="button"
                                                            x-on:click="selectedFibreType = fibreType.id; open = false"
                                                            :class="selectedFibreType == fibreType.id ? 'bg-indigo-50 text-indigo-700' : 'text-gray-900 hover:bg-gray-50'"
                                                            class="block w-full px-4 py-2 text-left text-sm">
                                                            <span x-text="fibreType.name"></span>
                                                        </button>
                                                    </li>
                                                </template>
                                                <li x-show="filteredFibreTypes.length === 0" class="px-4 py-2 text-sm text-gray-500">
                                                    Aucun type de fil trouvé
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                    @error('fibre_type_id') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                    
                                    @if($this->fibre_type_id && $this->availableStock > 0)
                                        <div class="mt-2 p-2 bg-green-100 border border-green-200 rounded-md">
                                            <p class="text-sm text-green-800">
                                                <strong>Stock disponible:</strong> {{ number_format($this->availableStock, 2) }} kg
                                            </p>
                                        </div>
                                    @elseif($this->fibre_type_id && $this->availableStock == 0)
                                        <div class="mt-2 p-2 bg-red-100 border border-red-200 rounded-md">
                                            <p class="text-sm text-red-800">
                                                <strong>Aucun stock disponible</strong> pour ce type de fil
                                            </p>
                                        </div>
                                    @endif
                                </div>

                                <div>
                                    <label for="edit_unit_price" class="block mb-2 text-sm font-medium text-gray-700">Prix unitaire (DT/kg)</label>
                                    <input type="number" id="edit_unit_price" wire:model.live="unit_price" step="0.01" min="0.01" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                    @error('unit_price') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div>
                                    <label for="edit_quantity" class="block mb-2 text-sm font-medium text-gray-700">Quantité (kg)</label>
                                    <input type="number" id="edit_quantity" wire:model.live="quantity" step="0.01" min="0.01" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                    @error('quantity') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                    @if($this->fibre_type_id && $this->availableStock > 0)
                                        <p class="mt-1 text-xs text-gray-500">Maximum: {{ number_format($this->availableStock, 2) }} kg</p>
                                    @endif
                                </div>

                                <div>
                                    <label for="edit_total_price" class="block mb-2 text-sm font-medium text-gray-700">Total Prix</label>
                                    <input type="number" id="edit_total_price" wire:model="total_price" step="0.01" min="0.01" readonly class="block w-full mt-1 border-gray-300 rounded-md shadow-sm bg-gray-100 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                    @error('total_price') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div>
                                    <label for="edit_creation_date" class="block mb-2 text-sm font-medium text-gray-700">Date de création</label>
                                    <input type="date" id="edit_creation_date" wire:model="creation_date" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                    @error('creation_date') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div class="flex justify-end space-x-3 mt-6">
                                    <button 
                                        type="button"
                                        @click="show = false"
                                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                                    >
                                        Annuler
                                    </button>
                                    <x-button type="submit">
                                        Mettre à jour
                                    </x-button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal pour créer un paiement -->
            <div 
                x-data="{ show: false }"
                @open-create-payment-modal.window="show = true"
                @close-create-payment-modal.window="show = false"
                @keydown.escape.window="show = false"
                x-show="show"
                x-cloak
                class="fixed inset-0 z-50 overflow-y-auto"
                aria-labelledby="modal-title"
                role="dialog"
                aria-modal="true"
            >
                <div class="flex items-center justify-center min-h-screen px-4 py-4 text-center sm:p-0">
                    <!-- Background overlay -->
                    <div 
                        x-show="show"
                        x-transition:enter="ease-out duration-300"
                        x-transition:enter-start="opacity-0"
                        x-transition:enter-end="opacity-100"
                        x-transition:leave="ease-in duration-200"
                        x-transition:leave-start="opacity-100"
                        x-transition:leave-end="opacity-0"
                        class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75"
                        @click="show = false"
                        aria-hidden="true"
                    ></div>

                    <!-- Modal panel -->
                    <div 
                        x-show="show"
                        x-transition:enter="ease-out duration-300"
                        x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                        x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
                        x-transition:leave="ease-in duration-200"
                        x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
                        x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                        class="relative inline-block overflow-hidden text-left align-middle transition-all transform bg-white rounded-lg shadow-xl w-full max-w-2xl"
                    >
                        <div class="px-4 pt-5 pb-4 bg-white sm:p-6 sm:pb-4">
                            <div class="flex items-center justify-between mb-4">
                                <h3 class="text-lg font-medium leading-6 text-gray-900" id="modal-title">
                                    Nouveau paiement
                                </h3>
                                <button 
                                    type="button"
                                    @click="show = false"
                                    class="text-gray-400 hover:text-gray-500"
                                >
                                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                    </svg>
                                </button>
                            </div>

                            <form wire:submit.prevent="savePayment" class="space-y-4">
                                <div>
                                    <label for="amount" class="block mb-2 text-sm font-medium text-gray-700">Montant (DT)</label>
                                    <input type="number" id="amount" wire:model="amount" step="0.01" min="0.01" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                    @error('amount') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div>
                                    <label for="payment_creation_date" class="block mb-2 text-sm font-medium text-gray-700">Date du paiement</label>
                                    <input type="date" id="payment_creation_date" wire:model="payment_creation_date" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                    @error('payment_creation_date') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div>
                                    <label for="payment_mode" class="block mb-2 text-sm font-medium text-gray-700">Mode de paiement</label>
                                    <select id="payment_mode" wire:model.live="payment_mode" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                        <option value="cash">Espèces</option>
                                        <option value="trait">Trait</option>
                                        <option value="cheque">Chèque</option>
                                    </select>
                                    @error('payment_mode') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                @if(in_array($this->payment_mode, ['cheque', 'trait']))
                                    <div>
                                        <label for="date_entree" class="block mb-2 text-sm font-medium text-gray-700">Date de création de l'instrument (chèque/traite)</label>
                                        <input type="date" id="date_entree" wire:model="date_entree" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                        @error('date_entree') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                    </div>

                                    <div>
                                        <label for="date_activation" class="block mb-2 text-sm font-medium text-gray-700">Date d'échéance</label>
                                        <input type="date" id="date_activation" wire:model="date_activation" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                        @error('date_activation') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                    </div>

                                    <div>
                                        <label for="instrument_owner" class="block mb-2 text-sm font-medium text-gray-700">Propriétaire (nom sur le chèque/traite)</label>
                                        <input type="text" id="instrument_owner" wire:model="instrument_owner" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" placeholder="Nom figurant sur l'instrument">
                                        @error('instrument_owner') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                    </div>

                                    <div>
                                        <label for="instrument_number" class="block mb-2 text-sm font-medium text-gray-700">Numéro du chèque/traite</label>
                                        <input type="text" id="instrument_number" wire:model="instrument_number" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" placeholder="Numéro de l'instrument">
                                        @error('instrument_number') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                    </div>
                                @endif

                                <div class="flex justify-end space-x-3 mt-6">
                                    <button 
                                        type="button"
                                        @click="show = false"
                                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                                    >
                                        Annuler
                                    </button>
                                    <x-button type="submit">
                                        Créer
                                    </x-button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal pour éditer un paiement -->
            <div 
                x-data="{ show: false }"
                @open-edit-payment-modal.window="show = true"
                @close-edit-payment-modal.window="show = false"
                @keydown.escape.window="show = false"
                x-show="show"
                x-cloak
                class="fixed inset-0 z-50 overflow-y-auto"
                aria-labelledby="modal-title"
                role="dialog"
                aria-modal="true"
            >
                <div class="flex items-center justify-center min-h-screen px-4 py-4 text-center sm:p-0">
                    <!-- Background overlay -->
                    <div 
                        x-show="show"
                        x-transition:enter="ease-out duration-300"
                        x-transition:enter-start="opacity-0"
                        x-transition:enter-end="opacity-100"
                        x-transition:leave="ease-in duration-200"
                        x-transition:leave-start="opacity-100"
                        x-transition:leave-end="opacity-0"
                        class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75"
                        @click="show = false"
                        aria-hidden="true"
                    ></div>

                    <!-- Modal panel -->
                    <div 
                        x-show="show"
                        x-transition:enter="ease-out duration-300"
                        x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                        x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
                        x-transition:leave="ease-in duration-200"
                        x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
                        x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                        class="relative inline-block overflow-hidden text-left align-middle transition-all transform bg-white rounded-lg shadow-xl w-full max-w-2xl"
                    >
                        <div class="px-4 pt-5 pb-4 bg-white sm:p-6 sm:pb-4">
                            <div class="flex items-center justify-between mb-4">
                                <h3 class="text-lg font-medium leading-6 text-gray-900" id="modal-title">
                                    Modifier le paiement
                                </h3>
                                <button 
                                    type="button"
                                    @click="show = false"
                                    class="text-gray-400 hover:text-gray-500"
                                >
                                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                    </svg>
                                </button>
                            </div>

                            <form wire:submit.prevent="updatePayment" class="space-y-4">
                                <div>
                                    <label for="edit_amount" class="block mb-2 text-sm font-medium text-gray-700">Montant (DT)</label>
                                    <input type="number" id="edit_amount" wire:model="amount" step="0.01" min="0.01" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                    @error('amount') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div>
                                    <label for="edit_payment_creation_date" class="block mb-2 text-sm font-medium text-gray-700">Date du paiement</label>
                                    <input type="date" id="edit_payment_creation_date" wire:model="payment_creation_date" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                    @error('payment_creation_date') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div>
                                    <label for="edit_payment_mode" class="block mb-2 text-sm font-medium text-gray-700">Mode de paiement</label>
                                    <select id="edit_payment_mode" wire:model.live="payment_mode" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                        <option value="cash">Espèces</option>
                                        <option value="trait">Trait</option>
                                        <option value="cheque">Chèque</option>
                                    </select>
                                    @error('payment_mode') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                @if(in_array($this->payment_mode, ['cheque', 'trait']))
                                    <div>
                                        <label for="edit_date_entree" class="block mb-2 text-sm font-medium text-gray-700">Date de création de l'instrument (chèque/traite)</label>
                                        <input type="date" id="edit_date_entree" wire:model="date_entree" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                        @error('date_entree') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                    </div>

                                    <div>
                                        <label for="edit_date_activation" class="block mb-2 text-sm font-medium text-gray-700">Date d'échéance</label>
                                        <input type="date" id="edit_date_activation" wire:model="date_activation" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                                        @error('date_activation') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                    </div>

                                    <div>
                                        <label for="edit_instrument_owner" class="block mb-2 text-sm font-medium text-gray-700">Propriétaire (nom sur le chèque/traite)</label>
                                        <input type="text" id="edit_instrument_owner" wire:model="instrument_owner" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" placeholder="Nom figurant sur l'instrument">
                                        @error('instrument_owner') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                    </div>

                                    <div>
                                        <label for="edit_instrument_number" class="block mb-2 text-sm font-medium text-gray-700">Numéro du chèque/traite</label>
                                        <input type="text" id="edit_instrument_number" wire:model="instrument_number" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" placeholder="Numéro de l'instrument">
                                        @error('instrument_number') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                    </div>
                                @endif

                                <div class="flex justify-end space-x-3 mt-6">
                                    <button 
                                        type="button"
                                        @click="show = false"
                                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                                    >
                                        Annuler
                                    </button>
                                    <x-button type="submit">
                                        Mettre à jour
                                    </x-button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal pour créer une remise -->
            <div 
                x-data="{ show: false }"
                @open-create-discount-modal.window="show = true"
                @close-create-discount-modal.window="show = false"
                @keydown.escape.window="show = false"
                x-show="show"
                x-cloak
                class="fixed inset-0 z-50 overflow-y-auto"
                aria-labelledby="modal-title"
                role="dialog"
                aria-modal="true"
            >
                <div class="flex items-center justify-center min-h-screen px-4 py-4 text-center sm:p-0">
                    <!-- Background overlay -->
                    <div 
                        x-show="show"
                        x-transition:enter="ease-out duration-300"
                        x-transition:enter-start="opacity-0"
                        x-transition:enter-end="opacity-100"
                        x-transition:leave="ease-in duration-200"
                        x-transition:leave-start="opacity-100"
                        x-transition:leave-end="opacity-0"
                        class="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75"
                        @click="show = false"
                        aria-hidden="true"
                    ></div>

                    <!-- Modal panel -->
                    <div 
                        x-show="show"
                        x-transition:enter="ease-out duration-300"
                        x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                        x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
                        x-transition:leave="ease-in duration-200"
                        x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
                        x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                        class="relative inline-block overflow-hidden text-left align-middle transition-all transform bg-white rounded-lg shadow-xl w-full max-w-2xl"
                    >
                        <div class="px-4 pt-5 pb-4 bg-white sm:p-6 sm:pb-4">
                            <div class="flex items-center justify-between mb-4">
                                <h3 class="text-lg font-medium leading-6 text-gray-900" id="modal-title">
                                    Nouvelle remise
                                </h3>
                                <button 
                                    type="button"
                                    @click="show = false"
                                    class="text-gray-400 hover:text-gray-500"
                                >
                                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                    </svg>
                                </button>
                            </div>

                            <form wire:submit.prevent="saveDiscount" class="space-y-4">
                                <div>
                                    <label for="discount_amount" class="block mb-2 text-sm font-medium text-gray-700">Montant de la remise (DT)</label>
                                    <input type="number" id="discount_amount" wire:model="discount_amount" step="0.01" min="0.01" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-orange-300 focus:ring focus:ring-orange-200 focus:ring-opacity-50">
                                    @error('discount_amount') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div>
                                    <label for="discount_reason" class="block mb-2 text-sm font-medium text-gray-700">Raison (optionnel)</label>
                                    <input type="text" id="discount_reason" wire:model="discount_reason" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-orange-300 focus:ring focus:ring-orange-200 focus:ring-opacity-50" placeholder="Ex: Remise fidélité, Promotion spéciale...">
                                    @error('discount_reason') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div>
                                    <label for="discount_date" class="block mb-2 text-sm font-medium text-gray-700">Date de la remise</label>
                                    <input type="date" id="discount_date" wire:model="discount_date" class="block w-full mt-1 border-gray-300 rounded-md shadow-sm focus:border-orange-300 focus:ring focus:ring-orange-200 focus:ring-opacity-50">
                                    @error('discount_date') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                                </div>

                                <div class="flex justify-end space-x-3 mt-6">
                                    <button 
                                        type="button"
                                        @click="show = false"
                                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-orange-500"
                                    >
                                        Annuler
                                    </button>
                                    <x-button type="submit" class="bg-orange-600 hover:bg-orange-700">
                                        Créer la remise
                                    </x-button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

        </x-app.container>
    @endvolt
</x-layouts.app>

