@extends('layouts.app')

@section('title', 'Create Equipment Reservation')

@section('content')
<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Create New Equipment Reservation</h5>
                        <a href="{{ route('equipment-reservations.index') }}" class="btn btn-outline-secondary btn-sm">
                            <i class="bi bi-arrow-left"></i> Back to Reservations
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <form action="{{ route('equipment-reservations.store') }}" method="POST" id="reservationForm">
                        @csrf
                        
                        <div class="row">
                            <div class="col-md-8">
                                <!-- Equipment Selection -->
                                <div class="mb-4">
                                    <h6 class="text-primary mb-3">Equipment Selection</h6>
                                    
                                    <div class="mb-3">
                                        <label for="equipment_id" class="form-label">Select Equipment *</label>
                                        <select class="form-select @error('equipment_id') is-invalid @enderror" 
                                                id="equipment_id" name="equipment_id" required>
                                            <option value="">Choose Equipment</option>
                                            @foreach($equipment as $item)
                                                <option value="{{ $item->id }}" 
                                                        {{ old('equipment_id', $selectedEquipment?->id) == $item->id ? 'selected' : '' }}
                                                        data-type="{{ $item->type }}"
                                                        data-start-time="{{ $item->start_time->format('H:i') }}"
                                                        data-end-time="{{ $item->end_time->format('H:i') }}"
                                                        data-slot-duration="{{ $item->slot_duration }}">
                                                    {{ $item->name }} ({{ $item->type_name }})
                                                </option>
                                            @endforeach
                                        </select>
                                        @error('equipment_id')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                    
                                    <div id="equipmentInfo" class="alert alert-info d-none">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <strong>Operating Hours:</strong><br>
                                                <span id="operatingHours">-</span>
                                            </div>
                                            <div class="col-md-4">
                                                <strong>Slot Duration:</strong><br>
                                                <span id="slotDuration">-</span>
                                            </div>
                                            <div class="col-md-4">
                                                <strong>Available Slots:</strong><br>
                                                <span id="availableSlots">-</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Date and Time Selection -->
                                <div class="mb-4">
                                    <h6 class="text-primary mb-3">Date and Time Selection</h6>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="reservation_date" class="form-label">Reservation Date *</label>
                                            <input type="date" class="form-control @error('reservation_date') is-invalid @enderror" 
                                                   id="reservation_date" name="reservation_date" 
                                                   value="{{ old('reservation_date', $selectedDate) }}" 
                                                   min="{{ date('Y-m-d') }}" readonly>
                                            @error('reservation_date')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>
                                        
                                        <div class="col-md-6 mb-3">
                                            <label for="time_slot_ids" class="form-label">Time Slots *</label>
                                            <select class="form-select @error('time_slot_ids') is-invalid @enderror" 
                                                    id="time_slot_ids" name="time_slot_ids[]" multiple required>
                                                <option value="">Select Equipment and Date First</option>
                                            </select>
                                            <small class="form-text text-muted">Hold Ctrl (or Cmd on Mac) to select multiple time slots</small>
                                            @error('time_slot_ids')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>
                                    </div>
                                    
                                    <div id="timeSlotsInfo" class="alert alert-warning d-none">
                                        <i class="bi bi-info-circle"></i>
                                        <span id="timeSlotsMessage">Select equipment and date to see available time slots</span>
                                    </div>
                                </div>

                                <!-- Additional Information -->
                                <div class="mb-4">
                                    <h6 class="text-primary mb-3">Additional Information</h6>
                                    
                                    <div class="mb-3">
                                        <label for="notes" class="form-label">Notes</label>
                                        <textarea class="form-control @error('notes') is-invalid @enderror" 
                                                  id="notes" name="notes" rows="3" 
                                                  placeholder="Any additional notes or special requirements...">{{ old('notes') }}</textarea>
                                        @error('notes')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <!-- Reservation Summary -->
                                <div class="card bg-light">
                                    <div class="card-header">
                                        <h6 class="mb-0">Reservation Summary</h6>
                                    </div>
                                    <div class="card-body">
                                        <div id="reservationSummary">
                                            <p class="text-muted">Select equipment and time to see reservation details</p>
                                        </div>
                                    </div>
                                </div>

                                <!-- Quick Help -->
                                <div class="card mt-3">
                                    <div class="card-header">
                                        <h6 class="mb-0">Quick Help</h6>
                                    </div>
                                    <div class="card-body">
                                        <ul class="list-unstyled small">
                                            <li><i class="bi bi-info-circle text-primary"></i> Reservations can be made for today or future dates</li>
                                            <li><i class="bi bi-clock text-primary"></i> Time slots are 30 minutes by default</li>
                                            <li><i class="bi bi-calendar text-primary"></i> Operating hours are 6:00 AM to 6:00 PM</li>
                                            <li><i class="bi bi-check-circle text-primary"></i> You can select multiple time slots for the same equipment</li>
                                            <li><i class="bi bi-mouse text-primary"></i> Hold Ctrl (or Cmd on Mac) to select multiple slots</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <hr>

                        <div class="d-flex justify-content-end gap-2">
                            <a href="{{ route('equipment-reservations.index') }}" class="btn btn-outline-secondary">
                                Cancel
                            </a>
                            <button type="submit" class="btn btn-primary" id="submitBtn" disabled>
                                <i class="bi bi-check-circle"></i> Create Reservation(s)
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const equipmentSelect = document.getElementById('equipment_id');
    const dateInput = document.getElementById('reservation_date');
    const timeSlotSelect = document.getElementById('time_slot_ids');
    const equipmentInfo = document.getElementById('equipmentInfo');
    const timeSlotsInfo = document.getElementById('timeSlotsInfo');
    const reservationSummary = document.getElementById('reservationSummary');
    const submitBtn = document.getElementById('submitBtn');
    
    let selectedEquipment = null;
    let availableSlots = [];

    // Update equipment info when equipment is selected
    equipmentSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        if (this.value) {
            selectedEquipment = {
                id: this.value,
                name: selectedOption.text,
                type: selectedOption.dataset.type,
                startTime: selectedOption.dataset.startTime,
                endTime: selectedOption.dataset.endTime,
                slotDuration: selectedOption.dataset.slotDuration
            };
            
            // Show equipment info
            document.getElementById('operatingHours').textContent = `${selectedEquipment.startTime} - ${selectedEquipment.endTime}`;
            document.getElementById('slotDuration').textContent = `${selectedEquipment.slotDuration} minutes`;
            equipmentInfo.classList.remove('d-none');
            
            // Load time slots if date is selected
            if (dateInput.value) {
                loadTimeSlots();
            }
        } else {
            selectedEquipment = null;
            equipmentInfo.classList.add('d-none');
            timeSlotsInfo.classList.add('d-none');
            timeSlotSelect.innerHTML = '<option value="">Select Equipment First</option>';
            updateReservationSummary();
        }
    });

    // Load time slots when date changes
    dateInput.addEventListener('change', function() {
        if (equipmentSelect.value && this.value) {
            loadTimeSlots();
        }
    });

    // Update time slot options when time slots are loaded
    timeSlotSelect.addEventListener('change', function() {
        updateReservationSummary();
    });

    function loadTimeSlots() {
        if (!selectedEquipment || !dateInput.value) return;

        const url = `/equipment/${selectedEquipment.id}/time-slots?date=${dateInput.value}`;
        
        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    availableSlots = data.data.available_slots || [];
                    console.log('Available slots:', availableSlots); // Debug log
                    updateTimeSlotsSelect();
                    updateTimeSlotsInfo();
                }
            })
            .catch(error => {
                console.error('Error loading time slots:', error);
                timeSlotsInfo.classList.remove('d-none');
                timeSlotsInfo.classList.remove('alert-success');
                timeSlotsInfo.classList.add('alert-warning');
                document.getElementById('timeSlotsMessage').textContent = 'Error loading time slots. Please try again.';
            });
    }

    function updateTimeSlotsSelect() {
        timeSlotSelect.innerHTML = '<option value="">Select Time Slots</option>';
        
        if (availableSlots && availableSlots.length > 0) {
            availableSlots.forEach(slot => {
                const option = document.createElement('option');
                option.value = slot.id;
                option.textContent = `${slot.start_time} - ${slot.end_time}`;
                timeSlotSelect.appendChild(option);
            });
            
            document.getElementById('availableSlots').textContent = availableSlots.length;
        } else {
            timeSlotSelect.innerHTML = '<option value="">No available slots</option>';
            document.getElementById('availableSlots').textContent = '0';
        }
    }

    function updateTimeSlotsInfo() {
        if (availableSlots && availableSlots.length > 0) {
            timeSlotsInfo.classList.remove('d-none');
            timeSlotsInfo.classList.remove('alert-warning');
            timeSlotsInfo.classList.add('alert-success');
            document.getElementById('timeSlotsMessage').textContent = 
                `${availableSlots.length} time slot(s) available for the selected date`;
        } else {
            timeSlotsInfo.classList.remove('d-none');
            timeSlotsInfo.classList.remove('alert-success');
            timeSlotsInfo.classList.add('alert-warning');
            document.getElementById('timeSlotsMessage').textContent = 
                'No available time slots for the selected date';
        }
    }

    function updateReservationSummary() {
        const selectedOptions = Array.from(timeSlotSelect.selectedOptions);
        
        if (selectedEquipment && selectedOptions.length > 0) {
            const selectedSlots = selectedOptions.map(option => {
                return availableSlots.find(slot => slot.id == option.value);
            }).filter(slot => slot); // Remove any undefined slots
            
            const duration = selectedEquipment.slotDuration;
            const slotCount = selectedSlots.length;
            
            let timeSlotsHtml = '';
            selectedSlots.forEach(slot => {
                timeSlotsHtml += `<div class="mb-1">• ${slot.start_time} - ${slot.end_time}</div>`;
            });
            
            reservationSummary.innerHTML = `
                <div class="mb-2">
                    <strong>Equipment:</strong><br>
                    ${selectedEquipment.name}
                </div>
                <div class="mb-2">
                    <strong>Selected Slots:</strong><br>
                    ${slotCount} slot(s) selected
                </div>
                <div class="mb-2">
                    <strong>Time Slots:</strong><br>
                    ${timeSlotsHtml}
                </div>
                <div class="mb-2">
                    <strong>Duration per Slot:</strong><br>
                    ${duration} minutes
                </div>
                <div class="mb-2">
                    <strong>Total Duration:</strong><br>
                    ${duration * slotCount} minutes
                </div>
                <hr>
                <div class="text-success">
                    <i class="bi bi-check-circle"></i> Ready to create ${slotCount} reservation${slotCount > 1 ? 's' : ''}
                </div>
            `;
            
            submitBtn.disabled = false;
        } else {
            reservationSummary.innerHTML = '<p class="text-muted">Select equipment and time slots to see reservation details</p>';
            submitBtn.disabled = true;
        }
    }

    // Initialize if equipment is pre-selected
    if (equipmentSelect.value) {
        equipmentSelect.dispatchEvent(new Event('change'));
    }
});
</script>
@endpush 