@props([
    'payment' => null,
    'clients' => [],
    'appointments' => [],
    'prefilledAmount' => null,
    'prefilledClientId' => null,
    'prefilledAppointmentId' => null
])

@php
    $isEdit = !is_null($payment);
    $action = $isEdit 
        ? route('provider.payments.update', $payment->uuid)
        : route('provider.payments.store');
    $method = $isEdit ? 'PUT' : 'POST';
    $title = $isEdit ? 'Modifier la facture' : 'Informations de paiement';
    $submitText = $isEdit ? 'Mettre à jour la facture' : 'Créer la facture';
@endphp

<div x-data="{
    showNewClientForm: false,
    clientError: '',
    newClient: {
        first_name: '',
        last_name: '',
        phone: ''
    },
    createClient() {
        this.clientError = '';
        if (!this.newClient.first_name || !this.newClient.last_name || !this.newClient.phone) {
            this.clientError = 'Tous les champs sont requis';
            return;
        }
        fetch('{{ route('provider.clients.store') }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json'
            },
            body: JSON.stringify(this.newClient)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const select = document.getElementById('client_id');
                const fullName = data.client.first_name + ' ' + data.client.last_name;
                const option = new Option(fullName, data.client.id, true, true);
                select.add(option);
                this.showNewClientForm = false;
                this.newClient = { first_name: '', last_name: '', phone: '' };
            } else {
                this.clientError = data.message || 'Erreur lors de la création';
            }
        })
        .catch(() => {
            this.clientError = 'Erreur lors de la création';
        });
    }
}">
<x-card>
    <x-slot name="header">
        <div class="flex items-center justify-between">
            <h3 class="text-lg font-semibold text-gray-900 dark:text-white">{{ $title }}</h3>
            <div class="flex gap-2">
                @if($isEdit)
                    <x-button href="{{ route('provider.payments.pdf', $payment->uuid) }}" target="_blank" variant="danger" size="sm">
                        <svg class="w-4 h-4 mr-1" 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>
                        PDF
                    </x-button>
                @endif
                <x-button href="{{ route('provider.finances.index', ['tab' => 'factures']) }}" variant="secondary" size="sm">
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                    </svg>
                    Retour
                </x-button>
            </div>
        </div>
    </x-slot>

    <form action="{{ $action }}" method="POST" class="space-y-6 pb-24">
        @csrf
        @if($isEdit)
            @method('PUT')
        @endif
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <x-input 
                type="date" 
                name="payment_date" 
                label="Date" 
                value="{{ old('payment_date', $isEdit ? $payment->payment_date->format('Y-m-d') : now()->format('Y-m-d')) }}"
                error="{{ $errors->first('payment_date') }}"
                required
            />

            <div>
                <div class="flex items-center justify-between mb-2">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">Client <span class="text-red-500">*</span></label>
                    <button type="button" @click="showNewClientForm = !showNewClientForm" class="text-xs text-primary hover:text-primary-dark font-medium">
                        <span x-show="!showNewClientForm">+ Nouveau client</span>
                        <span x-show="showNewClientForm" x-cloak>Annuler</span>
                    </button>
                </div>
                <x-select name="client_id" id="client_id" error="{{ $errors->first('client_id') }}" required x-show="!showNewClientForm">
                    <option value="">-- Aucun --</option>
                    @foreach($clients as $client)
                        <option value="{{ $client->id }}" {{ old('client_id', $isEdit ? $payment->client_id : ($prefilledClientId ?? '')) == $client->id ? 'selected' : '' }}>
                            {{ $client->full_name }}
                        </option>
                    @endforeach
                </x-select>
                <div x-show="showNewClientForm" x-cloak class="border border-gray-300 dark:border-gray-600 rounded-lg p-4 bg-gray-50 dark:bg-gray-700">
                    <div class="grid grid-cols-2 gap-3">
                        <x-input type="text" name="new_client_first_name" label="Prénom" x-model="newClient.first_name" />
                        <x-input type="text" name="new_client_last_name" label="Nom" x-model="newClient.last_name" />
                        <x-input type="tel" name="new_client_phone" label="Téléphone" x-model="newClient.phone" />
                        <div class="flex items-end">
                            <x-button type="button" @click="createClient()" variant="primary" size="sm" class="w-full">Créer le client</x-button>
                        </div>
                    </div>
                    <div x-show="clientError" x-cloak class="mt-2 text-sm text-red-600" x-text="clientError"></div>
                </div>
            </div>

            <div class="md:col-span-2">
                <div class="flex items-center justify-between mb-2">
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300">
                        Rendez-vous (sélection multiple)
                    </label>
                    <button type="button" id="select-all-btn" onclick="toggleSelectAll()" class="text-xs text-primary hover:text-primary-dark font-medium" style="display: none;">
                        Sélectionner tout
                    </button>
                </div>
                <div id="appointments-list" class="space-y-2 max-h-60 overflow-y-auto border border-gray-300 dark:border-gray-600 rounded-lg p-3 bg-white dark:bg-gray-800 @error('appointment_ids') border-red-500 @enderror">
                    @if(count($appointments) > 0)
                        @foreach($appointments as $appointment)
                            <label class="flex items-start p-2 hover:bg-gray-50 dark:hover:bg-gray-700 rounded cursor-pointer">
                                <input type="checkbox" 
                                       name="appointment_ids[]" 
                                       value="{{ $appointment->id }}"
                                       data-price="{{ $appointment->price_at_booking }}"
                                       {{ in_array($appointment->id, old('appointment_ids', $isEdit ? $payment->appointments->pluck('id')->toArray() : ($prefilledAppointmentId ? [$prefilledAppointmentId] : []))) ? 'checked' : '' }}
                                       class="appointment-checkbox mt-1 mr-3 h-4 w-4 text-primary border-gray-300 rounded focus:ring-primary">
                                <span class="text-sm text-gray-900 dark:text-white">
                                    {{ $appointment->start_time->format('d/m/Y H:i') }} - {{ $appointment->service->name ?? 'Service' }}<br>
                                    <span class="text-xs text-gray-500 dark:text-gray-400">{{ number_format($appointment->price_at_booking, 2) }} {{ $appointment->currency }}</span>
                                </span>
                            </label>
                        @endforeach
                    @else
                        <p class="text-sm text-gray-500 dark:text-gray-400 p-2">Sélectionnez un client pour voir ses rendez-vous</p>
                    @endif
                </div>
                <div id="total-display" class="mt-2 text-sm font-semibold text-gray-700 dark:text-gray-300" style="display: none;">
                    Total sélectionné : <span id="total-amount">0.00</span> {{ $isEdit ? $payment->currency : (auth()->user()->provider->generalSettings['currency'] ?? 'TND') }}
                </div>
                @error('appointment_ids')
                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                @enderror
            </div>

            <x-input 
                type="number" 
                name="amount" 
                label="Montant" 
                value="{{ old('amount', $isEdit ? $payment->amount : ($prefilledAmount ?? '')) }}"
                step="0.01"
                min="0"
                error="{{ $errors->first('amount') }}"
                required
                id="amount"
            />

            <x-select name="method" label="Méthode de paiement" required>
                <option value="cash" {{ old('method', $isEdit ? $payment->method : '') == 'cash' ? 'selected' : '' }}>Espèces</option>
                <option value="card" {{ old('method', $isEdit ? $payment->method : '') == 'card' ? 'selected' : '' }}>Carte</option>
                <option value="bank_transfer" {{ old('method', $isEdit ? $payment->method : '') == 'bank_transfer' ? 'selected' : '' }}>Virement bancaire</option>
                <option value="other" {{ old('method', $isEdit ? $payment->method : '') == 'other' ? 'selected' : '' }}>Autre</option>
            </x-select>

            <div class="md:col-span-2">
                <x-textarea 
                    name="notes" 
                    label="Notes" 
                    rows="3"
                    placeholder="Notes optionnelles..."
                    value="{{ old('notes', $isEdit ? $payment->notes : '') }}"
                />
            </div>
        </div>

        <!-- Bouton fixe au-dessus de la navigation du bas -->
        <div class="fixed bottom-16 left-0 right-0 p-4 bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 shadow-lg z-40">
            <div class="flex gap-3">
                <x-button href="{{ route('provider.finances.index', ['tab' => 'factures']) }}" variant="secondary" class="flex-1">
                    Annuler
                </x-button>
                <x-button type="submit" class="flex-1">
                    {{ $submitText }}
                </x-button>
            </div>
        </div>
    </form>
</x-card>
</div>

<script>
const baseUrl = window.location.origin + window.location.pathname.split('/provider')[0];
let allSelected = false;

function toggleSelectAll() {
    const checkboxes = document.querySelectorAll('.appointment-checkbox');
    const selectAllBtn = document.getElementById('select-all-btn');
    
    allSelected = !allSelected;
    
    checkboxes.forEach(cb => {
        cb.checked = allSelected;
    });
    
    selectAllBtn.textContent = allSelected ? 'Désélectionner tout' : 'Sélectionner tout';
    updateTotal();
}

function updateTotal() {
    const checkboxes = document.querySelectorAll('.appointment-checkbox:checked');
    let total = 0;
    checkboxes.forEach(cb => {
        total += parseFloat(cb.dataset.price || 0);
    });
    
    const totalDisplay = document.getElementById('total-display');
    const totalAmount = document.getElementById('total-amount');
    const amountInput = document.getElementById('amount');
    
    if (total > 0) {
        totalAmount.textContent = total.toFixed(2);
        totalDisplay.style.display = 'block';
        amountInput.value = total.toFixed(2);
    } else {
        totalDisplay.style.display = 'none';
        amountInput.value = '';
    }
}

const clientSelect = document.getElementById('client_id');
if (clientSelect) {
    clientSelect.addEventListener('change', function() {
    const clientId = this.value;
    const appointmentsList = document.getElementById('appointments-list');
    
    appointmentsList.innerHTML = '';
    document.getElementById('total-display').style.display = 'none';
    
    if (!clientId) {
        appointmentsList.innerHTML = '<p class="text-sm text-gray-500 dark:text-gray-400 p-2">Sélectionnez un client pour voir ses rendez-vous</p>';
        const selectAllBtn = document.getElementById('select-all-btn');
        if (selectAllBtn) selectAllBtn.style.display = 'none';
        return;
    }
    
    fetch(`${baseUrl}/provider/api/clients/${clientId}/appointments`)
        .then(response => response.json())
        .then(appointments => {
            if (appointments.length === 0) {
                appointmentsList.innerHTML = '<p class="text-sm text-gray-500 dark:text-gray-400 p-2">Aucun rendez-vous pour ce client</p>';
                const selectAllBtn = document.getElementById('select-all-btn');
                if (selectAllBtn) selectAllBtn.style.display = 'none';
            } else {
                appointments.forEach(appointment => {
                    const label = document.createElement('label');
                    label.className = 'flex items-start p-2 hover:bg-gray-50 dark:hover:bg-gray-700 rounded cursor-pointer';
                    label.innerHTML = `
                        <input type="checkbox" 
                               name="appointment_ids[]" 
                               value="${appointment.id}"
                               data-price="${appointment.price}"
                               class="appointment-checkbox mt-1 mr-3 h-4 w-4 text-primary border-gray-300 rounded focus:ring-primary">
                        <span class="text-sm text-gray-900 dark:text-white">${appointment.label}</span>
                    `;
                    appointmentsList.appendChild(label);
                });
                
                document.querySelectorAll('.appointment-checkbox').forEach(cb => {
                    cb.addEventListener('change', updateTotal);
                });
                
                // Show select all button if there are appointments
                const selectAllBtn = document.getElementById('select-all-btn');
                if (selectAllBtn) {
                    selectAllBtn.style.display = appointments.length > 1 ? 'block' : 'none';
                    allSelected = false;
                    selectAllBtn.textContent = 'Sélectionner tout';
                }
            }
        });
    });
}

document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.appointment-checkbox').forEach(cb => {
        cb.addEventListener('change', updateTotal);
    });
    
    // Show select all button if there are appointments on page load
    const selectAllBtn = document.getElementById('select-all-btn');
    const checkboxes = document.querySelectorAll('.appointment-checkbox');
    if (selectAllBtn && checkboxes.length > 1) {
        selectAllBtn.style.display = 'block';
    }
    
    updateTotal();
});
</script>