@extends('customers.layout')

@section('customer-content')
    <div class="bg-gradient-to-r from-blue-700 to-blue-800 shadow-lg rounded-lg mb-8 overflow-hidden">
        <div class="px-6 py-4">
            <div class="flex items-center">
                <div class="flex-shrink-0 bg-yellow-100 p-2 rounded-lg mr-4">
                    <svg class="h-8 w-8 text-yellow-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v1H3v-1z" />
                    </svg>
                </div>
                <div>
                    <h2 class="text-2xl font-bold text-yellow-400">
                        Add New Customer
                    </h2>
                    <p class="mt-1 text-sm text-blue-200">
                        Fill in the details below to create a new customer record.
                    </p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="bg-white shadow-xl rounded-lg overflow-hidden">
        
        <form action="{{ route('customers.store') }}" method="POST" class="p-6">
            @csrf
            
            <div class="space-y-6">
                <!-- Personal Information -->
                <div>
                    <div class="flex items-center mb-4 pb-2 border-b border-gray-200">
                        <div class="flex-shrink-0 bg-blue-100 p-1.5 rounded-full mr-3">
                            <svg class="h-5 w-5 text-blue-700" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                            </svg>
                        </div>
                        <h4 class="text-lg font-semibold text-gray-800">
                            Personal Information
                        </h4>
                    </div>
                    
                    <div class="grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
                        <div class="sm:col-span-3">
                            <label for="CustomerName" class="block text-sm font-medium text-gray-700">
                                Full Name <span class="text-red-500">*</span>
                            </label>
                            <div class="mt-1">
                                <input type="text" name="CustomerName" id="CustomerName" autocomplete="name" 
                                    value="{{ old('CustomerName') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md @error('CustomerName') border-red-300 text-red-900 placeholder-red-300 focus:outline-none focus:ring-red-500 focus:border-red-500 @enderror">
                                @error('CustomerName')
                                    <p class="mt-2 text-sm text-red-600" id="name-error">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="TenantName" class="block text-sm font-medium text-gray-700">
                                Tenant Name (if different)
                            </label>
                            <div class="mt-1">
                                <input type="text" name="TenantName" id="TenantName" 
                                    value="{{ old('TenantName') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md">
                                @error('TenantName')
                                    <p class="mt-2 text-sm text-red-600" id="tenant-name-error">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="TelNo" class="block text-sm font-medium text-gray-700">
                                Phone Number <span class="text-red-500">*</span>
                            </label>
                            <div class="mt-1">
                                <input type="text" name="TelNo" id="TelNo" autocomplete="tel" 
                                    value="{{ old('TelNo') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md @error('TelNo') border-red-300 text-red-900 placeholder-red-300 focus:outline-none focus:ring-red-500 focus:border-red-500 @enderror">
                                @error('TelNo')
                                    <p class="mt-2 text-sm text-red-600" id="tel-error">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="Email" class="block text-sm font-medium text-gray-700">
                                Email Address
                            </label>
                            <div class="mt-1">
                                <input type="email" name="Email" id="Email" autocomplete="email" 
                                    value="{{ old('Email') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md @error('Email') border-red-300 text-red-900 placeholder-red-300 focus:outline-none focus:ring-red-500 focus:border-red-500 @enderror">
                                @error('Email')
                                    <p class="mt-2 text-sm text-red-600" id="email-error">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="Address1" class="block text-sm font-medium text-gray-700">
                                Address Line 1 <span class="text-red-500">*</span>
                            </label>
                            <div class="mt-1">
                                <input type="text" name="Address1" id="Address1" autocomplete="address-line1" 
                                    value="{{ old('Address1') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md @error('Address1') border-red-300 text-red-900 placeholder-red-300 focus:outline-none focus:ring-red-500 focus:border-red-500 @enderror">
                                @error('Address1')
                                    <p class="mt-2 text-sm text-red-600" id="address1-error">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="Address2" class="block text-sm font-medium text-gray-700">
                                Address Line 2
                            </label>
                            <div class="mt-1">
                                <input type="text" name="Address2" id="Address2" autocomplete="address-line2" 
                                    value="{{ old('Address2') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md">
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="Address3" class="block text-sm font-medium text-gray-700">
                                City/Town
                            </label>
                            <div class="mt-1">
                                <input type="text" name="Address3" id="Address3" autocomplete="address-level2" 
                                    value="{{ old('Address3') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md">
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="ClientCode" class="block text-sm font-medium text-gray-700">
                                Client/ID Number
                            </label>
                            <div class="mt-1">
                                <input type="text" name="ClientCode" id="ClientCode" 
                                    value="{{ old('ClientCode') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md">
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Account Information -->
                <div>
                    <div class="flex items-center mb-4 pb-2 border-b border-gray-200">
                        <div class="flex-shrink-0 bg-blue-100 p-1.5 rounded-full mr-3">
                            <svg class="h-5 w-5 text-blue-700" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
                            </svg>
                        </div>
                        <h4 class="text-lg font-semibold text-gray-800">
                            Account Information
                        </h4>
                    </div>
                    
                    <div class="grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
                        <div class="sm:col-span-3">
                            <label for="AccountNo" class="block text-sm font-medium text-gray-700">
                                Account Number <span class="text-red-500">*</span>
                            </label>
                            <div class="mt-1">
                                <input type="text" name="AccountNo" id="AccountNo" 
                                    value="{{ old('AccountNo', 'CUST-' . strtoupper(Str::random(6))) }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md @error('AccountNo') border-red-300 text-red-900 placeholder-red-300 focus:outline-none focus:ring-red-500 focus:border-red-500 @enderror">
                                @error('AccountNo')
                                    <p class="mt-2 text-sm text-red-600" id="account-no-error">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="AccountType" class="block text-sm font-medium text-gray-700">
                                Account Type <span class="text-red-500">*</span>
                            </label>
                            <div class="mt-1">
                                <select id="AccountType" name="AccountType" class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md @error('AccountType') border-red-300 text-red-900 placeholder-red-300 focus:outline-none focus:ring-red-500 focus:border-red-500 @enderror">
                                    <option value="RESIDENTIAL" {{ old('AccountType', 'RESIDENTIAL') == 'RESIDENTIAL' ? 'selected' : '' }}>Residential</option>
                                    <option value="COMMERCIAL" {{ old('AccountType') == 'COMMERCIAL' ? 'selected' : '' }}>Commercial</option>
                                </select>
                                @error('AccountType')
                                    <p class="mt-2 text-sm text-red-600" id="account-type-error">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="ContractDate" class="block text-sm font-medium text-gray-700">
                                Contract Date <span class="text-red-500">*</span>
                            </label>
                            <div class="mt-1">
                                <input type="date" name="ContractDate" id="ContractDate" 
                                    value="{{ old('ContractDate', now()->format('Y-m-d')) }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md @error('ContractDate') border-red-300 text-red-900 placeholder-red-300 focus:outline-none focus:ring-red-500 focus:border-red-500 @enderror">
                                @error('ContractDate')
                                    <p class="mt-2 text-sm text-red-600" id="contract-date-error">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="AccountStatus" class="block text-sm font-medium text-gray-700">
                                Account Status <span class="text-red-500">*</span>
                            </label>
                            <div class="mt-1">
                                <select id="AccountStatus" name="AccountStatus" class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md @error('AccountStatus') border-red-300 text-red-900 placeholder-red-300 focus:outline-none focus:ring-red-500 focus:border-red-500 @enderror">
                                    <option value="A" {{ old('AccountStatus', 'A') == 'A' ? 'selected' : '' }}>Active</option>
                                    <option value="I" {{ old('AccountStatus') == 'I' ? 'selected' : '' }}>Inactive</option>
                                </select>
                                @error('AccountStatus')
                                    <p class="mt-2 text-sm text-red-600" id="account-status-error">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Deposit Information -->
                <div>
                    <div class="flex items-center mb-4 pb-2 border-b border-gray-200">
                        <div class="flex-shrink-0 bg-blue-100 p-1.5 rounded-full mr-3">
                            <svg class="h-5 w-5 text-blue-700" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg>
                        </div>
                        <h4 class="text-lg font-semibold text-gray-800">
                            Deposit Information
                        </h4>
                    </div>
                    
                    <div class="grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
                        <div class="sm:col-span-3">
                            <label for="Deposit" class="block text-sm font-medium text-gray-700">
                                Deposit Amount
                            </label>
                            <div class="mt-1 relative rounded-md shadow-sm">
                                <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                    <span class="text-gray-500 sm:text-sm">Ksh</span>
                                </div>
                                <input type="number" name="Deposit" id="Deposit" step="0.01" min="0" 
                                    value="{{ old('Deposit') }}"
                                    class="focus:ring-blue-500 focus:border-blue-500 block w-full pl-12 sm:text-sm border-gray-300 rounded-md @error('Deposit') border-red-300 text-red-900 placeholder-red-300 focus:outline-none focus:ring-red-500 focus:border-red-500 @enderror">
                                @error('Deposit')
                                    <p class="mt-2 text-sm text-red-600" id="deposit-error">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="DepositDate" class="block text-sm font-medium text-gray-700">
                                Deposit Date
                            </label>
                            <div class="mt-1">
                                <input type="date" name="DepositDate" id="DepositDate" 
                                    value="{{ old('DepositDate') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md @error('DepositDate') border-red-300 text-red-900 placeholder-red-300 focus:outline-none focus:ring-red-500 focus:border-red-500 @enderror">
                                @error('DepositDate')
                                    <p class="mt-2 text-sm text-red-600" id="deposit-date-error">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Unit Assignment -->
                <div>
                    <h4 class="text-md font-medium text-gray-900 mb-4 pb-2 border-b border-gray-200">
                        Unit Assignment
                    </h4>
                    
                    <div class="grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
                        <div class="sm:col-span-6">
                            <label for="UnitID" class="block text-sm font-medium text-gray-700">
                                Assign to Unit (Optional)
                            </label>
                            <div class="mt-1">
                                <select id="UnitID" name="UnitID" class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md">
                                    <option value="">-- Select a Unit --</option>
                                    @foreach($units as $id => $unitData)
                                        <option value="{{ $id }}" 
                                                data-property-id="{{ $unitData['property_id'] ?? '' }}" 
                                                data-water-meter="{{ $unitData['water_meter'] ?? '' }}" 
                                                data-electricity-meter="{{ $unitData['electricity_meter'] ?? '' }}"
                                                {{ old('UnitID') == $id ? 'selected' : '' }}>
                                            {{ $unitData['identity'] ?? $unitData }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <p class="mt-2 text-sm text-gray-500">
                                You can assign this customer to a unit now or do it later from the unit management section.
                            </p>
                        </div>
                    </div>
                </div>
                
                <!-- Meter Information -->
                <div id="meterInformationSection" class="hidden">
                    <div class="flex items-center mb-4 pb-2 border-b border-gray-200">
                        <div class="flex-shrink-0 bg-blue-100 p-1.5 rounded-full mr-3">
                            <svg class="h-5 w-5 text-blue-700" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                            </svg>
                        </div>
                        <h4 class="text-lg font-semibold text-gray-800">
                            Meter Information
                        </h4>
                    </div>
                    
                    <div class="grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-6">
                        <div class="sm:col-span-3">
                            <label for="WMeterNo" class="block text-sm font-medium text-gray-700">
                                Water Meter Number
                            </label>
                            <div class="mt-1">
                                <input type="text" name="WMeterNo" id="WMeterNo" 
                                    value="{{ old('WMeterNo') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md bg-gray-100"
                                    readonly>
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="WInitialReading" class="block text-sm font-medium text-gray-700">
                                Water Initial Reading
                            </label>
                            <div class="mt-1">
                                <input type="number" name="WInitialReading" id="WInitialReading" min="0" step="0.001"
                                    value="{{ old('WInitialReading') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md">
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="EMeterNo" class="block text-sm font-medium text-gray-700">
                                Electricity Meter Number
                            </label>
                            <div class="mt-1">
                                <input type="text" name="EMeterNo" id="EMeterNo" 
                                    value="{{ old('EMeterNo') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md bg-gray-100"
                                    readonly>
                            </div>
                        </div>
                        
                        <div class="sm:col-span-3">
                            <label for="EInitialReading" class="block text-sm font-medium text-gray-700">
                                Electricity Initial Reading
                            </label>
                            <div class="mt-1">
                                <input type="number" name="EInitialReading" id="EInitialReading" min="0" step="0.01"
                                    value="{{ old('EInitialReading') }}"
                                    class="shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Services Assignment -->
<div id="servicesSection" class="mt-8 hidden">
    <div class="flex items-center mb-4 pb-2 border-b border-gray-200">
        <div class="flex-shrink-0 bg-blue-100 p-1.5 rounded-full mr-3">
            <svg class="h-5 w-5 text-blue-700" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
            </svg>
        </div>
        <h4 class="text-lg font-semibold text-gray-800">
            Services Assignment
        </h4>
    </div>
    
    <!-- Services will be loaded here dynamically -->
    <div id="servicesContainer" class="space-y-4">
        <!-- Services will be inserted here by JavaScript -->
    </div>
    
    <!-- No services message -->
    <div id="noServicesMessage" class="hidden bg-gray-50 p-4 rounded-lg text-center text-gray-500">
        No services available for this property.
    </div>
    
    <!-- Loading indicator -->
    <div id="servicesLoading" class="hidden flex justify-center items-center py-4">
        <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        <span>Loading services...</span>
    </div>
</div>
                
                <!-- Form Actions -->
                <div class="pt-5">
                    <div class="flex justify-between">
                        <a href="{{ route('customers.index') }}" class="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-150">
                            <svg class="-ml-1 mr-2 h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                            </svg>
                            Back to Customers
                        </a>
                        <div class="space-x-3">
                            <button type="reset" class="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-150">
                                <svg class="-ml-1 mr-2 h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                </svg>
                                Reset
                            </button>
                            <button type="submit" class="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-150">
                                <svg class="-ml-1 mr-2 h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                                </svg>
                                Save Customer
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
    
    @push('scripts')
    <script>
        // Show/hide services section based on unit selection and load services
        document.addEventListener('DOMContentLoaded', function() {
            const unitSelect = document.getElementById('UnitID');
            const servicesSection = document.getElementById('servicesSection');
            const meterInfoSection = document.getElementById('meterInformationSection');
            const servicesContainer = document.getElementById('servicesContainer');
            const noServicesMessage = document.getElementById('noServicesMessage');
            
            // Function to handle unit selection change
            function handleUnitChange() {
                if (!unitSelect) return;
                
                const selectedOption = unitSelect.options[unitSelect.selectedIndex];
                const propertyId = selectedOption ? selectedOption.getAttribute('data-property-id') : null;
                const waterMeter = selectedOption ? selectedOption.getAttribute('data-water-meter') : '';
                const electricityMeter = selectedOption ? selectedOption.getAttribute('data-electricity-meter') : '';
                
                // Update meter information if available
                if (waterMeter) document.getElementById('WMeterNo').value = waterMeter;
                if (electricityMeter) document.getElementById('EMeterNo').value = electricityMeter;
                
                // Toggle sections based on selection
                if (unitSelect.value) {
                    if (servicesSection) servicesSection.classList.remove('hidden');
                    if (meterInfoSection) meterInfoSection.classList.remove('hidden');
                    
                    // Load services if property ID is available
                    if (propertyId) {
                        loadServices(propertyId);
                    } else if (noServicesMessage) {
                        noServicesMessage.textContent = 'No property information available for the selected unit.';
                        noServicesMessage.classList.remove('hidden');
                    }
                } else {
                    if (servicesSection) servicesSection.classList.add('hidden');
                    if (meterInfoSection) meterInfoSection.classList.add('hidden');
                    if (servicesContainer) servicesContainer.innerHTML = '';
                    if (noServicesMessage) noServicesMessage.classList.add('hidden');
                }
            }
            
            // Initialize event listener for unit selection
            if (unitSelect) {
                unitSelect.addEventListener('change', handleUnitChange);
                
                // Trigger change event if there's a pre-selected value (e.g., after validation error)
                if (unitSelect.value) {
                    handleUnitChange();
                }
            }
            
            // Function to load services for a property
            async function loadServices(propertyId) {
                console.log('Loading services for property ID:', propertyId);
                if (!propertyId) {
                    console.error('No property ID provided');
                    if (noServicesMessage) {
                        noServicesMessage.textContent = 'No property information available for the selected unit.';
                        noServicesMessage.classList.remove('hidden');
                    }
                    return;
                }
                
                // Show loading state
                const loadingElement = document.getElementById('servicesLoading');
                if (loadingElement) loadingElement.classList.remove('hidden');
                if (servicesContainer) servicesContainer.innerHTML = '';
                if (noServicesMessage) noServicesMessage.classList.add('hidden');
                
                try {
                    const url = `/properties/${propertyId}/services`;
                    console.log('Fetching from URL:', url);
                    
                    const response = await fetch(url, {
                        headers: {
                            'Accept': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || ''
                        },
                        credentials: 'same-origin'
                    });
                    
                    const data = await response.json();
                    console.log('Received response:', data);
                    
                    if (!response.ok || !data.success) {
                        throw new Error(data.message || `HTTP error! status: ${response.status}`);
                    }
                    
                    const services = data.data || [];
                    console.log('Services data:', services);
                    
                    // Hide loading state
                    if (loadingElement) loadingElement.classList.add('hidden');
                    
                    if (!servicesContainer) {
                        console.error('servicesContainer not found');
                        return;
                    }
                    
                    // Clear previous services
                    servicesContainer.innerHTML = '';
                    
                    if (services && services.length > 0) {
                        if (noServicesMessage) noServicesMessage.classList.add('hidden');
                        
                        // Add each service to the container
                        services.forEach(service => {
                            const serviceElement = document.createElement('div');
                            serviceElement.className = 'border border-gray-200 rounded-lg p-4 mt-2 service-item';
                            serviceElement.id = `service-${service.IDService}`;
                            serviceElement.innerHTML = `
                                <div class="flex items-start">
                                    <div class="flex items-center h-5">
                                        <input type="checkbox" 
                                               name="services[${service.IDService}][id]" 
                                               value="${service.IDService}" 
                                               id="service_${service.IDService}" 
                                               class="service-checkbox focus:ring-blue-500 h-4 w-4 text-blue-600 border-gray-300 rounded"
                                               data-price="${service.Price}"
                                               data-billing-cycle="MONTHLY">
                                    </div>
                                    <div class="ml-3 text-sm">
                                        <label for="service_${service.ServiceID}" class="font-medium text-gray-700">
                                            ${service.ServiceName}
                                        </label>
                                        <div class="mt-3 grid grid-cols-1 md:grid-cols-4 gap-4">
                                            <div>
                                                <label class="block text-xs font-medium text-gray-500">Unit Price</label>
                                                <div class="mt-1">
                                                    <input type="number" 
                                                           name="services[${service.IDService}][price]" 
                                                           value="${service.Price}" 
                                                           min="0" 
                                                           step="0.01"
                                                           class="service-price shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md"
                                                           disabled
                                                           readOnly>
                                                </div>
                                            </div>
                                            <div>
                                                <label class="block text-xs font-medium text-gray-500">Quantity</label>
                                                <div class="mt-1">
                                                    <input type="number" 
                                                           name="services[${service.IDService}][quantity]" 
                                                           value="1" 
                                                           min="1"
                                                           class="service-quantity shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md"
                                                           disabled>
                                                </div>
                                            </div>
                                            <div>
                                                <label class="block text-xs font-medium text-gray-500">Total</label>
                                                <div class="mt-1">
                                                    <input type="text" 
                                                           name="services[${service.IDService}][display_total]"
                                                           class="service-total shadow-sm bg-gray-100 block w-full sm:text-sm border-gray-300 rounded-md"
                                                           value="${service.Price}" 
                                                           readOnly
                                                           >
                                                </div>
                                            </div>
                                            <div>
                                                <label class="block text-xs font-medium text-gray-500">Start Date</label>
                                                <div class="mt-1">
                                                    <input type="date" 
                                                           name="services[${service.IDService}][start_date]" 
                                                           class="service-start-date shadow-sm focus:ring-blue-500 focus:border-blue-500 block w-full sm:text-sm border-gray-300 rounded-md"
                                                           value="${new Date().toISOString().split('T')[0]}"
                                                           disabled>
                                                </div>
                                            </div>
                                            <input type="hidden" name="services[${service.IDService}][billing_cycle]" value="MONTHLY" class="service-billing-cycle">
                                        </div>
                                    </div>
                                </div>
                            `;
                            servicesContainer.appendChild(serviceElement);
                        });
                    } else {
                        if (noServicesMessage) {
                            noServicesMessage.textContent = 'No services available for this property.';
                            noServicesMessage.classList.remove('hidden');
                        }
                    }
                } catch (error) {
                    console.error('Error loading services:', error);
                    if (noServicesMessage) {
                        noServicesMessage.textContent = error.message || 'Error loading services. Please try again.';
                        noServicesMessage.classList.remove('hidden');
                    }
                } finally {
                    if (loadingElement) loadingElement.classList.add('hidden');
                }
            }
            
            function toggleSections() {
                if (unitSelect && unitSelect.value) {
                    const selectedOption = unitSelect.options[unitSelect.selectedIndex];
                    const propertyId = selectedOption.getAttribute('data-property-id');
                    
                    // Show sections
                    if (servicesSection) servicesSection.classList.remove('hidden');
                    if (meterInfoSection) meterInfoSection.classList.remove('hidden');
                    
                    // Show loading state while we fetch services
                    const loadingElement = document.getElementById('servicesLoading');
                    if (loadingElement) loadingElement.classList.remove('hidden');
                    if (servicesContainer) servicesContainer.innerHTML = '';
                    if (noServicesMessage) noServicesMessage.classList.add('hidden');
                    
                    // Load services for the selected property
                    if (propertyId) {
                        loadServices(propertyId);
                    } else {
                        console.error('No property ID found for the selected unit');
                        if (loadingElement) loadingElement.classList.add('hidden');
                        if (noServicesMessage) {
                            noServicesMessage.textContent = 'No property information available for the selected unit.';
                            noServicesMessage.classList.remove('hidden');
                        }
                    }
                } else {
                    // Hide sections and clear services
                    if (servicesSection) servicesSection.classList.add('hidden');
                    if (meterInfoSection) meterInfoSection.classList.add('hidden');
                    if (servicesContainer) servicesContainer.innerHTML = '';
                    if (noServicesMessage) noServicesMessage.classList.add('hidden');
                    
                    const loadingElement = document.getElementById('servicesLoading');
                    if (loadingElement) loadingElement.classList.add('hidden');
                }
            }
            
            // Initialize the form
            handleUnitChange();
            
            // Function to calculate total
            function calculateTotal(serviceId) {
                const priceInput = document.querySelector(`.service-price[name="services[${serviceId}][price]"]`);
                const quantityInput = document.querySelector(`.service-quantity[name="services[${serviceId}][quantity]"]`);
                const totalInput = document.querySelector(`.service-total[name="services[${serviceId}][display_total]"]`);
                
                if (priceInput && quantityInput) {
                    const price = parseFloat(priceInput.value) || 0;
                    const quantity = parseInt(quantityInput.value) || 1;
                    const total = (price * quantity).toFixed(2);
                    
                    if (totalInput) {
                        totalInput.value = total;
                        // Format with thousands separators
                        totalInput.value = parseFloat(total).toLocaleString('en-US', {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2
                        });
                    }
                    return total;
                }
                return 0;
            }

            // Handle service checkbox changes
            document.addEventListener('change', function(e) {
                const serviceId = e.target.value;
                
                if (e.target.matches('.service-checkbox')) {
                    const priceInput = document.querySelector(`.service-price[name="services[${serviceId}][price]"]`);
                    const quantityInput = document.querySelector(`.service-quantity[name="services[${serviceId}][quantity]"]`);
                    const startDateInput = document.querySelector(`.service-start-date[name="services[${serviceId}][start_date]"]`);
                    
                    if (e.target.checked) {
                        priceInput.disabled = false;
                        quantityInput.disabled = false;
                        startDateInput.disabled = false;
                        // Set initial quantity to 1 if not set
                        if (!quantityInput.value) quantityInput.value = '1';
                        calculateTotal(serviceId); // Calculate initial total
                    } else {
                        priceInput.disabled = true;
                        quantityInput.disabled = true;
                        startDateInput.disabled = true;
                    }
                }
                
                // Handle quantity or price changes
                if (e.target.matches('.service-quantity, .service-price')) {
                    calculateTotal(serviceId);
                }
            });
            
            // Handle input events for real-time updates
            document.addEventListener('input', function(e) {
                // Get the service ID from the closest parent service element
                const serviceElement = e.target.closest('[id^="service-"]');
                if (!serviceElement) return;
                
                const serviceId = serviceElement.id.replace('service-', '');
                
                if (e.target.matches('.service-quantity, .service-price')) {
                    calculateTotal(serviceId);
                }
            });
            
            // Also handle change events for number inputs (for spinner clicks)
            document.addEventListener('change', function(e) {
                if (e.target.matches('.service-quantity, .service-price')) {
                    const serviceElement = e.target.closest('[id^="service-"]');
                    if (!serviceElement) return;
                    
                    const serviceId = serviceElement.id.replace('service-', '');
                    calculateTotal(serviceId);
                }
            });
            
            // Handle form submission
            const form = document.querySelector('form');
            if (form) {
                form.addEventListener('submit', function(e) {
                    const checkboxes = document.querySelectorAll('.service-checkbox:checked');
                    checkboxes.forEach(checkbox => {
                        const serviceId = checkbox.value;
                        const priceInput = document.querySelector(`.service-price[name="services[${serviceId}][price]"]`);
                        const quantityInput = document.querySelector(`.service-quantity[name="services[${serviceId}][quantity]"]`);
                        const startDateInput = document.querySelector(`.service-start-date[name="services[${serviceId}][start_date]"]`);
                        
                        // Ensure required fields are set for checked services
                        if (!priceInput.value) {
                            priceInput.value = checkbox.dataset.price || '0';
                        }
                        
                        if (!quantityInput.value || quantityInput.value < 1) {
                            quantityInput.value = '1';
                        }
                        
                        if (!startDateInput.value) {
                            startDateInput.value = new Date().toISOString().split('T')[0];
                        }
                        
                        // Recalculate total before submission
                        calculateTotal(serviceId);
                    });
                });
            }
        });

        
        // Auto-format phone number
        document.getElementById('TelNo').addEventListener('input', function(e) {
            let value = e.target.value.replace(/\D/g, '');
            
            // Format as 07XX XXX XXX or 01XX XXX XXX
            if (value.length > 3 && value.length <= 6) {
                value = value.replace(/(\d{4})(\d+)/, '$1 $2');
            } else if (value.length > 6) {
                value = value.replace(/(\d{4})(\d{3})(\d+)/, '$1 $2 $3');
            }
            
            e.target.value = value;
        });
        
        // Set deposit date to today if deposit amount is entered
        document.getElementById('Deposit').addEventListener('change', function(e) {
            const depositDate = document.getElementById('DepositDate');
            if (e.target.value && !depositDate.value) {
                depositDate.value = new Date().toISOString().split('T')[0];
            }
        });

        // Handle unit selection change
        document.getElementById('UnitID').addEventListener('change', function() {
            const unitId = this.value;
            const wMeterNoField = document.getElementById('WMeterNo');
            const eMeterNoField = document.getElementById('EMeterNo');
            const meterInfoSection = document.getElementById('meterInformationSection');
            console.log(unitId)
            if (!unitId) {
                // Hide meter information and clear fields if no unit is selected
                meterInfoSection.classList.add('hidden');
                resetMeterFields();
                return;
            }
            
            // Show meter information when a unit is selected
            meterInfoSection.classList.remove('hidden');

            // Show loading state
            const unitSelect = this;
            const originalValue = unitSelect.innerHTML;
            unitSelect.disabled = true;
            
            // Add loading class to the select
            unitSelect.classList.add('opacity-75', 'cursor-not-allowed');
            
            // Fetch unit details
            fetch(`/units/${unitId}/details`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        // Update meter fields with unit details and make meter numbers read-only
                        wMeterNoField.value = data.data.WMeterNo || '';
                        wMeterNoField.readOnly = true;
                        
                        document.getElementById('WInitialReading').value = data.data.WLastReading || '0.000';
                        
                        eMeterNoField.value = data.data.EMeterNo || '';
                        eMeterNoField.readOnly = true;
                        
                        document.getElementById('EInitialReading').value = data.data.ELastReading || '0.00';
                    } else {
                        resetMeterFields();
                        showToast('error', 'Failed to load unit details');
                    }
                })
                .catch(error => {
                    console.error('Error fetching unit details:', error);
                    resetMeterFields();
                    showToast('error', 'Error loading unit details. Please try again.');
                })
                .finally(() => {
                    // Reset select element
                    unitSelect.disabled = false;
                    unitSelect.classList.remove('opacity-75', 'cursor-not-allowed');
                });
        });

        function resetMeterFields() {
            document.getElementById('WMeterNo').value = '';
            document.getElementById('WInitialReading').value = '0.000';
            document.getElementById('EMeterNo').value = '';
            document.getElementById('EInitialReading').value = '0.00';
            
            // Make meter number fields editable when no unit is selected
            document.getElementById('WMeterNo').readOnly = false;
            document.getElementById('EMeterNo').readOnly = false;
        }

        function showToast(type, message) {
            // You can implement a toast notification here if you have one
            // For now, we'll just use alert
            alert(message);
        }
    </script>
    @endpush
@endsection
