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

    new class extends Component
    {
        public Payment $payment;

        #[Validate('required|exists:clients,id')]
        public $client_id = '';

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

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

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

        #[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 = '';

        public $clients;

        public function mount()
        {
            $paymentId = request()->route('id');
            $this->payment = Payment::with('client')->findOrFail($paymentId);
            
            $this->client_id = $this->payment->client_id;
            $this->amount = $this->payment->amount;
            $this->payment_mode = $this->payment->payment_mode;
            $this->creation_date = $this->payment->creation_date?->format('Y-m-d') ?? now()->toDateString();
            $this->date_entree = $this->payment->date_entree?->format('Y-m-d') ?? '';
            $this->date_activation = $this->payment->date_activation?->format('Y-m-d') ?? '';

            $this->instrument_owner = $this->payment->instrument_owner ?? '';
            $this->instrument_number = $this->payment->instrument_number ?? '';

            $this->clients = Client::with(['orders', 'payments'])->get();
        }

        public function save()
        {
            $validated = $this->validate();

            $isInstrument = in_array($validated['payment_mode'], ['cheque', 'trait']);
            
            $paymentData = [
                'client_id' => $validated['client_id'],
                'amount' => $validated['amount'],
                'payment_mode' => $validated['payment_mode'],
                'status' => 'validated',
                'creation_date' => $validated['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($this->instrument_owner) ? $this->instrument_owner : null;
                $paymentData['instrument_number'] = !empty($this->instrument_number) ? $this->instrument_number : null;
            } else {
                $paymentData['date_entree'] = null;
                $paymentData['date_activation'] = null;
                $paymentData['instrument_owner'] = null;
                $paymentData['instrument_number'] = null;
            }

            $this->payment->update($paymentData);

            $this->dispatch('toast', type: 'success', message: 'Payment updated successfully.');

            $this->redirect(route('payments'));
        }
    }
?>

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

            <x-elements.back-button
                class="max-w-full mx-auto mb-3"
                text="Retour à la liste des paiements"
                :href="route('payments')"
            />

            <div class="flex items-center justify-between mb-3">
                <x-app.heading
                        title="Modifier le paiement"
                        description="Mettre à jour les informations du paiement"
                        :border="false"
                    />
            </div>

            <form wire:submit="save" class="space-y-4">
                <div>
                    <label for="client_id" class="block mb-2 text-sm font-medium text-gray-700">Client</label>
                    <div x-data="{ 
                        open: false, 
                        search: '',
                        clients: @js($this->clients->map(fn($c) => [
                            'id' => $c->id, 
                            'name' => $c->firstname . ' ' . $c->lastname,
                            'total_orders' => number_format($c->total_orders, 2),
                            'remaining_credit' => number_format($c->remaining_credit, 2),
                            'display' => $c->firstname . ' ' . $c->lastname . ' - Total des commandes: ' . number_format($c->total_orders, 2) . ' DT - Crédit restant: ' . number_format($c->remaining_credit, 2) . ' DT'
                        ])),
                        get selectedClient() {
                            return $wire.get('client_id') || '';
                        },
                        set selectedClient(value) {
                            $wire.set('client_id', value);
                        },
                        get filteredClients() {
                            if (!this.search) return this.clients;
                            const searchLower = this.search.toLowerCase();
                            return this.clients.filter(client => 
                                client.name.toLowerCase().includes(searchLower) ||
                                client.display.toLowerCase().includes(searchLower)
                            );
                        },
                        get selectedClientDisplay() {
                            const client = this.clients.find(c => c.id == this.selectedClient);
                            return client ? client.display : 'Sélectionner un client';
                        }
                    }" 
                    x-on:click.outside="open = false"
                    class="relative">
                        <input type="hidden" wire:model="client_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="selectedClientDisplay" 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 client..."
                                    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="selectedClient = ''; open = false"
                                        :class="selectedClient == '' ? '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 client
                                    </button>
                                </li>
                                <template x-for="client in filteredClients" :key="client.id">
                                    <li>
                                        <button type="button"
                                            x-on:click="selectedClient = client.id; open = false"
                                            :class="selectedClient == client.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">
                                            <div class="font-medium" x-text="client.name"></div>
                                            <div class="text-xs text-gray-500 mt-1">
                                                <span>Total: <span x-text="client.total_orders"></span> DT</span>
                                                <span class="ml-2">Crédit: <span x-text="client.remaining_credit"></span> DT</span>
                                            </div>
                                        </button>
                                    </li>
                                </template>
                                <li x-show="filteredClients.length === 0" class="px-4 py-2 text-sm text-gray-500">
                                    Aucun client trouvé
                                </li>
                            </ul>
                        </div>
                    </div>
                    @error('client_id') <span class="text-xs text-red-500">{{ $message }}</span> @enderror
                </div>

                <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="creation_date" class="block mb-2 text-sm font-medium text-gray-700">Date du paiement</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>
                    <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>
                    <x-button type="submit">
                        Mettre à jour le paiement
                    </x-button>
                </div>
            </form>
        </x-app.container>
    @endvolt
</x-layouts.app>
