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

name('orders');

new class extends Component {
    public $orders;

    public function mount()
    {
        // Fetch all orders with client, fibre type, and client payments
        $this->orders = Order::with(['client.payments', 'fibreType'])->latest()->get();
    }

    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();
        
        // Refresh the orders list
        $this->orders = Order::with(['client.payments', 'fibreType'])->latest()->get();
        
        session()->flash('message', 'Commande supprimée avec succès. Le stock a été restauré.');
    }
};
?>

<x-layouts.app>
    @volt('orders')
        <x-app.container class="max-w-full">

            <div class="flex items-center justify-between mb-5">
                <x-app.heading
                    title="Liste des commandes"
                    description="Vérifiez vos commandes ci-dessous"
                    :border="false"
                />
                <x-button tag="a" href="/order/create">Nouvelle commande</x-button>
            </div>

            @if($this->orders?->isEmpty())
                <div class="w-full p-20 text-center bg-gray-100 rounded-xl">
                    <p class="text-gray-500">Vous n'avez pas encore de commandes.</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">Client</th>
                                <th class="px-4 py-2 text-left">Type de fil</th>
                                <th class="px-4 py-2 text-left">Quantity (kg)</th>
                                <th class="px-4 py-2 text-left">Prix unitaire</th>
                                <th class="px-4 py-2 text-left">Total Prix</th>
                                <th class="px-4 py-2 text-left">Date de création</th>
                                <th class="px-4 py-2 text-left">Statut du crédit du client</th>
                                <th class="px-4 py-2 text-left">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($this->orders as $order)
                                <tr>
                                    <td class="px-4 py-2">{{ $order->client->firstname }} {{ $order->client->lastname }}</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->unit_price, 2) }} DT</td>
                                    <td class="px-4 py-2">{{ number_format($order->total_price, 2) }} DT</td>
                                    <td class="px-4 py-2">{{ optional($order->creation_date)->format('d/m/Y') ?? '—' }}</td>
                                    <td class="px-4 py-2">
                                        <span class="px-2 py-1 text-xs rounded-full {{ $order->client->remaining_credit > 0 ? 'bg-red-100 text-red-800' : ($order->client->remaining_credit < 0 ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800') }}">
                                            {{ number_format($order->client->remaining_credit, 2) }} DT
                                        </span>
                                    </td>
                                    <td class="px-4 py-2 text-left">
                                        <div class="flex space-x-2">
                                            <x-button 
                                                tag="a" 
                                                href="/order/{{ $order->id }}/edit"
                                                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>
                                            </x-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

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