@extends('layouts.app')

@section('content')
<div class="container-fluid py-4">
    <!-- Page Header with Tabs -->
    <div class="page-header mb-0">
        <div class="d-flex flex-column">
            <!-- Header Section with Title and Button -->
            <div class="d-flex justify-content-between align-items-start mb-0">
                <div class="d-flex align-items-center">
                    <div class="me-3">
                        <div class="icon-shape icon-lg bg-gradient-primary bg-opacity-10 text-primary rounded-3">
                            <i class="fas fa-tachometer-alt fa-2x"></i>
                        </div>
                    </div>
                    <div>
                        <h1 class="mb-0">Meter Readings</h1>
                        <p class="text-muted mb-0">Manage and track utility meter readings</p>
                    </div>
                </div>
                <div>
                     <!-- Tabs Navigation -->
            <div class="w-100">
                <div class="card border-4 border-top border-warning">
                    <div class="card-body p-0">
                        <ul class="nav nav-tabs nav-fill w-100" id="meterReadingsTabs" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active d-flex align-items-center justify-content-center py-3" 
                                        id="unprocessed-tab" 
                                        data-bs-toggle="tab" 
                                        data-bs-target="#unprocessed-content" 
                                        type="button" 
                                        role="tab" 
                                        aria-controls="unprocessed" 
                                        aria-selected="true">
                                    <i class="fas fa-clock me-2"></i> 
                                    <span class="text-warning">Unprocessed Readings</span>
                                    <span class="badge bg-warning ms-2" id="unprocessed-count">0</span>
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link d-flex align-items-center justify-content-center py-3" 
                                        id="processed-tab" 
                                        data-bs-toggle="tab" 
                                        data-bs-target="#processed-content" 
                                        type="button" 
                                        role="tab" 
                                        aria-controls="processed" 
                                        aria-selected="false">
                                    <i class="fas fa-history me-2"></i> 
                                    <span class="text-primary">Processed History</span>
                                    <span class="badge bg-info ms-2">{{ $readings->total() }}</span>
                                </button>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
                </div>
                <!-- <div class="flex-shrink-0">
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addReadingModal">
                        <i class="fas fa-plus me-2"></i>New Reading
                    </button>
                </div> -->
            </div>
            
           
        </div>
    </div>

    <!-- Filters -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <form id="filterForm" class="row g-3" method="GET">
                <div class="col-md-2">
                    <label for="type" class="form-label">Consumption Type</label>
                    <select class="form-select" id="type" name="type">
                        <option value="">All Types</option>
                        @foreach($consumptionTypes as $type)
                            <option value="{{ $type }}" {{ request('type') == $type ? 'selected' : '' }}>
                                {{ $type }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="property_id" class="form-label">Property</label>
                    <select class="form-select" id="property_id" name="property_id">
                        <option value="">All Properties</option>
                        @foreach($properties as $propId => $propName)
                            <option value="{{ $propId }}" {{ request('property_id') == $propId ? 'selected' : '' }}>
                                {{ $propName }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label for="billing_period" class="form-label">Billing Period</label>
                    <select class="form-select" id="billing_period" name="billing_period">
                        @php
                            // Convert collections to arrays for JavaScript
                            $processedPeriods = $processedBillingPeriods->toArray();
                            $unprocessedPeriods = $unprocessedBillingPeriods->toArray();
                        @endphp
                        @foreach($billingPeriods as $period)
                            <option value="{{ $period }}" 
                                    data-processed="{{ in_array($period, $processedPeriods) ? '1' : '0' }}"
                                    data-unprocessed="{{ in_array($period, $unprocessedPeriods) ? '1' : '0' }}"
                                    {{ $currentBillingPeriod == $period ? 'selected' : '' }}>
                                {{ \Carbon\Carbon::createFromFormat('Ym', $period)->format('M Y') }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <a href="{{ route('meter-readings.index') }}" class="btn btn-outline-secondary w-100">
                        <i class="fas fa-undo me-1"></i> Reset
                    </a>
                </div>
                <div class="col-md-4">
                    <label for="searchInput" class="form-label">&nbsp;</label>
                    <div class="input-group">
                        <input type="text" 
                               class="form-control" 
                               id="searchInput" 
                               name="search"
                               value="{{ request('search') }}"
                               placeholder="Search by customer or account..." 
                               aria-label="Search">
                        <button class="btn btn-outline-secondary" type="submit">
                            <i class="fas fa-search"></i>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Tab Content -->
    <div class="tab-content" id="meterReadingsTabContent">
        <!-- Unprocessed Readings Tab -->
        <div class="tab-pane fade show active" id="unprocessed-content" role="tabpanel" aria-labelledby="unprocessed-tab">
            <div class="card border-4 shadow-sm border-top border-warning">
                <div class="card-header bg-light border-bottom-0 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 text-warning">
                        Unprocessed Readings
                        @if(request('property_id'))
                            @php
                                $selectedProperty = \App\Models\Property::find(request('property_id'));
                            @endphp
                            @if($selectedProperty)
                                For {{ $selectedProperty->PropName }}
                            @endif
                        @endif
                    </h5>
                    <button type="button" class="btn btn-success btn-sm" onclick="exportUnprocessedReadings()">
                        <i class="fas fa-file-excel me-1"></i>Export to Excel
                    </button>
                </div>
                <div class="card-body p-0 ">
                    <div class="table-responsive ">
                        <table class="table table-hover align-middle mb-0 ">
                            <thead class="bg-gradient-primary text-white">
                                <tr>
                                    <th>Date</th>
                                    <th>Customer</th>
                                    <th>Account No</th>
                                    <th class="text-end">Reading</th>
                                    <th class="text-end">Consumption</th>
                                    <th>Type</th>
                                    <th class="text-center">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="unprocessed-readings-body">
                                <!-- Will be populated by JavaScript -->
                                <tr>
                                    <td colspan="8" class="text-center py-4">
                                        <div class="spinner-border text-primary" style="width: 2rem; height: 2rem;" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                        <p class="mt-2 mb-0">Loading unprocessed readings...</p>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Pagination for unprocessed readings -->
                    <div id="unprocessed-pagination" class="card-footer bg-light" style="display: none;">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="text-muted small">
                                Showing <span id="unprocessed-from">1</span> to <span id="unprocessed-to">10</span> of <span id="unprocessed-total">0</span> entries
                            </div>
                            <div id="unprocessed-pagination-links">
                                <!-- Pagination links will be inserted here -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Processed History Tab -->
        <div class="tab-pane fade" id="processed-content" role="tabpanel" aria-labelledby="processed-tab">
                <div class="card border-4 shadow-sm border-top border-warning">
                    <div class="card-header bg-light border-bottom-0 d-flex justify-content-between align-items-center">
                        <h5 class="mb-0 text-primary">
                            Processed History
                            @if(request('property_id'))
                                @php
                                    $selectedProperty = \App\Models\Property::find(request('property_id'));
                                @endphp
                                @if($selectedProperty)
                                    For {{ $selectedProperty->PropName }}
                                @endif
                            @endif
                        </h5>
                        <button type="button" class="btn btn-success btn-sm" onclick="exportProcessedReadings()">
                            <i class="fas fa-file-excel me-1"></i>Export to Excel
                        </button>
                    </div>
                <div class="card-body p-0 ">
                    <div class="table-responsive ">
                        <table class="table table-hover align-middle mb-0 ">
                            <thead class="bg-gradient-primary text-white">
                                <tr>
                            <th>Date</th>
                            <th>Customer</th>
                            <th>Account No</th>
                            <th class="text-end">Reading</th>
                            <th class="text-end">Consumption</th>
                            <th>Type</th>
                            <th class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($readings as $reading)
                            <tr class="{{ $reading->ConsType == 'Electricity' ? 'bg-light' : 'bg-white' }} border-bottom">
                                <td class="text-nowrap">
                                    <span class="d-block">{{ \Carbon\Carbon::parse($reading->ReadingDate)->format('M d, Y') }}</span>
                                    <small class="text-muted">{{ \Carbon\Carbon::parse($reading->ReadingDate)->diffForHumans() }}</small>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="avatar-sm bg-light rounded-circle me-2 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                            <i class="fas fa-user text-primary"></i>
                                        </div>
                                        <div>
                                            <div class="fw-medium">{{ $reading->customer->CustomerName ?? 'N/A' }}</div>
                                            <small class="text-muted">Unit {{ $reading->unit->UnitIdentity ?? 'N/A' }}</small>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="text-muted">{{ $reading->customer->AccountNo ?? 'N/A' }}</span>
                                        </div>
                                    </div>
                                </td>
                                
                                <td class="text-end">
                                    <div class="fw-bold">{{ number_format($reading->Reading) }}</div>
                                    @if($reading->PrvReading)
                                        <div class="small text-muted">Prev: {{ number_format($reading->PrvReading) }}</div>
                                    @endif
                                </td>
                                <td class="text-end">
                                    <span class="badge bg-{{ $reading->Consumption > 0 ? 'success' : 'secondary' }}">
                                        {{ number_format($reading->Consumption) }}
                                    </span>
                                </td>
                                <td>
                                    <span class="badge bg-{{ $reading->ConsType == 'Electricity' ? 'info' : 'primary' }} px-3 py-2">
                                        <i class="fas fa-{{ $reading->ConsType == 'Electricity' ? 'bolt' : 'water' }} me-1"></i>
                                        {{ $reading->ConsType }}
                                    </span>
                                </td>
                                <td class="text-center">
                                    <a href="{{ route('meter-readings.show', $reading->MeterReadingID) }}" 
                                       class="btn btn-sm btn-outline-primary me-1" 
                                       data-bs-toggle="tooltip" 
                                       title="View details">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <button class="btn btn-sm btn-outline-warning edit-reading" 
                                            data-bs-toggle="modal" 
                                            data-bs-target="#editReadingModal"
                                            data-id="{{ $reading->MeterReadingID }}"
                                            data-current-reading="{{ $reading->Reading }}"
                                            data-previous-reading="{{ $reading->PrvReading }}"
                                            data-consumption-type="{{ $reading->ConsType }}"
                                            title="Edit reading">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="8" class="text-center py-4">
                                    <div class="text-muted">
                                        <div class="icon-shape icon-lg bg-gradient-primary bg-opacity-10 text-primary rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 64px; height: 64px;">
                                        <i class="fas fa-inbox fa-2x"></i>
                                    </div>
                                        <p class="mb-0">No meter readings found</p>
                                    </div>
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                        </table>
                    </div>
                    
                    @if($readings->hasPages())
                        <div class="card-footer bg-light">
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="text-muted small">
                                    Showing {{ $readings->firstItem() }} to {{ $readings->lastItem() }} of {{ $readings->total() }} entries
                                </div>
                                <div>
                                    {{ $readings->withQueryString()->links() }}
                                </div>
                            </div>
                        </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
    </div>
</div>


@push('styles')
<style>
    /* Main color scheme from logo */
    :root {
        --sulis-blue: #0033a0;
        --sulis-yellow: #ffcc00;
        --sulis-dark: #212529;
        --sulis-light: #f8f9fa;
    }
    
    /* Header and Navigation */
    .card {
        border: none;
        border-radius: 8px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        margin-bottom: 1.5rem;
    }
    
    .card-header {
        background-color: var(--sulis-blue);
        color: white;
        border-bottom: none;
        padding: 1rem 1.5rem;
        border-radius: 8px 8px 0 0 !important;
    }
    
    .nav-tabs {
        border-bottom: 2px solid #dee2e6;
    }
    
    .nav-tabs .nav-link {
        border: none;
        color: #6c757d;
        font-weight: 500;
        padding: 0.75rem 1.25rem;
        transition: all 0.3s ease;
    }
    
    .nav-tabs .nav-link.active {
        color: var(--sulis-blue);
        background-color: transparent;
        border: none;
        border-bottom: 3px solid var(--sulis-yellow);
        font-weight: 600;
    }
    
    .nav-tabs .nav-link:hover:not(.active) {
        color: var(--sulis-blue);
        background-color: rgba(0, 51, 160, 0.05);
    }
    
    /* Buttons */
    .btn-primary {
        background-color: var(--sulis-blue);
        border-color: var(--sulis-blue);
    }
    
    .btn-primary:hover, .btn-primary:focus {
        background-color: #00257a;
        border-color: #00257a;
    }
    
    .btn-outline-primary {
        color: var(--sulis-blue);
        border-color: var(--sulis-blue);
    }
    
    .btn-outline-primary:hover, .btn-outline-primary:focus {
        background-color: var(--sulis-blue);
        border-color: var(--sulis-blue);
    }
    
    /* Table Styling */
    .table {
        margin-bottom: 0;
    }
    
    .table thead th {
        background-color: var(--sulis-blue);
        color: white;
        border: none;
        font-weight: 500;
        padding: 0.75rem 1rem;
    }
    
    .table tbody tr {
        transition: background-color 0.2s ease;
    }
    
    .table tbody tr:hover {
        background-color: rgba(0, 51, 160, 0.05);
    }
    
    .table-hover > tbody > tr:hover > * {
        --bs-table-accent-bg: rgba(0, 51, 160, 0.05);
    }
    
    /* Badges */
    .badge {
        font-weight: 500;
        padding: 0.4em 0.6em;
    }
    
    .bg-warning {
        background-color: var(--sulis-yellow) !important;
        color: var(--sulis-dark);
    }
    
    .bg-info {
        background-color: var(--sulis-blue) !important;
        color: white;
    }
    
    /* Form Controls */
    .form-control:focus, .form-select:focus {
        border-color: var(--sulis-yellow);
        box-shadow: 0 0 0 0.25rem rgba(255, 204, 0, 0.25);
    }
    
    /* Custom Scrollbar */
    ::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }
    
    ::-webkit-scrollbar-track {
        background: #f1f1f1;
    }
    
    ::-webkit-scrollbar-thumb {
        background: var(--sulis-blue);
        border-radius: 4px;
    }
    
    ::-webkit-scrollbar-thumb:hover {
        background: #00257a;
    }
    
    /* Responsive adjustments */
    @media (max-width: 768px) {
        .table-responsive {
            border-radius: 0.5rem;
            border: 1px solid #dee2e6;
        }
        
        .nav-tabs .nav-link {
            padding: 0.5rem 0.75rem;
            font-size: 0.875rem;
        }
    }
    .table th { font-weight: 600; }
    .table > :not(caption) > * > * { padding: 0.75rem 0.75rem; }
    .badge { font-weight: 500; padding: 0.35em 0.65em; }
    .avatar-sm { width: 36px; height: 36px; }
    .progress { height: 6px; border-radius: 3px; }
    .btn-sm { padding: 0.25rem 0.5rem; font-size: 0.75rem; }
</style>
@endpush

<!-- Edit Reading Modal -->
<div class="modal fade" id="editReadingModal" tabindex="-1" aria-labelledby="editReadingModalLabel" role="dialog" aria-modal="true" inert>
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-light">
                <h5 class="modal-title" id="editReadingModalLabel">Edit Meter Reading</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="editReadingForm" method="POST" action="">
                @csrf
                @method('PUT')
                <div class="modal-body">
                    <input type="hidden" name="reading_id" id="reading_id">
                    
                    <div class="mb-3">
                        <label for="previous_reading" class="form-label">Previous Reading</label>
                        <input type="number" step="0.01" class="form-control" id="previous_reading" name="previous_reading" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="current_reading" class="form-label">Current Reading</label>
                        <input type="number" step="0.01" class="form-control" id="current_reading" name="current_reading" required>
                        <div class="form-text">Consumption: <span id="consumption_calc">0</span> units</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Changes</button>
                </div>
                <div class="visually-hidden" aria-live="polite" id="editModalStatus"></div>
            </form>
        </div>
    </div>
</div>

@push('scripts')
<script>
    // Form submission handler
    function handleFilterSubmit(e) {
        e.preventDefault();
        const form = e.target;
        const formData = new FormData(form);
        const params = new URLSearchParams();
        
        // Add all form data to params
        for (let [key, value] of formData.entries()) {
            if (value) params.set(key, value);
        }
        
        // Get active tab
        const activeTab = document.querySelector('.nav-tabs .nav-link.active').id.replace('-tab', '');
        params.set('active_tab', activeTab);
        
        // Update URL and reload
        window.location.href = `${window.location.pathname}?${params.toString()}`;
    }
    
    // Initialize form and tab handling
    document.addEventListener('DOMContentLoaded', function() {
        const filterForm = document.getElementById('filterForm');
        
        if (filterForm) {
            filterForm.addEventListener('submit', handleFilterSubmit);
        }
        
        // Handle tab changes to update the form's active_tab
        const tabLinks = document.querySelectorAll('.nav-tabs .nav-link');
        tabLinks.forEach(link => {
            link.addEventListener('click', function() {
                const activeTab = this.id.replace('-tab', '');
                document.querySelector('input[name="active_tab"]')?.remove();
                
                const hiddenInput = document.createElement('input');
                hiddenInput.type = 'hidden';
                hiddenInput.name = 'active_tab';
                hiddenInput.value = activeTab;
                filterForm.appendChild(hiddenInput);
            });
        });
    });

// Helper functions
function formatDate(dateString) {
    if (!dateString) return 'N/A';
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}

function timeAgo(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    const now = new Date();
    const seconds = Math.floor((now - date) / 1000);
    
    let interval = Math.floor(seconds / 31536000);
    if (interval >= 1) return interval + ' year' + (interval === 1 ? '' : 's') + ' ago';
    
    interval = Math.floor(seconds / 2592000);
    if (interval >= 1) return interval + ' month' + (interval === 1 ? '' : 's') + ' ago';
    
    interval = Math.floor(seconds / 86400);
    if (interval >= 1) return interval + ' day' + (interval === 1 ? '' : 's') + ' ago';
    
    interval = Math.floor(seconds / 3600);
    if (interval >= 1) return interval + ' hour' + (interval === 1 ? '' : 's') + ' ago';
    
    interval = Math.floor(seconds / 60);
    if (interval >= 1) return interval + ' minute' + (interval === 1 ? '' : 's') + ' ago';
    
    return 'just now';
}

function formatNumber(num) {
    if (num === null || num === undefined) return '0';
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

// Export functions
function exportProcessedReadings() {
    const billingPeriod = $('#billing_period').val() || '';
    const type = $('#type').val() || '';
    const propertyId = $('#property_id').val() || '';
    const search = $('#searchInput').val() || '';
    
    let url = '{{ route("meter-readings.export.processed") }}';
    const params = new URLSearchParams();
    
    if (billingPeriod) params.set('billing_period', billingPeriod);
    if (type) params.set('type', type);
    if (propertyId) params.set('property_id', propertyId);
    if (search) params.set('search', search);
    
    if (params.toString()) {
        url += '?' + params.toString();
    }
    
    window.location.href = url;
}

function exportUnprocessedReadings() {
    const billingPeriod = $('#billing_period').val() || '';
    const type = $('#type').val() || '';
    const propertyId = $('#property_id').val() || '';
    const search = $('#searchInput').val() || '';
    
    let url = '{{ route("meter-readings.export.unprocessed") }}';
    const params = new URLSearchParams();
    
    if (billingPeriod) params.set('billing_period', billingPeriod);
    if (type) params.set('type', type);
    if (propertyId) params.set('property_id', propertyId);
    if (search) params.set('search', search);
    
    if (params.toString()) {
        url += '?' + params.toString();
    }
    
    window.location.href = url;
}

// Generate pagination links
function generatePaginationLinks(pagination, currentPage) {
    let links = '';
    
    // Previous button
    if (pagination.current_page > 1) {
        links += `<li class="page-item"><a class="page-link" href="#" onclick="loadUnprocessedReadings(${pagination.current_page - 1}); return false;">Previous</a></li>`;
    } else {
        links += `<li class="page-item disabled"><span class="page-link">Previous</span></li>`;
    }
    
    // Page numbers
    for (let i = Math.max(1, pagination.current_page - 2); i <= Math.min(pagination.last_page, pagination.current_page + 2); i++) {
        if (i === pagination.current_page) {
            links += `<li class="page-item active"><span class="page-link">${i}</span></li>`;
        } else {
            links += `<li class="page-item"><a class="page-link" href="#" onclick="loadUnprocessedReadings(${i}); return false;">${i}</a></li>`;
        }
    }
    
    // Next button
    if (pagination.current_page < pagination.last_page) {
        links += `<li class="page-item"><a class="page-link" href="#" onclick="loadUnprocessedReadings(${pagination.current_page + 1}); return false;">Next</a></li>`;
    } else {
        links += `<li class="page-item disabled"><span class="page-link">Next</span></li>`;
    }
    
    return `<ul class="pagination pagination-sm mb-0">${links}</ul>`;
}

// Function to load unprocessed readings
function loadUnprocessedReadings(page = 1) {
    console.log('Loading unprocessed readings...', { page });
    const loadingRow = `
        <tr>
            <td colspan="8" class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2 mb-0">Loading unprocessed readings...</p>
            </td>
        </tr>`;

    // Show loading state
    $('#unprocessed-readings-table tbody').html(loadingRow);

    // Get the current search term
    const searchTerm = $('#searchInput').val() || '';
    
    // Get the current filters
    const billingPeriod = $('#billing_period').val() || '';
    const type = $('#type').val() || '';
    const propertyId = $('#property_id').val() || '';

    // Make AJAX request to get unprocessed readings
    $.ajax({
        url: '{{ route("meter-readings.api.unprocessed") }}',
        type: 'GET',
        data: {
            search: searchTerm,
            billing_period: billingPeriod,
            type: type,
            property_id: propertyId,
            page: page,
            per_page: 10
        },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(response) {
            console.log('Unprocessed readings loaded:', response);
            
            const tbody = $('#unprocessed-readings-body');
            tbody.empty();
            
            if (response.success && response.data && response.data.length > 0) {
                response.data.forEach(function(reading) {
                    tbody.append(`
                        <tr class="${reading.cons_type === 'Electricity' ? 'table-info' : 'table-light'}">
                            <td class="text-nowrap">
                                <span class="d-block">${reading.reading_date ? formatDate(reading.reading_date) : 'N/A'}</span>
                                <small class="text-muted">${reading.reading_date ? timeAgo(reading.reading_date) : ''}</small>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="avatar-sm bg-light rounded-circle me-2 d-flex align-items-center justify-content-center" style="width: 30px; height: 30px;">
                                        <i class="fas fa-user text-primary"></i>
                                    </div>
                                    <div>
                                        <div class="fw-medium">${reading.customer || 'N/A'}</div>
                                        <small class="text-muted">Unit ${reading.unit || 'N/A'}</small>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="text-muted">${reading.account_no || 'N/A'}</span>
                            </td>
                            <td class="text-end">
                                <div class="fw-bold">${reading.reading ? formatNumber(reading.reading) : '0'}</div>
                                ${reading.previous_reading ? `<div class="small text-muted">Prev: ${formatNumber(reading.previous_reading)}</div>` : ''}
                            </td>
                            <td class="text-end">
                                <span class="badge bg-${reading.consumption > 0 ? 'success' : 'secondary'}">
                                    ${formatNumber(reading.consumption || 0)}
                                </span>
                            </td>
                            <td>${reading.cons_type || 'N/A'}</td>
                            <td class="text-center">
                                <a href="/meter-readings/${reading.id}" 
                                   class="btn btn-sm btn-outline-primary me-1" 
                                   data-bs-toggle="tooltip" 
                                   title="View details">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <button class="btn btn-sm btn-outline-warning edit-reading" 
                                        data-bs-toggle="modal" 
                                        data-bs-target="#editReadingModal"
                                        data-id="${reading.id}"
                                        data-current-reading="${reading.reading || ''}"
                                        data-previous-reading="${reading.previous_reading || ''}"
                                        data-consumption-type="${reading.cons_type || ''}"
                                        title="Edit reading">
                                    <i class="fas fa-edit"></i>
                                </button>
                               
                            </td>
                        </tr>
                    `);
                });
                
                // Update the unprocessed count badge
                $('#unprocessed-count').text(response.pagination.total);
                
                // Show and update pagination
                if (response.pagination.has_pages) {
                    $('#unprocessed-pagination').show();
                    $('#unprocessed-from').text(response.pagination.from || 1);
                    $('#unprocessed-to').text(response.pagination.to || response.data.length);
                    $('#unprocessed-total').text(response.pagination.total);
                    
                    // Generate pagination links
                    const paginationLinks = generatePaginationLinks(response.pagination, page);
                    $('#unprocessed-pagination-links').html(paginationLinks);
                } else {
                    $('#unprocessed-pagination').hide();
                }
            } else {
                tbody.append(`
                    <tr>
                        <td colspan="7" class="text-center py-4 text-muted">
                            <i class="fas fa-inbox fa-2x mb-2 d-block"></i>
                            ${response.message || 'No unprocessed meter readings found'}
                        </td>
                    </tr>
                `);
                $('#unprocessed-count').text('0');
                $('#unprocessed-pagination').hide();
            }
        },
        error: function(xhr, status, error) {
            console.error('Error loading unprocessed readings:', {
                status: xhr.status,
                statusText: xhr.statusText,
                responseText: xhr.responseText,
                error: error
            });
            
            let errorMessage = 'Failed to load unprocessed readings. ';
            if (xhr.responseJSON && xhr.responseJSON.message) {
                errorMessage += xhr.responseJSON.message;
            } else {
                errorMessage += 'Please try again.';
            }
            
            const tbody = $('#unprocessed-readings-body');
            tbody.html(`
                <tr>
                    <td colspan="8" class="text-center text-danger py-4">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        ${errorMessage}
                    </td>
                </tr>
            `);
            $('#unprocessed-pagination').hide();
        }
    });
}

function updateBillingPeriods(activeTab) {
    const billingPeriodSelect = document.getElementById('billing_period');
    const options = billingPeriodSelect.querySelectorAll('option');
    
    // Show/hide options based on the active tab
    options.forEach(option => {
        if (option.value === '') {
            option.style.display = '';
            return;
        }
        
        if (activeTab === 'unprocessed') {
            option.style.display = option.dataset.unprocessed === '1' ? '' : 'none';
        } else {
            option.style.display = option.dataset.processed === '1' ? '' : 'none';
        }
    });
    
    // If the selected option is hidden, select the first visible option
    if (billingPeriodSelect.style.display === 'none') {
        const firstVisible = Array.from(options).find(opt => opt.style.display !== 'none');
        if (firstVisible) {
            billingPeriodSelect.value = firstVisible.value;
        }
    }
}

function handleFilterSubmit(event) {
    event.preventDefault();
    // Get the active tab
    const activeTab = document.querySelector('#meterReadingsTabs .nav-link.active');
    // Submit the form with the active tab as a parameter
    const form = event.target;
    const formData = new FormData(form);
    const params = new URLSearchParams(formData);
    
    // Add the active tab to the URL
    if (activeTab) {
        const tabId = activeTab.getAttribute('id');
        if (tabId) {
            const tabName = tabId.replace('-tab', '');
            params.append('active_tab', tabName);
            
            // Update billing periods when submitting the form
            updateBillingPeriods(tabName);
        }
    }
    
    // Submit the form with the updated parameters
    window.location.href = window.location.pathname + '?' + params.toString();
}

// Function to update tab headers with selected property name
function updateTabHeaders() {
    const propertySelect = document.getElementById('property_id');
    const selectedOption = propertySelect.options[propertySelect.selectedIndex];
    const propertyName = selectedOption.text;
    const propertyId = propertySelect.value;
    
    // Update unprocessed readings header
    const unprocessedHeader = document.querySelector('#unprocessed-content h5');
    if (unprocessedHeader) {
        if (propertyId && propertyName !== 'All Properties') {
            unprocessedHeader.innerHTML = '<span class="text-warning">Unprocessed Readings For ' + propertyName + '</span>';
        } else {
            unprocessedHeader.innerHTML = '<span class="text-warning">Unprocessed Readings</span>';
        }
    }
    
    // Update processed history header
    const processedHeader = document.querySelector('#processed-content h5');
    if (processedHeader) {
        if (propertyId && propertyName !== 'All Properties') {
            processedHeader.innerHTML = '<span class="text-primary">Processed History For ' + propertyName + '</span>';
        } else {
            processedHeader.innerHTML = '<span class="text-primary">Processed History</span>';
        }
    }
}

$(document).ready(function() {
    // Set the active tab from URL parameter or default to 'unprocessed'
    const urlParams = new URLSearchParams(window.location.search);
    const activeTabParam = urlParams.get('active_tab') || 'unprocessed';
    const activeTab = document.getElementById(activeTabParam + '-tab');
    if (activeTab) {
        const tab = new bootstrap.Tab(activeTab);
        tab.show();
        
        // Initialize billing periods for the active tab
        updateBillingPeriods(activeTabParam);
    }
    
    // Load unprocessed readings when the page loads
    loadUnprocessedReadings();
    
    // Initialize tab headers with current property selection
    updateTabHeaders();
    
    // Handle tab change to update URL and billing periods
    document.querySelectorAll('#meterReadingsTabs .nav-link').forEach(tab => {
        tab.addEventListener('shown.bs.tab', function (event) {
            const tabId = event.target.getAttribute('id').replace('-tab', '');
            const url = new URL(window.location);
            url.searchParams.set('active_tab', tabId);
            window.history.pushState({}, '', url);
            
            // Update billing periods when switching tabs
            updateBillingPeriods(tabId);
            
            // If on unprocessed tab, reload the unprocessed readings
            if (tabId === 'unprocessed') {
                loadUnprocessedReadings();
            }
        });
    });
    
    // Auto-submit form when filter dropdowns change (for processed tab)
    $('#type, #property_id, #billing_period').on('change', function() {
        if (!$('#unprocessed-tab').hasClass('active')) {
            // For processed tab, submit form with active tab parameter
            const activeTab = document.querySelector('#meterReadingsTabs .nav-link.active');
            const form = document.getElementById('filterForm');
            const formData = new FormData(form);
            const params = new URLSearchParams(formData);
            
            // Add the active tab to the URL
            if (activeTab) {
                const tabId = activeTab.getAttribute('id');
                if (tabId) {
                    const tabName = tabId.replace('-tab', '');
                    params.append('active_tab', tabName);
                }
            }
            
            // Submit the form with the updated parameters
            window.location.href = window.location.pathname + '?' + params.toString();
        } else {
            // For unprocessed tab, update header and reload data
            updateTabHeaders();
            loadUnprocessedReadings();
        }
    });
    
    // Handle filter form submission (remove date validation that's not needed for this form)
    $('#filterForm').on('submit', function(e) {
        // Form will submit normally
        return true;
    });
    
    // Handle tab change
    $('a[data-bs-toggle="tab"]').on('shown.bs.tab', function(e) {
        const target = $(e.target).attr('href');
        if (target === '#unprocessed-content') {
            loadUnprocessedReadings();
        }
        // The processed content is already loaded via the initial page load
    });

    // Handle modal accessibility
    const editModal = document.getElementById('editReadingModal');
    let focusedElementBeforeModal;

    // When modal is about to be shown
    editModal.addEventListener('show.bs.modal', function() {
        // Store the element that had focus before opening the modal
        focusedElementBeforeModal = document.activeElement;
        
        // Remove inert attribute when modal is shown
        editModal.removeAttribute('inert');
        
        // Set focus to the first focusable element in the modal
        const firstFocusable = editModal.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled])');
        if (firstFocusable) {
            firstFocusable.focus();
        }
    });

    // When modal is hidden
    editModal.addEventListener('hidden.bs.modal', function() {
        // Add inert attribute back when modal is hidden
        editModal.setAttribute('inert', '');
        
        // Return focus to the element that had focus before the modal was opened
        if (focusedElementBeforeModal) {
            focusedElementBeforeModal.focus();
        }
    });

    // Close modal when clicking outside
    editModal.addEventListener('click', function(e) {
        if (e.target === editModal) {
            const modal = bootstrap.Modal.getInstance(editModal);
            modal.hide();
        }
    });

    // Initialize tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // Handle edit reading modal
    $('#editReadingModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var modal = $(this);
        
        // Get data from button data attributes (using kebab-case as defined in HTML)
        var currentReading = button.data('current-reading');
        var previousReading = button.data('previous-reading') || '';
        var readingId = button.data('id');
        
        // Update modal content with the values
        modal.find('#reading_id').val(readingId);
        modal.find('#current_reading').val(currentReading || '');
        modal.find('#previous_reading').val(previousReading || '');
        
        // Update form action URL
        modal.find('form').attr('action', '/meter-readings/' + readingId);
        
        // Set focus to the first input when modal is shown
        modal.find('input[type="number"]').first().focus();
    });
    
    // Handle form submission
    $('#editReadingForm').on('submit', function(e) {
        e.preventDefault();
        
        var form = $(this);
        var formData = form.serialize();
        var submitBtn = form.find('button[type="submit"]');
        var originalBtnText = submitBtn.html();
        
        // Disable button and show loading state
        submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span> Saving...');
        
        // Clear any previous alerts
        $('.alert').remove();
        
        $.ajax({
            url: form.attr('action'),
            type: 'POST',
            data: formData,
            success: function(response) {
                // Show success message
                var alert = `
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i>
                        Meter reading updated successfully!
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>`;
                
                // Add alert before the table
                $('.card-body').prepend(alert);
                
                // Hide modal after a short delay
                setTimeout(function() {
                    $('#editReadingModal').modal('hide');
                    // Reload the page to reflect changes
                    setTimeout(function() {
                        window.location.reload();
                    }, 500);
                }, 1000);
            },
            error: function(xhr) {
                // Re-enable button
                submitBtn.prop('disabled', false).html(originalBtnText);
                
                var errorMessage = 'An error occurred while updating the meter reading. Please try again.';
                
                // Try to get error message from response
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.message) {
                        errorMessage = response.message;
                    } else if (response.errors) {
                        // Handle validation errors
                        errorMessage = Object.values(response.errors).join('<br>');
                    }
                } catch (e) {
                    console.error('Error parsing error response:', e);
                }
                
                // Show error message in modal
                var alert = `
                    <div class="alert alert-danger alert-dismissible fade show mb-3" role="alert">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <div>${errorMessage}</div>
                        </div>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>`;
                
                // Clear any existing alerts and add new one
                $('.modal .alert').remove();
                form.prepend(alert);
                
                // Scroll to top of form to show error
                $('html, body').animate({
                    scrollTop: form.offset().top - 100
                }, 300);
            },
            complete: function() {
                // Re-enable button if not already done in error handler
                submitBtn.prop('disabled', false).html(originalBtnText);
            }
        });
    });
});
</script>
@endpush

@endsection
