// mode-waktu.js - Mode Waktu Controller with CRUD import { initializeApp } from "https://www.gstatic.com/firebasejs/12.7.0/firebase-app.js"; import { getAuth, onAuthStateChanged, signOut } from "https://www.gstatic.com/firebasejs/12.7.0/firebase-auth.js"; import { getDatabase, ref, set, onValue, update, remove } from "https://www.gstatic.com/firebasejs/12.7.0/firebase-database.js"; // Firebase configuration const firebaseConfig = { apiKey: "AIzaSyCQWvoDxDyVCuLEDiwammjUIVYxVARzJig", authDomain: "project-ta-951b4.firebaseapp.com", databaseURL: "https://project-ta-951b4-default-rtdb.firebaseio.com", projectId: "project-ta-951b4", storageBucket: "project-ta-951b4.firebasestorage.app", messagingSenderId: "217854138058", appId: "1:217854138058:web:50a5bcd5a61ac1820c4633", measurementId: "G-6ML8QQEGNZ" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const auth = getAuth(app); const database = getDatabase(app); let schedules = []; let isPageLoaded = false; const MODE_WAKTU_BASE_PATH = 'kontrol_1'; function getSchedulePath(scheduleId) { return `${MODE_WAKTU_BASE_PATH}/${scheduleId}`; } function getNextScheduleId() { const indices = schedules .map((item) => { const match = String(item.id || '').match(/^jadwal_(\d+)$/i); return match ? parseInt(match[1], 10) : 0; }) .filter((value) => Number.isFinite(value)); const nextIndex = indices.length > 0 ? Math.max(...indices) + 1 : 1; return `jadwal_${nextIndex}`; } function getSelectedPotsFromFirebase(potAktif) { const selected = []; if (Array.isArray(potAktif)) { potAktif.forEach((value) => { const potNumber = Number(value); if (Number.isFinite(potNumber) && potNumber >= 1 && potNumber <= 5) { selected.push(`pot${potNumber}`); } }); return Array.from(new Set(selected)); } if (potAktif && typeof potAktif === 'object') { const hasNumericKeys = Object.keys(potAktif).some((key) => /^\d+$/.test(key)); if (hasNumericKeys) { Object.values(potAktif).forEach((value) => { const potNumber = Number(value); if (Number.isFinite(potNumber) && potNumber >= 1 && potNumber <= 5) { selected.push(`pot${potNumber}`); } }); return Array.from(new Set(selected)); } for (let i = 1; i <= 5; i++) { if (potAktif[`pot_${i}`] === true || potAktif[`pot${i}`] === true) { selected.push(`pot${i}`); } } } return selected; } function normalizeScheduleFromMobile(id, data) { const pots = getSelectedPotsFromFirebase(data?.pot_aktif); let pumpType = 'air'; if (data?.pompa_pengaduk) { pumpType = 'pengaduk'; } else if (data?.pompa_pupuk) { pumpType = 'nutrisi'; } else if (data?.pompa_air) { pumpType = 'air'; } return { id, name: data?.nama || `Jadwal ${String(id).replace('jadwal_', '')}`, time: data?.waktu || '', duration: Number(data?.durasi || 30), pots, pumpType, aktif: data?.aktif === true }; } function toMobileScheduleData(scheduleData) { const selectedPots = Array.isArray(scheduleData.pots) ? scheduleData.pots : []; const potAktifList = Array.from(new Set( selectedPots .map((pot) => Number(String(pot).replace('pot', ''))) .filter((potNumber) => Number.isFinite(potNumber) && potNumber >= 1 && potNumber <= 5) )); return { aktif: true, durasi: Number(scheduleData.duration || 30), waktu: scheduleData.time || '', pompa_air: scheduleData.pumpType === 'air', pompa_pupuk: scheduleData.pumpType === 'nutrisi', pompa_pengaduk: scheduleData.pumpType === 'pengaduk', pot_aktif: potAktifList }; } // Notification function function showNotification(message, type = 'success') { const notification = document.getElementById('notification'); if (!notification) { const notif = document.createElement('div'); notif.id = 'notification'; notif.className = `notification ${type}`; notif.textContent = message; document.body.appendChild(notif); setTimeout(() => { notif.classList.add('show'); }, 10); setTimeout(() => { notif.classList.remove('show'); setTimeout(() => notif.remove(), 300); }, 3000); } else { notification.className = `notification ${type}`; notification.textContent = message; notification.classList.add('show'); setTimeout(() => { notification.classList.remove('show'); }, 3000); } } // Authentication check onAuthStateChanged(auth, (user) => { if (user) { document.getElementById('userEmail').textContent = user.email; document.getElementById('dashboardPage').style.display = 'block'; // document.getElementById('loginMessage').hidden = true; initializeMode(); } else { document.getElementById('dashboardPage').style.display = 'none'; // document.getElementById('loginMessage').hidden = false; setTimeout(() => { window.location.href = '../index.html'; }, 2000); } }); // Logout handler document.getElementById('signOutBtn')?.addEventListener('click', async () => { try { await signOut(auth); window.location.href = '../index.html'; } catch (error) { showNotification('Error logging out: ' + error.message, 'error'); } }); // Normalize boolean value from Firebase (handle string, number, boolean) function normalizeBooleanValue(value) { if (typeof value === 'boolean') return value; if (typeof value === 'number') return value !== 0; if (typeof value === 'string') { const lower = value.toLowerCase().trim(); return lower === 'true' || lower === '1' || lower === 'yes'; } return false; } // Update toggle UI based on active state function updateToggleUI(isActive) { const mainToggle = document.getElementById('mainToggle'); const statusIndicator = document.getElementById('statusIndicator'); const statusText = document.getElementById('statusText'); const btnAddSchedule = document.getElementById('btnAddSchedule'); if (mainToggle) { if (isActive) { mainToggle.classList.add('active'); } else { mainToggle.classList.remove('active'); } } if (statusIndicator) { if (isActive) { statusIndicator.classList.add('active'); statusText.textContent = 'Aktif'; if (btnAddSchedule) btnAddSchedule.disabled = false; } else { statusIndicator.classList.remove('active'); statusText.textContent = 'Tidak Aktif'; if (btnAddSchedule) btnAddSchedule.disabled = true; } } } // Initialize mode function initializeMode() { // Listen to Mode Waktu status (field: waktu) const statusRef = ref(database, `${MODE_WAKTU_BASE_PATH}/waktu`); onValue(statusRef, (snapshot) => { const firebaseValue = snapshot.val(); const isActive = normalizeBooleanValue(firebaseValue); updateToggleUI(isActive); }); // Load schedules from Firebase loadSchedulesFromFirebase(); // Setup add schedule button setupAddScheduleButton(); isPageLoaded = true; } // Load schedules from Firebase function loadSchedulesFromFirebase() { const schedulesRef = ref(database, MODE_WAKTU_BASE_PATH); onValue(schedulesRef, (snapshot) => { schedules = []; const data = snapshot.val(); if (data) { Object.keys(data).forEach((key) => { if (/^jadwal_\d+$/i.test(key) && data[key] && typeof data[key] === 'object') { schedules.push(normalizeScheduleFromMobile(key, data[key])); } }); schedules.sort((a, b) => { const aNum = parseInt(String(a.id).replace('jadwal_', ''), 10) || 0; const bNum = parseInt(String(b.id).replace('jadwal_', ''), 10) || 0; return aNum - bNum; }); } renderSchedules(); }); } // Render schedules to the UI function renderSchedules() { const container = document.getElementById('scheduleContainer'); if (!container) return; if (schedules.length === 0) { container.innerHTML = `
Belum ada jadwal penyiraman
Klik tombol "Tambah Jadwal" untuk membuat jadwal baru