@extends('layouts.app')

@section('title', 'History Sensor')

@section('content')
    <style>
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .animate-fadeIn {
            animation: fadeIn 0.5s ease-out forwards;
        }
    </style>

    
    <div class="mt-8 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="bg-white overflow-hidden shadow-sm rounded-lg">
            <div class="p-6 bg-white border-b border-gray-200">
                <!-- Info Pembaruan Otomatis -->
                <div class="mb-4 bg-blue-50 p-3 rounded-md border border-blue-200">
                    <div class="flex items-start">
                        <div class="flex-shrink-0">
                            <svg class="h-5 w-5 text-blue-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <div class="ml-3">
                            <h3 class="text-sm font-medium text-blue-800">Pembaruan Realtime</h3>
                            <div class="mt-1 text-sm text-blue-700">
                                <p>Data sensor akan otomatis terekam saat ada perubahan nilai pada setiap sensor dan ditampilkan secara realtime pada tabel history tanpa perlu refresh halaman.</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Filter dan Kontrol -->
                <div class="flex flex-col md:flex-row justify-between items-center mb-6">
                    <div class="flex items-center space-x-4 mb-4 md:mb-0">
                        <select id="sensor-filter" class="rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                            <option value="all">Semua Sensor</option>
                            <option value="suhu">Suhu</option>
                            <option value="kelembapan_tanah">Kelembapan Tanah</option>
                            <option value="cahaya">Cahaya</option>
                        </select>
                        
                        <div class="flex items-center">
                            <input type="date" id="date-filter" class="rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" title="Filter berdasarkan tanggal">
                            <button id="reset-date" class="ml-2 px-2 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 focus:outline-none transition-colors" title="Reset filter tanggal">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                        
                        <button id="sync-firebase" class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors flex items-center">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" 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>
                            Sinkronisasi
                        </button>
                                              
                        <button id="clear-history" class="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600 transition-colors">
                            Hapus Riwayat
                        </button>
                    </div>
                    
                    <div class="flex items-center text-sm text-gray-500">
                        <div>Total data: <span id="total-records">0</span></div>
                        
                        <div class="ml-4 flex items-center space-x-2">
                            <span id="realtime-status" class="px-2 py-1 bg-green-100 text-green-800 rounded-full flex items-center">
                                <span class="h-2 w-2 bg-green-500 rounded-full mr-1 animate-pulse"></span>
                                Realtime aktif
                            </span>
                            <button id="toggle-realtime" class="text-gray-600 hover:text-gray-800 focus:outline-none" title="Toggle realtime update">
                                <svg xmlns="http://www.w3.org/2000/svg" class="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 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Tabel Riwayat -->
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Waktu</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Sensor</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nilai Baru</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                                <th scope="col" class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Hapus</th>
                            </tr>
                        </thead>
                        <tbody id="history-table-body" class="bg-white divide-y divide-gray-200">
                            <!-- Data akan diisi menggunakan JavaScript -->
                            <tr id="no-data-row">
                                <td colspan="6" class="px-6 py-4 text-center text-sm text-gray-500">
                                    Tidak ada data riwayat
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="flex justify-between items-center mt-4">
                    <div class="flex items-center">
                        <label for="rows-per-page" class="text-sm text-gray-600 mr-2">Baris per halaman:</label>
                        <select id="rows-per-page" class="rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
                            <option value="5">5</option>
                            <option value="10" selected>10</option>
                            <option value="25">25</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                    </div>
                    <div class="flex items-center space-x-2">
                        <span class="text-sm text-gray-600">
                            Halaman <span id="current-page">1</span> dari <span id="total-pages">1</span>
                        </span>
                        <div class="flex space-x-1">
                            <button id="prev-page" class="px-3 py-1 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 disabled:opacity-50">
                                &lt;
                            </button>
                            <button id="next-page" class="px-3 py-1 bg-gray-100 text-gray-700 rounded-md hover:bg-gray-200 disabled:opacity-50">
                                &gt;
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- SweetAlert2 CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<!-- SweetAlert2 JS -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    // Definisikan variabel global di luar DOMContentLoaded
    let currentPage = 1;
    let rowsPerPage = 10;
    let currentFilterType = 'all';
    let currentFilterDate = null;
    let filteredHistoryGlobal = [];
    let csrfToken = "{{ csrf_token() }}"; // Tambahkan CSRF token untuk request API
    
    // Tambahkan referensi elemen global di awal script, sebelum semua fungsi
    let historyTableBody;
    let totalRecordsElement;
    let sensorFilter;
    let dateFilter;
    let resetDateButton;
    let clearHistoryButton;
    let noDataRow;
    let itemToDeleteIndex = null;
    
    // Tambahkan variabel global baru
    let currentPageElement;
    let totalPagesElement;
    let prevPageButton;
    let nextPageButton;
    
    // Fungsi inisialisasi elemen
    function initializeElements() {
        historyTableBody = document.getElementById('history-table-body');
        totalRecordsElement = document.getElementById('total-records');
        sensorFilter = document.getElementById('sensor-filter');
        dateFilter = document.getElementById('date-filter');
        resetDateButton = document.getElementById('reset-date');
        clearHistoryButton = document.getElementById('clear-history');
        noDataRow = document.getElementById('no-data-row');
        
        // Tambahkan inisialisasi elemen paginasi
        currentPageElement = document.getElementById('current-page');
        totalPagesElement = document.getElementById('total-pages');
        prevPageButton = document.getElementById('prev-page');
        nextPageButton = document.getElementById('next-page');
    }
    
    // Pindahkan fungsi-fungsi ke scope global
    function parseFirebaseTimestamp(timestamp) {
        // Jika timestamp kosong atau undefined, gunakan waktu sekarang
        if (!timestamp) return new Date();
        
        // Handle Firebase Timestamp object
        if (timestamp && typeof timestamp === 'object' && timestamp.seconds) {
            return new Date(timestamp.seconds * 1000);
        }
        
        // Handle string timestamp dalam format ISO
        if (typeof timestamp === 'string') {
            try {
            return new Date(timestamp);
            } catch (e) {
                console.error('Error parsing timestamp string:', e);
                return new Date();
            }
        }
        
        // Handle timestamp dalam bentuk number (unix timestamp)
        if (typeof timestamp === 'number') {
            return new Date(timestamp);
        }
        
        console.warn('Timestamp format tidak dikenal:', timestamp);
        return new Date(); // Fallback ke waktu sekarang jika format tidak dikenal
    }

    // Fungsi untuk memuat data dari file JSON melalui API
    async function loadHistory() {
        console.log('loadHistory() dipanggil');
        try {
            console.log('Mencoba mengambil data dari /api/history');
            const response = await fetch('/api/history');
            console.log('Response status:', response.status);
            console.log('Response OK:', response.ok);
            
            if (!response.ok) {
                throw new Error('Network response was not ok: ' + response.status);
            }
            
            const historyData = await response.json();
            console.log('Data berhasil diterima:', historyData);
            
            // Validasi data
            if (!Array.isArray(historyData)) {
                console.error('Data yang diterima bukan array:', historyData);
                return [];
            }
            
            console.log('Jumlah data:', historyData.length);
            
            // Pastikan data memiliki format yang benar dan validasi timestamp
            return historyData.map(item => {
                // Validasi item
                if (!item || typeof item !== 'object') {
                    console.warn('Item tidak valid:', item);
                    return {
                        timestamp: new Date().toISOString(),
                        sensor: 'unknown',
                        newValue: 0
                    };
                }
                
                // Validasi timestamp
                let timestamp = item.timestamp;
                if (timestamp) {
                    try {
                        // Coba parse timestamp untuk memastikan format valid
                        new Date(timestamp);
                    } catch (e) {
                        console.warn('Timestamp tidak valid:', timestamp);
                        timestamp = new Date().toISOString();
                    }
                } else {
                    timestamp = new Date().toISOString();
                }
                
                return {
                    timestamp: timestamp,
                    sensor: item.sensor || 'unknown',
                    newValue: isNaN(parseFloat(item.newValue)) ? 0 : parseFloat(item.newValue)
                };
            });
        } catch (error) {
            console.error('Error loading history:', error);
            Swal.fire({
                icon: 'error',
                title: 'Gagal memuat data',
                text: 'Terjadi kesalahan saat memuat data history: ' + error.message
            });
            return [];
        }
    }

    // Fungsi untuk menampilkan history
    async function displayHistory(filterType = 'all', filterDate = null, forceRefresh = false) {
        console.log('Display History dipanggil dengan filter:', { filterType, filterDate, rowsPerPage, forceRefresh });
        currentFilterType = filterType;
        currentFilterDate = filterDate;
        
        try {
            // Tampilkan loading indicator jika ini adalah refresh penuh (bukan update realtime)
            if (!forceRefresh) {
                historyTableBody.innerHTML = `
                    <tr>
                        <td colspan="6" class="px-6 py-4 text-center text-sm text-gray-500">
                            <div class="flex justify-center">
                                <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>Memuat data...</span>
                            </div>
                        </td>
                    </tr>
                `;
            }
            
            // Ambil data dari API
            let history = await loadHistory();
            
            if (!history || history.length === 0) {
                historyTableBody.innerHTML = `
                    <tr>
                        <td colspan="6" class="px-6 py-4 text-center text-sm text-gray-500">
                            Tidak ada data history yang tersedia
                        </td>
                    </tr>
                `;
                totalRecordsElement.textContent = "0";
                currentPageElement.textContent = "1";
                totalPagesElement.textContent = "1";
                return;
            }
            
            // Filter berdasarkan jenis sensor
            if (filterType !== 'all') {
                if (filterType === 'kelembapan_tanah') {
                    // Filter untuk kedua kemungkinan nama sensor (untuk kompatibilitas data lama)
                    history = history.filter(item => item.sensor === 'kelembapan_tanah' || item.sensor === 'kelembaban');
                } else {
                    history = history.filter(item => item.sensor === filterType);
                }
            }
            
            // Filter berdasarkan tanggal jika ada
            if (filterDate) {
                try {
                    const selectedDate = new Date(filterDate);
                    selectedDate.setHours(0, 0, 0, 0);
                    
                    const nextDay = new Date(selectedDate);
                    nextDay.setDate(selectedDate.getDate() + 1);
                    
                    history = history.filter(item => {
                        try {
                            const itemDate = parseFirebaseTimestamp(item.timestamp);
                            return itemDate >= selectedDate && itemDate < nextDay;
                        } catch (error) {
                            console.error('Error filtering date:', error);
                            return false;
                        }
                    });
                } catch (error) {
                    console.error('Error in date filtering:', error);
                }
            }
            
            // Urutkan history berdasarkan timestamp terbaru
            history.sort((a, b) => {
                const dateA = new Date(a.timestamp);
                const dateB = new Date(b.timestamp);
                return dateB - dateA; // Urutkan dari yang terbaru
            });
            
            // Jika ini adalah update realtime, periksa apakah data berubah
            if (forceRefresh) {
                // Jika tidak ada data baru, keluar dari fungsi
                if (historyDataUnchanged(history, filteredHistoryGlobal)) {
                    console.log('Data tidak berubah, tidak perlu update tampilan');
                    return;
                }
            }
            
            // Update data global
            filteredHistoryGlobal = history;
            totalRecordsElement.textContent = history.length;
            
            // Hitung total halaman berdasarkan rowsPerPage
            const totalPages = Math.ceil(history.length / rowsPerPage);
            
            // Pastikan currentPage valid
            if (currentPage > totalPages) {
                currentPage = totalPages || 1;
            }
            
            // Update indikator halaman
            currentPageElement.textContent = currentPage;
            totalPagesElement.textContent = totalPages;
            
            // Hitung indeks awal dan akhir untuk data yang akan ditampilkan
            const startIdx = (currentPage - 1) * rowsPerPage;
            const endIdx = Math.min(startIdx + rowsPerPage, history.length);
            const pageData = history.slice(startIdx, endIdx);
            
            // Update status tombol navigasi
            prevPageButton.disabled = currentPage === 1;
            nextPageButton.disabled = currentPage >= totalPages;
            
            // Update styling tombol
            if (prevPageButton.disabled) {
                prevPageButton.classList.add('opacity-50', 'cursor-not-allowed');
            } else {
                prevPageButton.classList.remove('opacity-50', 'cursor-not-allowed');
            }
            
            if (nextPageButton.disabled) {
                nextPageButton.classList.add('opacity-50', 'cursor-not-allowed');
            } else {
                nextPageButton.classList.remove('opacity-50', 'cursor-not-allowed');
            }

            // Bersihkan tabel
            if (pageData.length === 0) {
                historyTableBody.innerHTML = `
                    <tr>
                        <td colspan="6" class="px-6 py-4 text-center text-sm text-gray-500">
                            Tidak ada data history yang tersedia
                        </td>
                    </tr>
                `;
                return;
            } else {
                // Render tabel baru dengan data terbaru
                historyTableBody.innerHTML = '';
                
                // Render data
                pageData.forEach((item, index) => {
                    try {
                        const rowId = startIdx + index;
                        
                        // Format waktu dengan penanganan error
                        let date;
                        try {
                            date = parseFirebaseTimestamp(item.timestamp);
                        } catch (error) {
                            console.error('Error parsing date:', error, item);
                            date = new Date(); // Fallback ke waktu sekarang
                        }
                        
                        const formattedDate = date.toLocaleDateString('id-ID', {
                            day: '2-digit',
                            month: '2-digit',
                            year: 'numeric'
                        });
                        const formattedTime = date.toLocaleTimeString('id-ID');
                        
                        // Tentukan warna berdasarkan jenis sensor
                        let sensorColor = 'text-gray-800';
                        if (item.sensor === 'suhu') sensorColor = 'text-red-600';
                        if (item.sensor === 'kelembapan_tanah' || item.sensor === 'kelembaban') sensorColor = 'text-blue-600';
                        if (item.sensor === 'cahaya') sensorColor = 'text-yellow-600';
                        
                        // Unit berdasarkan jenis sensor
                        let unit = '';
                        if (item.sensor === 'suhu') unit = '°C';
                        if (item.sensor === 'kelembapan_tanah' || item.sensor === 'kelembaban') unit = '%';
                        if (item.sensor === 'cahaya') unit = ' lux';
                        
                        // Dapatkan status dan aksi berdasarkan nilai baru
                        const { status, action, statusClass } = getSensorStatusAndAction(item.sensor, item.newValue);
                        
                        // Buat elemen baris baru
                        const tr = document.createElement('tr');
                        tr.dataset.id = rowId;
                        tr.className = `${index % 2 === 0 ? 'bg-white' : 'bg-gray-50'} ${forceRefresh ? 'animate-fadeIn' : ''}`;
                        
                        // Set HTML untuk baris
                        tr.innerHTML = `
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${formattedDate} ${formattedTime}</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="font-medium ${sensorColor} capitalize">${item.sensor === 'kelembapan_tanah' || item.sensor === 'kelembaban' ? 'Kelembapan Tanah' : item.sensor}</span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${item.newValue}${unit}</td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="font-medium ${statusClass}">${status}</span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm ${action.includes('On') ? 'text-green-600' : 'text-gray-600'} font-medium">
                                ${action}
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-center">
                                <button class="delete-btn text-red-500 hover:text-red-700 focus:outline-none">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                    </svg>
                                </button>
                            </td>
                        `;
                        
                        // Tambahkan baris ke tabel
                        historyTableBody.appendChild(tr);
                    } catch (error) {
                        console.error('Error rendering row:', error, item);
                    }
                });
                
                // Tambahkan event listener untuk tombol hapus
                document.querySelectorAll('.delete-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        const row = this.closest('tr');
                        itemToDeleteIndex = parseInt(row.dataset.id);
                        confirmDeleteSingleItem();
                    });
                });
            }
            
            console.log('Menampilkan data:', {
                total: history.length,
                halaman: currentPage,
                totalHalaman: totalPages,
                barisPerHalaman: rowsPerPage,
                dataYangDitampilkan: pageData.length
            });
        } catch (error) {
            console.error('Error displaying history:', error);
            
            // Hanya tampilkan pesan error jika ini adalah refresh penuh (bukan update realtime)
            if (!forceRefresh) {
                historyTableBody.innerHTML = `
                    <tr>
                        <td colspan="6" class="px-6 py-4 text-center text-sm text-red-500">
                            <div class="flex flex-col items-center">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                <span>Error: ${error.message || 'Terjadi kesalahan saat menampilkan data.'}</span>
                            </div>
                        </td>
                    </tr>
                `;
            }
        }
    }
    
    // Fungsi untuk membandingkan dua array data history
    function historyDataUnchanged(newData, oldData) {
        if (!oldData || !newData) return false;
        
        // Jika jumlah data berbeda, data telah berubah
        if (newData.length !== oldData.length) return false;
        
        // Periksa 3 data teratas untuk efisiensi
        // Ini mengasumsikan bahwa data baru muncul di awal array (setelah pengurutan)
        const compareLimit = Math.min(3, newData.length);
        
        for (let i = 0; i < compareLimit; i++) {
            // Bandingkan timestamp dan nilai untuk menentukan apakah ada perubahan
            if (newData[i].timestamp !== oldData[i].timestamp ||
                newData[i].sensor !== oldData[i].sensor ||
                newData[i].newValue !== oldData[i].newValue) {
                return false; // Data telah berubah
            }
        }
        
        return true; // Data tidak berubah
    }

    // Event listener untuk document ready
    document.addEventListener('DOMContentLoaded', function() {
        initializeElements();
        
        // Status realtime update
        let isRealtimeEnabled = true;
        
        // Referensi ke Firebase Database
        const historyRef = firebase.database().ref('historySensor');
        const sensorRef = firebase.database().ref('sensor');
        
        // Fungsi untuk menangani perubahan data sensor
        function onSensorChange(snapshot) {
            if (!isRealtimeEnabled) return;
            
            console.log('Perubahan pada sensor terdeteksi');
            // Refresh data history
            displayHistory(currentFilterType, currentFilterDate, true);
        }
        
        // Fungsi untuk menangani penambahan data baru ke history
        function onHistoryAdded(snapshot) {
            if (!isRealtimeEnabled) return;
            
            console.log('Data history baru terdeteksi:', snapshot.key);
            // Refresh data history ketika ada data baru ditambahkan
            displayHistory(currentFilterType, currentFilterDate, true);
        }
        
        // Fungsi untuk toggle realtime update
        function toggleRealtimeUpdate() {
            isRealtimeEnabled = !isRealtimeEnabled;
            
            const realtimeStatus = document.getElementById('realtime-status');
            const toggleRealtime = document.getElementById('toggle-realtime');
            
            if (isRealtimeEnabled) {
                // Aktifkan fitur realtime
                realtimeStatus.innerHTML = `
                    <span class="h-2 w-2 bg-green-500 rounded-full mr-1 animate-pulse"></span>
                    Realtime aktif
                `;
                realtimeStatus.className = 'px-2 py-1 bg-green-100 text-green-800 rounded-full flex items-center';
                toggleRealtime.innerHTML = `
                    <svg xmlns="http://www.w3.org/2000/svg" class="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 9v6m4-6v6m7-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                `;
                
                // Update tampilan tabel 
                displayHistory(currentFilterType, currentFilterDate);
                
                // Aktifkan listener Firebase - tidak perlu setup ulang karena kita pakai .on di luar
            } else {
                // Nonaktifkan fitur realtime
                realtimeStatus.innerHTML = `
                    <span class="h-2 w-2 bg-gray-500 rounded-full mr-1"></span>
                    Realtime nonaktif
                `;
                realtimeStatus.className = 'px-2 py-1 bg-gray-100 text-gray-800 rounded-full flex items-center';
                toggleRealtime.innerHTML = `
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                `;
            }
        }
        
        // Toggle button event
        document.getElementById('toggle-realtime').addEventListener('click', toggleRealtimeUpdate);
        
        // Ambil preferensi tersimpan dari localStorage
        const savedRowsPerPage = localStorage.getItem('preferredRowsPerPage');
        if (savedRowsPerPage) {
            document.getElementById('rows-per-page').value = savedRowsPerPage;
            rowsPerPage = parseInt(savedRowsPerPage);
        } else {
            rowsPerPage = parseInt(document.getElementById('rows-per-page').value) || 10;
        }

        // Event listener untuk rows per page
        document.getElementById('rows-per-page').addEventListener('change', function() {
            rowsPerPage = parseInt(this.value);
            currentPage = 1; // Reset ke halaman pertama ketika mengubah jumlah baris
            localStorage.setItem('preferredRowsPerPage', this.value); // Simpan preferensi
            displayHistory(currentFilterType, currentFilterDate);
        });
        
        // Event listeners
        sensorFilter.addEventListener('change', function() {
            currentPage = 1;
            displayHistory(this.value, dateFilter.value);
        });
        
        dateFilter.addEventListener('change', function() {
            currentPage = 1;
            displayHistory(sensorFilter.value, this.value);
        });
        
        resetDateButton.addEventListener('click', function() {
            dateFilter.value = null;
            currentPage = 1;
            displayHistory(sensorFilter.value, null);
        });
        
        // Tombol Hapus Riwayat
        clearHistoryButton.addEventListener('click', function() {
            confirmDeleteAllItems();
        });
        
        // Tombol Sinkronisasi Firebase
        document.getElementById('sync-firebase').addEventListener('click', function() {
            syncFromFirebase();
        });
        
        // Event listener untuk tombol navigasi
        prevPageButton.addEventListener('click', function() {
            if (currentPage > 1) {
                currentPage--;
                displayHistory(currentFilterType, currentFilterDate);
            }
        });
        
        nextPageButton.addEventListener('click', function() {
            const totalPages = Math.ceil(filteredHistoryGlobal.length / rowsPerPage);
            if (currentPage < totalPages) {
                currentPage++;
                displayHistory(currentFilterType, currentFilterDate);
            }
        });
        
        // Keyboard navigation
        document.addEventListener('keydown', function(e) {
            if (e.key === 'ArrowLeft' && !prevPageButton.disabled) {
                prevPageButton.click();
            } else if (e.key === 'ArrowRight' && !nextPageButton.disabled) {
                nextPageButton.click();
            }
        });
        
        // Tambahkan event listener ke Firebase untuk deteksi perubahan data
        // 1. Listener untuk child_added - saat entri baru ditambahkan ke history
        historyRef.on('child_added', onHistoryAdded);
        
        // 2. Listener untuk perubahan nilai sensor
        sensorRef.on('child_changed', onSensorChange);
        
        // 3. Listener untuk nilai baru dari sensor
        sensorRef.on('value', (snapshot) => {
            if (isRealtimeEnabled) {
                // Tidak perlu memeriksa setiap nilai, hanya perlu memeriksa perubahan
                // Ini akan memicu hampir sama dengan onSensorChange, tetapi lebih akurat untuk perubahan nilai total
                console.log('Snapshot nilai sensor baru terdeteksi');
                displayHistory(currentFilterType, currentFilterDate, true);
            }
        });
        
        // 4. Tampilkan alert jika koneksi Firebase terputus
        firebase.database().ref('.info/connected').on('value', function(snap) {
            if (snap.val() === true) {
                console.log('Terhubung ke Firebase Realtime Database');
            } else {
                console.log('Terputus dari Firebase Realtime Database');
                // Mungkin tampilkan notifikasi ke pengguna
            }
        });
        
        // Tampilkan data awal
        displayHistory();
        
        // Setup auto refresh setiap 3 detik sebagai fallback jika Firebase listener tidak berfungsi
        setInterval(function() {
            if (isRealtimeEnabled) {
                console.log('Auto refresh data history (fallback polling)');
                displayHistory(currentFilterType, currentFilterDate, true);
            }
        }, 3000);
    });

    // Fungsi konfirmasi hapus menggunakan SweetAlert2
    function confirmDeleteSingleItem() {
        Swal.fire({
            title: 'Apakah Anda yakin?',
            text: "Data yang dihapus tidak dapat dikembalikan!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Ya, hapus!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                deleteSingleItem();
            }
        });
    }

    function confirmDeleteAllItems() {
        Swal.fire({
            title: 'Hapus semua data?',
            text: "Semua data riwayat sensor akan dihapus dan tidak dapat dikembalikan!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Ya, hapus semua!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                deleteAllItems();
            }
        });
    }

    // Fungsi hapus data menggunakan API
    async function deleteSingleItem() {
        if (itemToDeleteIndex === null) return;
        
        try {
            // Tampilkan loading
            Swal.fire({
                title: 'Menghapus data...',
                text: 'Mohon tunggu sebentar',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Kirim request ke API untuk menghapus item
            const response = await fetch('/api/history/delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify({ index: itemToDeleteIndex })
            });
        
            if (!response.ok) {
                throw new Error('Gagal menghapus data');
            }
            
            const result = await response.json();
            
            // Tampilkan pesan sukses
            Swal.fire({
                title: 'Terhapus!',
                text: 'Data berhasil dihapus.',
                icon: 'success',
                timer: 1500,
                showConfirmButton: false
            });
            
            // Refresh tampilan
            displayHistory(currentFilterType, currentFilterDate);
            
        } catch (error) {
            console.error('Error deleting item:', error);
            
            Swal.fire({
                title: 'Error!',
                text: error.message || 'Terjadi kesalahan saat menghapus data',
                icon: 'error'
            });
        }
    }

    async function deleteAllItems() {
        try {
            // Tampilkan loading
            Swal.fire({
                title: 'Menghapus semua data...',
                text: 'Mohon tunggu sebentar',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Kirim request ke API untuk menghapus semua item
            const response = await fetch('/api/history/clear', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': csrfToken
                }
            });
            
            if (!response.ok) {
                throw new Error('Gagal menghapus data');
            }
            
            const result = await response.json();
            
            // Tampilkan pesan sukses
        Swal.fire({
            title: 'Terhapus!',
            text: 'Semua data riwayat berhasil dihapus.',
            icon: 'success',
            timer: 1500,
            showConfirmButton: false
        });
        
            // Refresh tampilan
        displayHistory();
            
        } catch (error) {
            console.error('Error clearing history:', error);
            
            Swal.fire({
                title: 'Error!',
                text: error.message || 'Terjadi kesalahan saat menghapus data',
                icon: 'error'
            });
        }
    }

    // Tambahkan fungsi untuk mendapatkan status dan aksi berdasarkan jenis sensor dan nilai
    function getSensorStatusAndAction(sensor, value) {
        let status = '--';
        let action = '--';
        let statusClass = '';
        
        if (sensor === 'suhu') {
            if (value < 24) {
                status = 'Rendah';
                action = 'Kipas Off';
                statusClass = 'text-blue-600';
            } else if (value >= 25 && value <= 27) {
                status = 'Normal';
                action = 'Kipas Off';
                statusClass = 'text-green-600';
            } else if (value >= 28) {
                status = 'Tinggi';
                action = 'Kipas On';
                statusClass = 'text-red-600';
            }
        } else if (sensor === 'kelembapan_tanah' || sensor === 'kelembaban') {
            if (value < 40) {
                status = 'Kering';
                action = 'Pompa Air On';
                statusClass = 'text-yellow-600';
            } else if (value >= 40 && value < 50) {
                status = 'Cukup';
                action = 'Pompa Air Off';
                statusClass = 'text-green-600';
            } else if (value >= 50 && value < 60) {
                status = 'Optimal';
                action = 'Pompa Air Off';
                statusClass = 'text-green-600';
            } else if (value >= 60 && value <= 70) {
                status = 'Lembap';
                action = 'Pompa Air Off';
                statusClass = 'text-blue-600';
            } else if (value > 70) {
                status = 'Sangat Lembap';
                action = 'Pompa Air Off';
                statusClass = 'text-blue-400';
            }
        } else if (sensor === 'cahaya') {
            if (value < 8000) {
                status = 'Rendah';
                action = 'Lampu On';
                statusClass = 'text-blue-600';
            } else if (value >= 8001 && value <= 11000) {
                status = 'Normal';
                action = 'Lampu Off';
                statusClass = 'text-green-600';
            } else if (value > 11001) {
                status = 'Tinggi';
                action = 'Lampu Off';
                statusClass = 'text-yellow-600';
            }
        }
        
        return { status, action, statusClass };
    }

    // Fungsi untuk sinkronisasi data dari Firebase
    async function syncFromFirebase() {
        try {
            // Tampilkan loading
            Swal.fire({
                title: 'Sinkronisasi Data...',
                text: 'Sedang mengambil data terbaru dari Firebase',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Kirim request ke API untuk sinkronisasi
            const response = await fetch('/api/history/sync-firebase', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': csrfToken
                }
            });
            
            if (!response.ok) {
                throw new Error('Gagal melakukan sinkronisasi');
            }
            
            const result = await response.json();
            
            // Tampilkan pesan sukses
            Swal.fire({
                title: 'Berhasil!',
                text: 'Data berhasil disinkronkan dari Firebase',
                icon: 'success',
                timer: 1500,
                showConfirmButton: false
            });
            
            // Refresh tampilan
            displayHistory(currentFilterType, currentFilterDate);
            
        } catch (error) {
            console.error('Error syncing from Firebase:', error);
            
            Swal.fire({
                title: 'Error!',
                text: error.message || 'Terjadi kesalahan saat sinkronisasi data',
                icon: 'error'
            });
        }
    }
</script>
@endsection
