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

name('payments.admin');

new class extends Component {
    public $payments;
    public $clients;
    public $selectedClient = '';
    public $search = '';

    // Form fields for creating new 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('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 function mount()
    {
        $this->loadPayments();
        $this->clients = Client::with(['orders', 'payments'])->get();
    }

    public function loadPayments()
    {
        $query = Payment::with('client');
        
        if ($this->selectedClient) {
            $query->where('client_id', $this->selectedClient);
        }
        
        if ($this->search) {
            $query->whereHas('client', function($q) {
                $q->where('firstname', 'like', '%' . $this->search . '%')
                  ->orWhere('lastname', 'like', '%' . $this->search . '%')
                  ->orWhere('phone_number', 'like', '%' . $this->search . '%');
            });
        }
        
        $this->payments = $query->latest()->get();
    }

    public function updatedSelectedClient()
    {
        $this->loadPayments();
    }

    public function updatedSearch()
    {
        $this->loadPayments();
    }

    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',
        ];

        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;
        }
        
        Payment::create($paymentData);
        
        $this->reset(['client_id', 'amount', 'payment_mode', 'date_entree', 'date_activation', 'instrument_owner', 'instrument_number']);
        $this->loadPayments();
        
        $this->dispatch('toast', type: 'success', message: 'Payment created successfully.');
    }

    public function deletePayment($paymentId)
    {
        Payment::find($paymentId)->delete();
        $this->loadPayments();
    }

    public function validatePayment($paymentId)
    {
        try {
            $payment = Payment::findOrFail($paymentId);
            $payment->validate();
            $this->loadPayments();
            $this->dispatch('toast', type: 'success', message: 'Payment validated successfully.');
        } catch (\Exception $e) {
            session()->flash('error', 'Error validating payment: ' . $e->getMessage());
        }
    }

    public function rejectPayment($paymentId)
    {
        try {
            $payment = Payment::findOrFail($paymentId);
            $payment->reject();
            $this->loadPayments();
            $this->dispatch('toast', type: 'warning', message: 'Payment rejected.');
        } catch (\Exception $e) {
            session()->flash('error', 'Error rejecting payment: ' . $e->getMessage());
        }
    }
};
?>

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

            <div class="flex items-center justify-between mb-5">
                <x-app.heading
                    title="Gestion des paiements"
                    description="Gérez les paiements des clients et consultez l'historique des paiements"
                    :border="false"
                />
                <div class="flex space-x-3">
                    <x-button tag="a" href="/payment/pending" class="bg-yellow-600 hover:bg-yellow-700">
                        Chèques & Traites
                    </x-button>
                    <x-button tag="a" href="/payment" class="bg-blue-600 hover:bg-blue-700">
                        Tous les paiements
                    </x-button>
                </div>
            </div>

        <!-- Filters -->
            <div class="mb-6">
                <div class="bg-white p-4 rounded-lg  border-gray-200 shadow-sm">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Champ de recherche -->
                        <div>
                            <input 
                                type="text" 
                                id="search" 
                                wire:model.live.debounce.300ms="search" 
                                placeholder="Rechercher par nom ou numéro de téléphone..." 
                                class="block w-full px-4 py-2.5 border border-gray-300 rounded-lg shadow-sm transition-all duration-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500 focus:ring-opacity-20 outline-none"
                            >
                        </div>

                        <!-- Sélecteur client -->
                        <div>
                            <div x-data="{ 
                                open: false, 
                                search: '',
                                clients: @js($this->clients->map(fn($c) => ['id' => $c->id, 'name' => $c->firstname . ' ' . $c->lastname])),
                                get selectedClient() {
                                    return $wire.get('selectedClient') || '';
                                },
                                set selectedClient(value) {
                                    $wire.set('selectedClient', value);
                                },
                                get filteredClients() {
                                    if (!this.search) return this.clients;
                                    const searchLower = this.search.toLowerCase();
                                    return this.clients.filter(client => 
                                        client.name.toLowerCase().includes(searchLower)
                                    );
                                },
                                get selectedClientName() {
                                    if (!this.selectedClient) return 'Tous les clients';
                                    const client = this.clients.find(c => c.id == this.selectedClient);
                                    return client ? client.name : 'Tous les clients';
                                }
                            }" 
                            x-on:click.outside="open = false"
                            class="relative">
                                <input type="hidden" wire:model.live="selectedClient" />
                                <button type="button" 
                                    x-on:click="open = !open"
                                    class="block w-full px-4 py-2.5 text-left bg-white border border-gray-300 rounded-lg shadow-sm transition-all duration-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500 focus:ring-opacity-20 outline-none">
                                    <span x-text="selectedClientName" 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-lg 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">
                                                Tous les clients
                                            </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">
                                                    <span x-text="client.name"></span>
                                                </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>
                        </div>
                    </div>
                </div>
            </div>


            <!-- Create Payment Form -->
            <div class="mb-6 p-6 bg-white border border-gray-200 rounded-lg shadow-sm">
                <h3 class="text-xl font-semibold text-gray-900 mb-6">Créer un nouveau paiement</h3>
                
                @if (session()->has('error'))
                    <div class="mb-6 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg">
                        {{ session('error') }}
                    </div>
                @endif

                <form wire:submit="save" class="space-y-6">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <div>
                            <label for="client_id" class="block text-sm font-medium text-gray-700 mb-2">Client</label>
                            <div x-data="{ 
                                open: false, 
                                search: '',
                                clients: @js($this->clients->map(fn($c) => [
                                    'id' => $c->id, 
                                    'name' => $c->firstname . ' ' . $c->lastname,
                                    'remaining_credit' => number_format($c->remaining_credit, 2),
                                    'display' => $c->firstname . ' ' . $c->lastname . ' (' . number_format($c->remaining_credit, 2) . ' DT restant)'
                                ])),
                                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 px-4 py-2.5 text-left bg-white border border-gray-300 rounded-lg shadow-sm transition-all duration-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500 focus:ring-opacity-20 outline-none">
                                    <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-lg 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>Crédit restant: <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-600 mt-1 block">{{ $message }}</span> @enderror
                        </div>

                        <div>
                            <label for="amount" class="block text-sm font-medium text-gray-700 mb-2">Montant (DT)</label>
                            <input type="number" id="amount" wire:model="amount" step="0.01" min="0.01" class="block w-full px-4 py-2.5 border border-gray-300 rounded-lg shadow-sm transition-all duration-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500 focus:ring-opacity-20 outline-none">
                            @error('amount') <span class="text-xs text-red-600 mt-1 block">{{ $message }}</span> @enderror
                        </div>

                        <div>
                            <label for="payment_mode" class="block text-sm font-medium text-gray-700 mb-2">Mode de paiement</label>
                            <select id="payment_mode" wire:model.live="payment_mode" class="block w-full px-4 py-2.5 border border-gray-300 rounded-lg shadow-sm transition-all duration-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500 focus:ring-opacity-20 outline-none bg-white">
                                <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-600 mt-1 block">{{ $message }}</span> @enderror
                        </div>
                    </div>

                    @if(in_array($this->payment_mode, ['cheque', 'trait']))
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 pt-4 border-t border-gray-200">
                            <div>
                                <label for="date_entree" class="block text-sm font-medium text-gray-700 mb-2">Date de création</label>
                                <input type="date" id="date_entree" wire:model="date_entree" class="block w-full px-4 py-2.5 border border-gray-300 rounded-lg shadow-sm transition-all duration-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500 focus:ring-opacity-20 outline-none">
                                @error('date_entree') <span class="text-xs text-red-600 mt-1 block">{{ $message }}</span> @enderror
                            </div>

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

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

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

                    <div class="flex justify-end pt-4 border-t border-gray-200">
                        <x-button type="submit" class="px-6 py-2.5">
                            Créer un nouveau paiement
                        </x-button>
                    </div>
                </form>
            </div>

            <!-- Payments List -->
            <div class="bg-white border border-gray-200 rounded-lg shadow-sm overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-200">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Client</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Montant (DT)</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Mode de paiement</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Date</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Propriétaire</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">N° instrument</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Crédit restant</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                        @foreach($this->payments as $payment)
                            <tr class="hover:bg-gray-50 transition-colors">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div>
                                        <div class="font-medium text-gray-900">{{ $payment->client->firstname }} {{ $payment->client->lastname }}</div>
                                        <div class="text-sm text-gray-500">{{ $payment->client->phone_number }}</div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap font-medium text-gray-900">{{ number_format($payment->amount, 2) }} DT</td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                                        {{ ucfirst(str_replace('_', ' ', $payment->payment_mode)) }}
                                    </span>
                                </td>
                                
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $payment->creation_date->format('d/m/Y ') }}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $payment->instrument_owner ?? '-' }}</td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ $payment->instrument_number ?? '-' }}</td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full {{ $payment->client->remaining_credit > 0 ? 'bg-red-100 text-red-800' : ($payment->client->remaining_credit < 0 ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800') }}">
                                        {{ number_format($payment->client->remaining_credit, 2) }} DT
                                    </span>
                                </td>
                               
                            </tr>
                        @endforeach
                    </tbody>
                    </table>
                </div>
            </div>

            @if($this->payments->isEmpty())
                <div class="w-full p-20 text-center bg-gray-50 rounded-lg border border-gray-200 mt-4">
                    <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                    </svg>
                    <h3 class="mt-2 text-sm font-medium text-gray-900">No payments</h3>
                    <p class="mt-1 text-sm text-gray-500">No payments found matching your criteria.</p>
                </div>
            @endif

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