@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h2>Create New Tenancy</h2>
                </div>
                <div class="card-body">
                    <form action="{{ route('tenancy.store') }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        @include('tenancy.form')
                        
                        <div class="form-group row mb-0">
                            <div class="col-md-6 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Create Tenancy') }}
                                </button>
                                <a href="{{ route('tenancy.index') }}" class="btn btn-secondary">
                                    {{ __('Cancel') }}
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    $(document).ready(function() {
        // Initialize select2
        $('.select2').select2({
            theme: 'bootstrap4',
            width: '100%'
        });
        
        // Load available units when property or block changes
        $('select[name="property_id"], select[name="block_id"]').on('change', function() {
            loadAvailableUnits();
        });
        
        function loadAvailableUnits() {
            $.ajax({
                url: '{{ route("tenancy.get-available-units") }}',
                type: 'GET',
                data: {
                    property_id: $('select[name="property_id"]').val(),
                    block_id: $('select[name="block_id"]').val()
                },
                success: function(response) {
                    var unitSelect = $('select[name="unit_id"]');
                    unitSelect.empty();
                    
                    if (response.length > 0) {
                        $.each(response, function(key, unit) {
                            unitSelect.append(new Option(unit.UnitIdentity, unit.UnitID));
                        });
                        unitSelect.trigger('change');
                    } else {
                        unitSelect.append(new Option('No units available', ''));
                    }
                }
            });
        }
        
        // Load units on page load
        loadAvailableUnits();
    });
</script>
@endpush
@endsection
