@extends('layouts.provider')

@section('title', 'Modifier Rendez-vous')
@section('page-title', 'Modifier Rendez-vous')

@section('content')
<div class="space-y-6">
    <x-card>
        <x-slot name="header">
            <div class="flex items-center gap-3">
                <a href="{{ route('provider.appointments.calendar') }}" class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300">
                    <svg class="w-5 h-5" 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>
                </a>
                <h2 class="text-xl font-bold text-gray-900 dark:text-white">Modifier Rendez-vous</h2>
            </div>
        </x-slot>

        <!-- Formulaire -->
        <form action="{{ route('provider.appointments.update', $appointment->uuid) }}" method="POST" class="space-y-6">
            @csrf
            @method('PUT')
            
            <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">Informations du rendez-vous</h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Date de début -->
                <div>
                    <label for="start_date" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Date <span class="text-red-500">*</span>
                    </label>
                    <input type="date" 
                           id="start_date" 
                           name="start_date" 
                           value="{{ old('start_date', $appointment->start_time->format('Y-m-d')) }}"
                           required
                           class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 @error('start_time') border-red-500 @enderror">
                    @error('start_time')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Heure de début -->
                <div>
                    <label for="start_time" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Heure de début <span class="text-red-500">*</span>
                    </label>
                    <input type="time" 
                           id="start_time" 
                           name="start_time" 
                           value="{{ old('start_time', $appointment->start_time->format('H:i')) }}"
                           required
                           class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                </div>

                <!-- Heure de fin -->
                <div>
                    <label for="end_time" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Heure de fin <span class="text-red-500">*</span>
                    </label>
                    <input type="time" 
                           id="end_time" 
                           name="end_time" 
                           value="{{ old('end_time', $appointment->end_time->format('H:i')) }}"
                           required
                           class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 @error('end_time') border-red-500 @enderror">
                    @error('end_time')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Client -->
                <div>
                    <label for="client_id" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Client
                    </label>
                    <select id="client_id" 
                            name="client_id" 
                            class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 @error('client_id') border-red-500 @enderror">
                        <option value="">Sélectionner un client</option>
                        @foreach($clients as $client)
                            <option value="{{ $client->id }}" {{ old('client_id', $appointment->client_id) == $client->id ? 'selected' : '' }}>
                                {{ $client->full_name }}
                            </option>
                        @endforeach
                    </select>
                    @error('client_id')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Service -->
                <div>
                    <label for="service_id" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Service
                    </label>
                    <select id="service_id" 
                            name="service_id" 
                            class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 @error('service_id') border-red-500 @enderror">
                        <option value="">Sélectionner un service</option>
                        @foreach($services as $service)
                            <option value="{{ $service->id }}" 
                                    data-price="{{ $service->base_price }}"
                                    data-currency="{{ $service->currency }}"
                                    data-duration="{{ $service->duration_minutes }}"
                                    {{ old('service_id', $appointment->service_id) == $service->id ? 'selected' : '' }}>
                                {{ $service->name }} - {{ $service->formatted_price }} ({{ $service->formatted_duration }})
                            </option>
                        @endforeach
                    </select>
                    @error('service_id')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Prix -->
                <div>
                    <label for="price_at_booking" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Prix
                    </label>
                    <div class="relative">
                        <input type="number" 
                               id="price_at_booking" 
                               name="price_at_booking" 
                               value="{{ old('price_at_booking', $appointment->price_at_booking) }}"
                               step="0.01"
                               min="0"
                               class="w-full px-4 py-3 pr-16 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 @error('price_at_booking') border-red-500 @enderror"
                               placeholder="0.00">
                        <div class="absolute inset-y-0 right-0 flex items-center pr-3">
                            <span class="text-gray-500 dark:text-gray-400 text-sm">{{ $appointment->currency }}</span>
                        </div>
                    </div>
                    @error('price_at_booking')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Alerte ajustement de prix -->
                <div class="md:col-span-2">
                    <div id="priceAlert" class="hidden bg-amber-50 border-l-4 border-amber-500 p-4 rounded-r-lg">
                        <div class="flex items-start justify-between">
                            <div class="flex items-start flex-1">
                                <div class="flex-shrink-0">
                                    <svg class="h-5 w-5 text-amber-500" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
                                    </svg>
                                </div>
                                <div class="ml-3">
                                    <p class="text-sm font-medium text-amber-800" id="priceAlertMessage"></p>
                                    <p class="mt-1 text-sm text-amber-700" id="priceAlertQuestion"></p>
                                    <div class="mt-2 text-xs font-mono bg-amber-100 text-amber-900 px-3 py-2 rounded inline-block" id="priceAlertCalculation"></div>
                                </div>
                            </div>
                            <div class="flex gap-2 ml-4">
                                <button type="button" onclick="acceptPriceAdjustment()" class="bg-amber-600 hover:bg-amber-700 text-white text-sm font-medium py-2 px-4 rounded transition-colors whitespace-nowrap">
                                    ✓ Adapter
                                </button>
                                <button type="button" onclick="rejectPriceAdjustment()" class="bg-gray-200 hover:bg-gray-300 text-gray-800 text-sm font-medium py-2 px-4 rounded transition-colors whitespace-nowrap">
                                    ✗ Garder
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Statut -->
                <div>
                    <label for="status" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Statut <span class="text-red-500">*</span>
                    </label>
                    <select id="status" 
                            name="status" 
                            required
                            class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 @error('status') border-red-500 @enderror">
                        <option value="scheduled" {{ old('status', $appointment->status) === 'scheduled' ? 'selected' : '' }}>Programmé</option>
                        <option value="completed" {{ old('status', $appointment->status) === 'completed' ? 'selected' : '' }}>Terminé</option>
                        <option value="canceled" {{ old('status', $appointment->status) === 'canceled' ? 'selected' : '' }}>Annulé</option>
                        <option value="no_show" {{ old('status', $appointment->status) === 'no_show' ? 'selected' : '' }}>Absent</option>
                    </select>
                    @error('status')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Notes -->
                <div class="md:col-span-2">
                    <label for="notes" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Notes
                    </label>
                    <textarea id="notes" 
                              name="notes" 
                              rows="3"
                              class="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-white rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 @error('notes') border-red-500 @enderror"
                              placeholder="Notes optionnelles sur ce rendez-vous...">{{ old('notes', $appointment->notes) }}</textarea>
                    @error('notes')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>
            </div>

            <!-- Actions -->
            <div class="flex gap-3 pt-6 border-t border-gray-200 dark:border-gray-700">
                <x-button type="submit" class="flex-1">Modifier le rendez-vous</x-button>
                <x-button href="{{ route('provider.appointments.calendar') }}" variant="secondary">Annuler</x-button>
                <form action="{{ route('provider.appointments.destroy', $appointment->uuid) }}" method="POST" class="inline">
                    @csrf
                    @method('DELETE')
                    <x-button type="submit" variant="danger" onclick="return confirm('Êtes-vous sûr de vouloir supprimer ce rendez-vous ?')">Supprimer</x-button>
                </form>
            </div>
        </form>

        <!-- Encaissements section -->
        <div class="mt-8 pt-8 border-t border-gray-200 dark:border-gray-700">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold text-gray-900 dark:text-white">Encaissements liés</h3>
                <a href="{{ route('provider.payments.create', ['appointment_id' => $appointment->id, 'client_id' => $appointment->client_id, 'amount' => $appointment->price_at_booking]) }}" 
                   class="inline-flex items-center px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors">
                    + Ajouter encaissement
                </a>
            </div>
            @if($appointment->payments->count() > 0)
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                        <thead class="bg-gray-50 dark:bg-gray-700">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Date</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Montant</th>
                                <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Méthode</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                            @foreach($appointment->payments as $payment)
                                <tr>
                                    <td class="px-4 py-3 text-sm dark:text-gray-300">{{ $payment->payment_date->format('d/m/Y') }}</td>
                                    <td class="px-4 py-3 text-sm font-semibold dark:text-white">{{ number_format($payment->amount, 2) }} {{ $payment->currency }}</td>
                                    <td class="px-4 py-3 text-sm dark:text-gray-300">
                                        @switch($payment->method)
                                            @case('cash') Espèces @break
                                            @case('card') Carte @break
                                            @case('bank_transfer') Virement @break
                                            @case('other') Autre @break
                                        @endswitch
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                <div class="mt-3 text-sm">
                    <span class="text-gray-600 dark:text-gray-400">Total encaissé :</span> 
                    <span class="font-bold text-gray-900 dark:text-white">{{ number_format($appointment->payments->sum('amount'), 2) }} {{ $appointment->currency }}</span>
                </div>
            @else
                <p class="text-gray-500 dark:text-gray-400 text-sm">Aucun encaissement pour ce rendez-vous.</p>
            @endif
        </div>
    </x-card>
</div>

<script>
    let serviceDurationMinutes = 0;
    let serviceBasePrice = 0;
    let pendingNewPrice = null;
    let priceAlertAnswered = false;
    let allowSubmit = false;
    let endTimeSetManually = false;

    // Initialiser avec le service actuel
    window.addEventListener('DOMContentLoaded', function() {
        const serviceSelect = document.getElementById('service_id');
        const selectedOption = serviceSelect.options[serviceSelect.selectedIndex];
        if (selectedOption) {
            serviceDurationMinutes = parseInt(selectedOption.getAttribute('data-duration')) || 0;
            serviceBasePrice = parseFloat(selectedOption.getAttribute('data-price')) || 0;
        }
        updateStartTimeMax();
    });
    
    function updateStartTimeMax() {
        // Pas besoin de définir max en HTML
    }

    document.getElementById('service_id').addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        const price = selectedOption.getAttribute('data-price');
        const duration = selectedOption.getAttribute('data-duration');
        
        serviceDurationMinutes = duration ? parseInt(duration) : 0;
        serviceBasePrice = price ? parseFloat(price) : 0;
        
        if (price) {
            document.getElementById('price_at_booking').value = price;
        }
        
        updateStartTimeMax();
        
        if (duration && !endTimeSetManually) {
            calculateEndTime();
        }
        
        hidePriceAlert();
    });
    
    document.getElementById('start_date').addEventListener('change', checkForPriceAdjustment);
    
    document.getElementById('start_time').addEventListener('change', function() {
        if (!endTimeSetManually && serviceDurationMinutes) {
            calculateEndTime();
        }
        setTimeout(checkForPriceAdjustment, 100);
    });
    
    document.getElementById('end_time').addEventListener('change', function() {
        endTimeSetManually = true;
        checkForPriceAdjustment();
    });
    
    function calculateEndTime() {
        if (endTimeSetManually) return;
        
        const startTime = document.getElementById('start_time').value;
        const serviceSelect = document.getElementById('service_id');
        const selectedOption = serviceSelect.options[serviceSelect.selectedIndex];
        const duration = selectedOption.getAttribute('data-duration');
        
        if (startTime && duration) {
            const [hours, minutes] = startTime.split(':').map(Number);
            const startMinutes = hours * 60 + minutes;
            const endMinutes = startMinutes + parseInt(duration);
            
            const endHours = Math.floor(endMinutes / 60);
            const endMins = endMinutes % 60;
            
            const endTime = String(endHours).padStart(2, '0') + ':' + String(endMins).padStart(2, '0');
            const endTimeInput = document.getElementById('end_time');
            endTimeInput.value = endTime;
            endTimeInput.setAttribute('value', endTime);
        }
    }

    function checkForPriceAdjustment() {
        if (!serviceDurationMinutes || !serviceBasePrice) return;
        
        const startTime = document.getElementById('start_time').value;
        const endTime = document.getElementById('end_time').value;
        
        if (!startTime || !endTime) return;
        
        const [startH, startM] = startTime.split(':').map(Number);
        const [endH, endM] = endTime.split(':').map(Number);
        const sessionDurationMinutes = (endH * 60 + endM) - (startH * 60 + startM);
        
        if (sessionDurationMinutes <= 0) {
            hidePriceAlert();
            return;
        }
        
        if (sessionDurationMinutes === serviceDurationMinutes) {
            hidePriceAlert();
            return;
        }
        
        const ratio = sessionDurationMinutes / serviceDurationMinutes;
        const newPrice = (serviceBasePrice * ratio).toFixed(2);
        
        showPriceAlert(newPrice, ratio, sessionDurationMinutes);
    }

    function showPriceAlert(newPrice, ratio, sessionDurationMinutes) {
        pendingNewPrice = newPrice;
        priceAlertAnswered = false;
        
        const alertDiv = document.getElementById('priceAlert');
        const messageEl = document.getElementById('priceAlertMessage');
        const questionEl = document.getElementById('priceAlertQuestion');
        const calculationEl = document.getElementById('priceAlertCalculation');
        
        const adjustmentType = sessionDurationMinutes > serviceDurationMinutes ? 'augmentée' : 'réduite';
        
        messageEl.textContent = `Durée ${adjustmentType} : ${sessionDurationMinutes} min (au lieu de ${serviceDurationMinutes} min)`;
        questionEl.textContent = `Voulez-vous adapter le prix à ${newPrice} TND ?`;
        calculationEl.textContent = `${serviceBasePrice} TND × ${ratio.toFixed(2)} = ${newPrice} TND`;
        
        alertDiv.classList.remove('hidden');
        alertDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    function hidePriceAlert() {
        document.getElementById('priceAlert').classList.add('hidden');
        pendingNewPrice = null;
    }

    function acceptPriceAdjustment() {
        if (pendingNewPrice) {
            document.getElementById('price_at_booking').value = pendingNewPrice;
        }
        priceAlertAnswered = true;
        hidePriceAlert();
    }

    function rejectPriceAdjustment() {
        priceAlertAnswered = true;
        hidePriceAlert();
    }

    document.querySelector('form').addEventListener('submit', function(e) {
        const startDate = document.getElementById('start_date').value;
        const startTime = document.getElementById('start_time').value;
        const endTime = document.getElementById('end_time').value;
        
        const alertVisible = !document.getElementById('priceAlert').classList.contains('hidden');
        
        if (alertVisible && !priceAlertAnswered) {
            e.preventDefault();
            allowSubmit = true;
            return false;
        }
        
        if (startDate && startTime) {
            const startDateTime = document.createElement('input');
            startDateTime.type = 'hidden';
            startDateTime.name = 'start_time';
            startDateTime.value = startDate + ' ' + startTime;
            this.appendChild(startDateTime);
            
            const endDateTime = document.createElement('input');
            endDateTime.type = 'hidden';
            endDateTime.name = 'end_time';
            endDateTime.value = startDate + ' ' + endTime;
            this.appendChild(endDateTime);
        }
    });
</script>
        </div>
    </div>
</div>
@endsection
