@extends('layouts.app')

@section('title', 'إنشاء خطاب إنهاء الدفاع المدني')

@push('styles')
    <link rel="stylesheet" href="{{ asset('css/civil-defense-custom.css') }}">
@endpush

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">إنشاء خطاب إنهاء الدفاع المدني</h3>
                    <div class="card-tools">
                        <a href="{{ route('civil-defense.termination-letters.index') }}" class="btn btn-default btn-sm">
                            <i class="fas fa-arrow-left"></i> العودة للقائمة
                        </a>
                    </div>
                </div>
                <form action="{{ route('civil-defense.termination-letters.store') }}" method="POST">
                    @csrf
                    <div class="card-body">
                        @if ($errors->any())
                            <div class="alert alert-danger">
                                <ul class="mb-0">
                                    @foreach ($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                            </div>
                        @endif

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="elevator_id">المصعد (تحت الصيانة) <span class="text-danger">*</span></label>
                                    <select name="elevator_id" id="elevator_id" class="form-control select2 @error('elevator_id') is-invalid @enderror" required>
                                        <option value="">اختر المصعد</option>
                                        @foreach($elevators as $elevator)
                                            <option value="{{ $elevator->id }}" {{ old('elevator_id') == $elevator->id ? 'selected' : '' }}>
                                                {{ $elevator->serial_number }} - {{ $elevator->customer->name ?? 'غير متوفر' }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('elevator_id')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="termination_date">تاريخ الإنهاء <span class="text-danger">*</span></label>
                                    <input type="date" name="termination_date" id="termination_date" class="form-control @error('termination_date') is-invalid @enderror" value="{{ old('termination_date', date('Y-m-d')) }}" required>
                                    @error('termination_date')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="customer_id">العميل <span class="text-danger">*</span></label>
                                    <input type="hidden" name="customer_id" id="customer_id" value="{{ old('customer_id') }}">
                                    <input type="text" id="customer_name" class="form-control" readonly>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="customer_phone">هاتف العميل</label>
                                    <input type="text" id="customer_phone" class="form-control" readonly>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="customer_address">عنوان العميل <span class="text-danger">*</span></label>
                                    <textarea name="customer_address" id="customer_address" class="form-control @error('customer_address') is-invalid @enderror" rows="3" required>{{ old('customer_address') }}</textarea>
                                    @error('customer_address')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-footer">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> حفظ
                        </button>
                        <a href="{{ route('civil-defense.termination-letters.index') }}" class="btn btn-default">
                            <i class="fas fa-times"></i> إلغاء
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
    $(function() {
        $('.select2').select2();

        // Get customer information when elevator is selected
        $('#elevator_id').on('change', function() {
            var elevatorId = $(this).val();
            console.log('Elevator selected:', elevatorId);
            
            if (elevatorId) {
                var url = "{{ route('civil-defense.get-customer-info') }}";
                console.log('AJAX URL:', url);
                
                $.ajax({
                    url: url,
                    type: "GET",
                    data: { elevator_id: elevatorId },
                    dataType: 'json',
                    beforeSend: function() {
                        console.log('Sending AJAX request...');
                    },
                    success: function(response) {
                        console.log('AJAX response:', response);
                        $('#customer_id').val(response.customer_id);
                        $('#customer_name').val(response.customer_name);
                        $('#customer_phone').val(response.customer_phone);
                        $('#customer_address').val(response.customer_address);
                    },
                    error: function(xhr, status, error) {
                        console.error('AJAX error:', error);
                        console.error('Status:', status);
                        console.error('Response:', xhr.responseText);
                        alert('Error fetching customer information. Please check console for details.');
                    }
                });
            } else {
                $('#customer_id').val('');
                $('#customer_name').val('');
                $('#customer_phone').val('');
                $('#customer_address').val('');
            }
        });

        // If elevator_id is already selected (e.g., on validation error), trigger change event
        if ($('#elevator_id').val()) {
            $('#elevator_id').trigger('change');
        }
    });
</script>
@endpush