<div class="form-group row mb-3">
    <label for="customer_id" class="col-md-4 col-form-label text-md-right">{{ __('Tenant') }} <span class="text-danger">*</span></label>
    <div class="col-md-6">
        <select name="customer_id" id="customer_id" class="form-control select2 @error('customer_id') is-invalid @enderror" required>
            <option value="">Select Tenant</option>
            @foreach($customers as $customer)
                <option value="{{ $customer->CustomerID }}" {{ (isset($tenancy) && $tenancy->customer_id == $customer->CustomerID) || old('customer_id') == $customer->CustomerID ? 'selected' : '' }}>
                    {{ $customer->CustomerName }} - {{ $customer->AccountNo }} 
                </option>
            @endforeach
        </select>
        @error('customer_id')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

@php
// Load all properties with their blocks and units
$properties = \App\Models\Property::with(['blocks', 'blocks.units'])
    ->where('CompanyID', auth()->user()->CompanyID)
    ->get();

// Get all blocks and units for the initial page load
$allBlocks = \App\Models\Block::whereIn('PropID', $properties->pluck('PropID'))->get();
$allUnits = \App\Models\ProUnit::whereIn('BlockID', $allBlocks->pluck('BlockID'))->get();

// Get selected values for edit mode
$selectedProperty = isset($tenancy) && $tenancy->unit ? $tenancy->unit->PropID : null;
$selectedBlock = isset($tenancy) && $tenancy->unit ? $tenancy->unit->BlockID : null;
$selectedUnit = isset($tenancy) ? $tenancy->unit_id : null;

// Prepare blocks and units data for JavaScript
$blocksData = [];
foreach ($properties as $property) {
    $blocksData[$property->PropID] = $property->blocks->map(function($block) {
        return [
            'id' => $block->BlockID,
            'name' => $block->BlockName
        ];
    })->toArray();
}

$unitsData = [];
foreach ($allBlocks as $block) {
    $unitsData[$block->BlockID] = $block->units->map(function($unit) {
        return [
            'id' => $unit->UnitID,
            'name' => $unit->UnitIdentity,
            'block_id' => $unit->BlockID,
            'property_id' => $unit->PropID
        ];
    })->toArray();
}
@endphp

<div class="form-group row mb-3">
    <label class="col-md-4 col-form-label text-md-right">Property & Unit <span class="text-danger">*</span></label>
    <div class="col-md-6">
        <div class="row">
            <div class="col-md-6 mb-2">
                <select name="property_id" id="property_id" class="form-control select2">
                    <option value="">Select Property</option>
                    @foreach($properties as $property)
                        <option value="{{ $property->PropID }}" 
                            {{ $selectedProperty == $property->PropID ? 'selected' : '' }}>
                            {{ $property->PropName }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-6 mb-2">
                <select name="block_id" id="block_id" class="form-control select2">
                    <option value="">Select Block</option>
                    @foreach($allBlocks as $block)
                        <option value="{{ $block->BlockID }}" 
                            data-property="{{ $block->PropID }}"
                            {{ $selectedBlock == $block->BlockID ? 'selected' : '' }}>
                            {{ $block->BlockName }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-12">
                <select name="unit_id" id="unit_id" class="form-control select2 @error('unit_id') is-invalid @enderror" required>
                    <option value="">Select Unit</option>
                    @foreach($allUnits as $unit)
                        <option value="{{ $unit->UnitID }}"
                            data-block="{{ $unit->BlockID }}"
                            data-property="{{ $unit->PropID }}"
                            {{ $selectedUnit == $unit->UnitID ? 'selected' : '' }}>
                            {{ $unit->UnitIdentity }}
                        </option>
                    @endforeach
                </select>
                @error('unit_id')
                    <span class="invalid-feedback" role="alert">
                        <strong>{{ $message }}</strong>
                    </span>
                @enderror
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
$(document).ready(function() {
    // Initialize Select2
    $('.select2').select2({
        width: '100%',
        placeholder: 'Select an option',
        allowClear: true
    });

    // Cache selectors
    const $propertySelect = $('#property_id');
    const $blockSelect = $('#block_id');
    const $unitSelect = $('#unit_id');
    
    // Initialize form state
    function updateFormState() {
        const propertyId = $propertySelect.val();
        const blockId = $blockSelect.val();
        
        // Update block select state
        $blockSelect.prop('disabled', !propertyId);
        
        // Update unit select state
        $unitSelect.prop('disabled', !blockId);
        
        // If no property is selected, disable both block and unit selects
        if (!propertyId) {
            $blockSelect.prop('disabled', true);
            $unitSelect.prop('disabled', true);
        }
    }
    
    // Set initial state
    updateFormState();

    // When property changes
    $propertySelect.on('change', function() {
        const propertyId = $(this).val();
        
        // Reset dependent selects
        $blockSelect.val('').trigger('change');
        $unitSelect.val('').trigger('change');
        
        // Update block select state
        updateBlockSelectState();
        
        if (!propertyId) {
            return;
        }
        
        // Show/hide blocks based on selected property
        $blockSelect.find('option').each(function() {
            const $option = $(this);
            if ($option.val() === '') {
                $option.show();
            } else {
                const blockPropertyId = $option.data('property');
                $option.toggle(blockPropertyId == propertyId);
            }
        });
        
        // Enable block select if there are visible options (other than the default)
        const hasVisibleBlocks = $blockSelect.find('option:not([value=""]):visible').length > 0;
        $blockSelect.prop('disabled', !hasVisibleBlocks);
    });
    
    // When block changes
    $blockSelect.on('change', function() {
        const blockId = $(this).val();
        
        // Reset unit selection
        $unitSelect.val('');
        
        if (!blockId) {
            updateFormState();
            return;
        }
        
        // Show/hide units based on selected block
        $unitSelect.find('option').each(function() {
            const $option = $(this);
            if ($option.val() === '') {
                $option.show();
            } else {
                const unitBlockId = $option.data('block');
                $option.toggle(unitBlockId === blockId);
            }
        });
        
        // Update form state
        updateFormState();
    });
    
    // Trigger change on property select if it has a value (edit mode)
    if ($propertySelect.val()) {
        // Manually filter blocks for the pre-selected property
        const propertyId = $propertySelect.val();
        $blockSelect.find('option').each(function() {
            const $option = $(this);
            if ($option.val() === '') {
                $option.show();
            } else {
                const blockPropertyId = $option.data('property');
                $option.toggle(blockPropertyId == propertyId);
            }
        });
        
        // Enable block select and trigger change
        $blockSelect.prop('disabled', false);
        if ($blockSelect.val()) {
            $blockSelect.trigger('change');
        }
    }
    
    // Trigger change on block select if it has a value (edit mode)
    if ($blockSelect.val()) {
        $blockSelect.trigger('change');
    }
});
</script>
@endpush

<div class="form-group row mb-3">
    <label for="status_id" class="col-md-4 col-form-label text-md-right">{{ __('Status') }} <span class="text-danger">*</span></label>
    <div class="col-md-6">
        <select name="status_id" id="status_id" class="form-control select2 @error('status_id') is-invalid @enderror" required>
            <option value="">Select Status</option>
            @foreach($statuses as $status)
                <option value="{{ $status->id }}" {{ (isset($tenancy) && $tenancy->status_id == $status->id) || old('status_id') == $status->id ? 'selected' : '' }}>
                    {{ $status->name }}
                </option>
            @endforeach
        </select>
        @error('status_id')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

<div class="form-group row mb-3">
    <label for="start_date" class="col-md-4 col-form-label text-md-right">{{ __('Start Date') }} <span class="text-danger">*</span></label>
    <div class="col-md-6">
        <input id="start_date" type="date" class="form-control @error('start_date') is-invalid @enderror" name="start_date" value="{{ old('start_date', isset($tenancy) ? $tenancy->start_date->format('Y-m-d') : '') }}" required>
        @error('start_date')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

<div class="form-group row mb-3">
    <label for="end_date" class="col-md-4 col-form-label text-md-right">{{ __('End Date') }}</label>
    <div class="col-md-6">
        <input id="end_date" type="date" class="form-control @error('end_date') is-invalid @enderror" name="end_date" value="{{ old('end_date', isset($tenancy) && $tenancy->end_date ? $tenancy->end_date->format('Y-m-d') : '') }}">
        @error('end_date')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

<div class="form-group row mb-3">
    <label for="monthly_rent" class="col-md-4 col-form-label text-md-right">{{ __('Monthly Rent') }} <span class="text-danger">*</span></label>
    <div class="col-md-6">
        <div class="input-group">
            <span class="input-group-text">{{ config('settings.currency_symbol', '$') }}</span>
            <input id="monthly_rent" type="number" step="0.01" min="0" class="form-control @error('monthly_rent') is-invalid @enderror" name="monthly_rent" value="{{ old('monthly_rent', $tenancy->monthly_rent ?? '') }}" required>
        </div>
        @error('monthly_rent')
            <span class="invalid-feedback d-block" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

<div class="form-group row mb-3">
    <label for="security_deposit" class="col-md-4 col-form-label text-md-right">{{ __('Security Deposit') }}</label>
    <div class="col-md-6">
        <div class="input-group">
            <span class="input-group-text">{{ config('settings.currency_symbol', '$') }}</span>
            <input id="security_deposit" type="number" step="0.01" min="0" class="form-control @error('security_deposit') is-invalid @enderror" name="security_deposit" value="{{ old('security_deposit', $tenancy->security_deposit ?? '0.00') }}">
        </div>
        @error('security_deposit')
            <span class="invalid-feedback d-block" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

<div class="form-group row mb-3">
    <label for="move_in_date" class="col-md-4 col-form-label text-md-right">{{ __('Move-in Date') }}</label>
    <div class="col-md-6">
        <input id="move_in_date" type="date" class="form-control @error('move_in_date') is-invalid @enderror" name="move_in_date" value="{{ old('move_in_date', isset($tenancy) && $tenancy->move_in_date ? $tenancy->move_in_date->format('Y-m-d') : '') }}">
        @error('move_in_date')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

@if(isset($tenancy) && $tenancy->status_id == 3) {{-- Assuming 3 is the ID for 'terminated' --}}
<div class="form-group row mb-3">
    <label for="move_out_date" class="col-md-4 col-form-label text-md-right">{{ __('Move-out Date') }}</label>
    <div class="col-md-6">
        <input id="move_out_date" type="date" class="form-control @error('move_out_date') is-invalid @enderror" name="move_out_date" value="{{ old('move_out_date', $tenancy->move_out_date ? $tenancy->move_out_date->format('Y-m-d') : '') }}">
        @error('move_out_date')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>
@endif

<div class="form-group row mb-3">
    <label for="services" class="col-md-4 col-form-label text-md-right">{{ __('Additional Services') }}</label>
    <div class="col-md-6">
        <select name="services[]" id="services" class="form-control select2 @error('services') is-invalid @enderror" multiple>
            @foreach($services as $id => $name)
                <option value="{{ $id }}" {{ (isset($selectedServices) && in_array($id, $selectedServices)) || in_array($id, old('services', [])) ? 'selected' : '' }}>
                    {{ $name }}
                </option>
            @endforeach
        </select>
        <small class="form-text text-muted">Select additional services for this tenancy</small>
        @error('services')
            <span class="invalid-feedback d-block" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

<div class="form-group row mb-3">
    <label for="lease_document" class="col-md-4 col-form-label text-md-right">{{ __('Lease Document') }}</label>
    <div class="col-md-6">
        <input id="lease_document" type="file" class="form-control @error('lease_document') is-invalid @enderror" name="lease_document">
        @if(isset($tenancy) && $tenancy->lease_document_path)
            <div class="mt-2">
                <a href="{{ Storage::url($tenancy->lease_document_path) }}" target="_blank" class="btn btn-sm btn-info">
                    <i class="fas fa-file-pdf"></i> View Current Document
                </a>
            </div>
        @endif
        @error('lease_document')
            <span class="invalid-feedback d-block" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>

<div class="form-group row mb-3">
    <label for="notes" class="col-md-4 col-form-label text-md-right">{{ __('Notes') }}</label>
    <div class="col-md-6">
        <textarea id="notes" class="form-control @error('notes') is-invalid @enderror" name="notes" rows="3">{{ old('notes', $tenancy->notes ?? '') }}</textarea>
        @error('notes')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
</div>
