@extends('layouts.app')

@section('content')
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <h1>Add New Meter Reading</h1>
                <div>
                    <a href="{{ route('meter-readings.index') }}" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left"></i> Back to List
                    </a>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <form action="{{ route('meter-readings.store') }}" method="POST" id="meterReadingForm">
                @csrf
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="CustomerID" class="form-label">Customer <span class="text-danger">*</span></label>
                            <select class="form-select select2 @error('CustomerID') is-invalid @enderror" 
                                    id="CustomerID" name="CustomerID" required>
                                <option value="">Select Customer</option>
                                @foreach($customers as $customer)
                                    <option value="{{ $customer->CustomerID }}" 
                                        {{ old('CustomerID') == $customer->CustomerID ? 'selected' : '' }}>
                                        {{ $customer->CustomerName }} ({{ $customer->CustomerID }})
                                    </option>
                                @endforeach
                            </select>
                            @error('CustomerID')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="mb-3">
                            <label for="UnitID" class="form-label">Unit <span class="text-danger">*</span></label>
                            <select class="form-select select2 @error('UnitID') is-invalid @enderror" 
                                    id="UnitID" name="UnitID" required>
                                <option value="">Select Unit</option>
                                @foreach($units as $unit)
                                    <option value="{{ $unit->UnitID }}" 
                                        data-property="{{ $unit->property->PropertyName ?? 'N/A' }}"
                                        {{ old('UnitID') == $unit->UnitID ? 'selected' : '' }}>
                                        {{ $unit->UnitNumber }} - {{ $unit->property->PropertyName ?? 'N/A' }}
                                    </option>
                                @endforeach
                            </select>
                            <small id="unitProperty" class="form-text text-muted"></small>
                            @error('UnitID')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="BillingPeriod" class="form-label">Billing Period <span class="text-danger">*</span></label>
                            <input type="text" class="form-control @error('BillingPeriod') is-invalid @enderror" 
                                   id="BillingPeriod" name="BillingPeriod" 
                                   value="{{ old('BillingPeriod', date('Y-m')) }}" required>
                            @error('BillingPeriod')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="ConsType" class="form-label">Consumption Type <span class="text-danger">*</span></label>
                            <select class="form-select @error('ConsType') is-invalid @enderror" 
                                    id="ConsType" name="ConsType" required>
                                <option value="">Select Type</option>
                                @foreach($consumptionTypes as $type)
                                    <option value="{{ $type->tID }}" 
                                        {{ old('ConsType') == $type->tID ? 'selected' : '' }}>
                                        {{ $type->tName }} ({{ $type->tID }})
                                    </option>
                                @endforeach
                            </select>
                            @error('ConsType')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="ReadingDate" class="form-label">Reading Date <span class="text-danger">*</span></label>
                            <input type="date" class="form-control @error('ReadingDate') is-invalid @enderror" 
                                   id="ReadingDate" name="ReadingDate" 
                                   value="{{ old('ReadingDate', date('Y-m-d')) }}" required>
                            @error('ReadingDate')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="MeterNo" class="form-label">Meter Number</label>
                            <input type="text" class="form-control @error('MeterNo') is-invalid @enderror" 
                                   id="MeterNo" name="MeterNo" 
                                   value="{{ old('MeterNo') }}">
                            @error('MeterNo')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="Reading" class="form-label">Current Reading <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <input type="number" step="0.01" 
                                       class="form-control @error('Reading') is-invalid @enderror" 
                                       id="Reading" name="Reading" 
                                       value="{{ old('Reading') }}" required>
                                <span class="input-group-text" id="unitOfMeasure">units</span>
                                @error('Reading')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="mb-3">
                            <label for="BaseOfBilling" class="form-label">Basis of Billing</label>
                            <select class="form-select @error('BaseOfBilling') is-invalid @enderror" 
                                    id="BaseOfBilling" name="BaseOfBilling">
                                <option value="Actual" {{ old('BaseOfBilling') == 'Actual' ? 'selected' : '' }}>Actual Reading</option>
                                <option value="Estimated" {{ old('BaseOfBilling') == 'Estimated' ? 'selected' : '' }}>Estimated</option>
                                <option value="Average" {{ old('BaseOfBilling') == 'Average' ? 'selected' : '' }}>Average</option>
                                <option value="Flat Rate" {{ old('BaseOfBilling') == 'Flat Rate' ? 'selected' : '' }}>Flat Rate</option>
                            </select>
                            @error('BaseOfBilling')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-12">
                        <div class="mb-3">
                            <label for="ReadingComments" class="form-label">Comments</label>
                            <textarea class="form-control @error('ReadingComments') is-invalid @enderror" 
                                      id="ReadingComments" name="ReadingComments" 
                                      rows="3">{{ old('ReadingComments') }}</textarea>
                            @error('ReadingComments')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                </div>
                
                <!-- Hidden fields -->
                <input type="hidden" name="CompanyID" id="CompanyID" value="{{ auth()->user()->CompanyID ?? 1 }}">
                
                <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
                    <button type="reset" class="btn btn-outline-secondary me-md-2">
                        <i class="fas fa-undo"></i> Reset
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Save Reading
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Previous Readings Card -->
    <div class="card mt-4" id="previousReadingsCard" style="display: none;">
        <div class="card-header bg-light">
            <h5 class="mb-0">Previous Readings</h5>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-sm table-hover mb-0" id="previousReadingsTable">
                    <thead class="table-light">
                        <tr>
                            <th>Date</th>
                            <th>Reading</th>
                            <th>Consumption</th>
                            <th>Basis</th>
                            <th>Comments</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Will be populated by JavaScript -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    .select2-container--default .select2-selection--single {
        height: 38px;
        padding: 5px 0;
        border: 1px solid #ced4da;
    }
    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 36px;
    }
</style>
@endpush

@push('scripts')
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    // Initialize Select2
    $('.select2').select2({
        width: '100%',
        placeholder: 'Select an option',
        allowClear: true
    });
    
    // Show property info when unit is selected
    $('#UnitID').on('change', function() {
        const selectedOption = $(this).find('option:selected');
        const propertyName = selectedOption.data('property');
        $('#unitProperty').text(propertyName);
        
        // Load previous readings when unit is selected
        loadPreviousReadings();
    });
    
    // Handle consumption type change
    $('#ConsType').on('change', function() {
        // You can add logic here to update the unit of measure based on the consumption type
        // For now, we'll just update the placeholder text
        const typeText = $(this).find('option:selected').text();
        $('#unitOfMeasure').text(typeText.toLowerCase().includes('water') ? 'm³' : 'kWh');
        
        // Reload previous readings if unit is already selected
        if ($('#UnitID').val()) {
            loadPreviousReadings();
        }
    });
    
    // Function to load previous readings
    function loadPreviousReadings() {
        const unitId = $('#UnitID').val();
        const consType = $('#ConsType').val();
        
        if (!unitId || !consType) {
            return;
        }
        
        $.ajax({
            url: '{{ route("api.meter-readings.previous") }}',
            method: 'GET',
            data: {
                unit_id: unitId,
                cons_type: consType,
                limit: 5
            },
            success: function(response) {
                const tbody = $('#previousReadingsTable tbody');
                tbody.empty();
                
                if (response.data && response.data.length > 0) {
                    response.data.forEach(function(reading) {
                        tbody.append(`
                            <tr>
                                <td>${reading.reading_date_formatted}</td>
                                <td>${parseFloat(reading.reading).toLocaleString()}</td>
                                <td>${reading.consumption ? parseFloat(reading.consumption).toLocaleString() : 'N/A'}</td>
                                <td>${reading.base_of_billing || 'Actual'}</td>
                                <td>${reading.reading_comments || ''}</td>
                            </tr>
                        `);
                    });
                    
                    // Show the previous readings card
                    $('#previousReadingsCard').show();
                    
                    // If there's a previous reading, update the previous reading fields
                    const lastReading = response.data[0];
                    if (lastReading) {
                        // You can use this data to pre-fill or calculate fields if needed
                        console.log('Last reading:', lastReading);
                    }
                } else {
                    tbody.append('<tr><td colspan="5" class="text-center">No previous readings found</td></tr>');
                    $('#previousReadingsCard').show();
                }
            },
            error: function(xhr) {
                console.error('Error loading previous readings:', xhr);
            }
        });
    }
    
    // Form submission handling
    $('#meterReadingForm').on('submit', function(e) {
        // You can add any client-side validation here
        // For example, checking if current reading is greater than previous reading
        
        // Show loading state
        const submitBtn = $(this).find('button[type="submit"]');
        submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...');
    });
});
</script>
@endpush
@endsection
