@extends('layouts.app')

@section('title', 'Edit 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">Edit 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.update', $equipmentReservation) }}" method="POST" id="reservationForm">
                        @csrf
                        @method('PUT')
                        
                        <div class="row">
                            <div class="col-md-8">
                                <!-- Equipment Information (Read-only) -->
                                <div class="mb-4">
                                    <h6 class="text-primary mb-3">Equipment Information</h6>
                                    
                                    <div class="alert alert-info">
                                        <div class="d-flex align-items-center">
                                            <div class="avatar-sm bg-info text-white rounded-circle d-flex align-items-center justify-content-center me-3">
                                                <i class="bi bi-gear-wide-connected"></i>
                                            </div>
                                            <div>
                                                <h6 class="mb-1">{{ $equipmentReservation->equipment->name }}</h6>
                                                <span class="badge bg-info">{{ $equipmentReservation->equipment->type_name }}</span>
                                                <p class="mb-0 mt-1">
                                                    Operating Hours: {{ $equipmentReservation->equipment->start_time->format('H:i') }} - {{ $equipmentReservation->equipment->end_time->format('H:i') }} | 
                                                    Slot Duration: {{ $equipmentReservation->equipment->slot_duration }} minutes
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <input type="hidden" name="equipment_id" value="{{ $equipmentReservation->equipment_id }}">
                                </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', $equipmentReservation->reservation_date->format('Y-m-d')) }}" 
                                                   min="{{ date('Y-m-d') }}" required>
                                            @error('reservation_date')
                                                <div class="invalid-feedback">{{ $message }}</div>
                                            @enderror
                                        </div>
                                        
                                        <div class="col-md-6 mb-3">
                                            <label for="start_time" class="form-label">Start Time *</label>
                                            <select class="form-select @error('start_time') is-invalid @enderror" 
                                                    id="start_time" name="start_time" required>
                                                <option value="">Loading time slots...</option>
                                            </select>
                                            @error('start_time')
                                                <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">Loading available time slots...</span>
                                    </div>
                                </div>

                                <!-- Status Selection -->
                                <div class="mb-4">
                                    <h6 class="text-primary mb-3">Reservation Status</h6>
                                    
                                    <div class="mb-3">
                                        <label for="status" class="form-label">Status *</label>
                                        <select class="form-select @error('status') is-invalid @enderror" 
                                                id="status" name="status" required>
                                            @foreach($statuses as $key => $name)
                                                <option value="{{ $key }}" 
                                                        {{ old('status', $equipmentReservation->status) == $key ? 'selected' : '' }}>
                                                    {{ $name }}
                                                </option>
                                            @endforeach
                                        </select>
                                        @error('status')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </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', $equipmentReservation->notes) }}</textarea>
                                        @error('notes')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <!-- Current Reservation Info -->
                                <div class="card bg-light mb-4">
                                    <div class="card-header">
                                        <h6 class="mb-0">Current Reservation</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <strong>Equipment:</strong><br>
                                            {{ $equipmentReservation->equipment->name }}
                                        </div>
                                        <div class="mb-3">
                                            <strong>Current Date:</strong><br>
                                            {{ $equipmentReservation->formatted_date }}
                                        </div>
                                        <div class="mb-3">
                                            <strong>Current Time:</strong><br>
                                            {{ $equipmentReservation->formatted_time_range }}
                                        </div>
                                        <div class="mb-3">
                                            <strong>Current Status:</strong><br>
                                            <span class="badge {{ $equipmentReservation->status_badge_class }}">
                                                {{ $equipmentReservation->status_name }}
                                            </span>
                                        </div>
                                        <div class="mb-3">
                                            <strong>User:</strong><br>
                                            {{ $equipmentReservation->user->name }}
                                        </div>
                                        <div>
                                            <strong>Created:</strong><br>
                                            {{ $equipmentReservation->created_at->format('M d, Y H:i') }}
                                        </div>
                                    </div>
                                </div>

                                <!-- Updated Reservation Summary -->
                                <div class="card bg-light">
                                    <div class="card-header">
                                        <h6 class="mb-0">Updated Reservation Summary</h6>
                                    </div>
                                    <div class="card-body">
                                        <div id="reservationSummary">
                                            <p class="text-muted">Make changes to see updated summary</p>
                                        </div>
                                    </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">
                                <i class="bi bi-check-circle"></i> Update Reservation
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const dateInput = document.getElementById('reservation_date');
    const startTimeSelect = document.getElementById('start_time');
    const timeSlotsInfo = document.getElementById('timeSlotsInfo');
    const reservationSummary = document.getElementById('reservationSummary');
    const statusSelect = document.getElementById('status');
    const notesTextarea = document.getElementById('notes');
    
    let availableSlots = [];
    const equipmentId = {{ $equipmentReservation->equipment_id }};
    const currentStartTime = '{{ $equipmentReservation->start_time->format("H:i") }}';

    // Load time slots on page load
    loadTimeSlots();

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

    // Update summary when any field changes
    [startTimeSelect, statusSelect, notesTextarea].forEach(element => {
        element.addEventListener('change', updateReservationSummary);
    });

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

        const url = `/equipment/${equipmentId}/time-slots?date=${dateInput.value}`;
        
        // Show loading state
        startTimeSelect.innerHTML = '<option value="">Loading...</option>';
        timeSlotsInfo.classList.remove('d-none');
        document.getElementById('timeSlotsMessage').textContent = 'Loading available time slots...';
        
        fetch(url)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    availableSlots = data.data.available_slots;
                    updateTimeSlotsSelect();
                    updateTimeSlotsInfo();
                }
            })
            .catch(error => {
                console.error('Error loading time slots:', error);
                timeSlotsInfo.classList.remove('d-none');
                document.getElementById('timeSlotsMessage').textContent = 'Error loading time slots. Please try again.';
            });
    }

    function updateTimeSlotsSelect() {
        startTimeSelect.innerHTML = '<option value="">Select Time Slot</option>';
        
        if (availableSlots.length > 0) {
            availableSlots.forEach(slot => {
                const option = document.createElement('option');
                option.value = slot.start_time;
                option.textContent = `${slot.start_time} - ${slot.end_time}`;
                
                // Select current time if available
                if (slot.start_time === currentStartTime) {
                    option.selected = true;
                }
                
                startTimeSelect.appendChild(option);
            });
        } else {
            startTimeSelect.innerHTML = '<option value="">No available slots</option>';
        }
        
        updateReservationSummary();
    }

    function updateTimeSlotsInfo() {
        if (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() {
        if (dateInput.value && startTimeSelect.value) {
            const selectedSlot = availableSlots.find(slot => slot.start_time === startTimeSelect.value);
            const statusText = statusSelect.options[statusSelect.selectedIndex].text;
            
            reservationSummary.innerHTML = `
                <div class="mb-2">
                    <strong>Equipment:</strong><br>
                    {{ $equipmentReservation->equipment->name }}
                </div>
                <div class="mb-2">
                    <strong>Date:</strong><br>
                    ${new Date(dateInput.value).toLocaleDateString()}
                </div>
                <div class="mb-2">
                    <strong>Time:</strong><br>
                    ${startTimeSelect.value} - ${selectedSlot ? selectedSlot.end_time : ''}
                </div>
                <div class="mb-2">
                    <strong>Status:</strong><br>
                    <span class="badge bg-${getStatusBadgeClass(statusSelect.value)}">${statusText}</span>
                </div>
                <div class="mb-2">
                    <strong>User:</strong><br>
                    {{ $equipmentReservation->user->name }}
                </div>
                <hr>
                <div class="text-success">
                    <i class="bi bi-check-circle"></i> Ready to update reservation
                </div>
            `;
        } else {
            reservationSummary.innerHTML = '<p class="text-muted">Make changes to see updated summary</p>';
        }
    }

    function getStatusBadgeClass(status) {
        const statusClasses = {
            'confirmed': 'success',
            'cancelled': 'danger',
            'completed': 'info'
        };
        return statusClasses[status] || 'secondary';
    }
});
</script>
@endpush 