document.addEventListener('DOMContentLoaded', function () { const alarmForm = document.getElementById('alarm-form'); const alarmsList = document.getElementById('alarms-list'); const alarmModal = new bootstrap.Modal(document.getElementById('alarm-modal')); const alarmSound = document.getElementById('alarm-sound'); const dismissAlarmBtn = document.getElementById('dismiss-alarm'); const enableNotificationsBtn = document.getElementById('enable-notifications'); let notificationPermission = false; // Request notification permission if (enableNotificationsBtn) { enableNotificationsBtn.addEventListener('click', () => { Notification.requestPermission().then(permission => { if (permission === 'granted') { notificationPermission = true; alert('Notifications enabled!'); enableNotificationsBtn.style.display = 'none'; } else { alert('Notification permission denied.'); } }); }); } // Function to fetch and display alarms const fetchAlarms = () => { fetch('/api/alarms.php?action=get') .then(response => response.json()) .then(data => { alarmsList.innerHTML = ''; if (data.success) { data.alarms.forEach(alarm => { addAlarmToList(alarm.id, alarm.alarm_time, alarm.note_id, alarm.is_active); }); } }); }; // Function to add a single alarm to the list const addAlarmToList = (id, time, noteId, isActive) => { const listItem = document.createElement('li'); listItem.className = 'list-group-item d-flex justify-content-between align-items-center'; listItem.dataset.id = id; const timeText = document.createElement('span'); timeText.textContent = new Date(`1970-01-01T${time}`).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); const noteLink = document.createElement('a'); noteLink.href = `/note.php?id=${noteId}`; noteLink.textContent = `Note #${noteId}`; noteLink.className = 'mx-3'; const controls = document.createElement('div'); const toggleSwitch = document.createElement('div'); toggleSwitch.className = 'form-check form-switch'; const toggleInput = document.createElement('input'); toggleInput.className = 'form-check-input'; toggleInput.type = 'checkbox'; toggleInput.role = 'switch'; toggleInput.checked = isActive; toggleInput.addEventListener('change', () => handleToggleAlarm(id, toggleInput.checked)); toggleSwitch.appendChild(toggleInput); const deleteBtn = document.createElement('button'); deleteBtn.className = 'btn btn-danger btn-sm ms-3'; deleteBtn.textContent = 'Delete'; deleteBtn.addEventListener('click', () => handleDeleteAlarm(id)); controls.appendChild(toggleSwitch); controls.appendChild(deleteBtn); listItem.appendChild(timeText); listItem.appendChild(noteLink); listItem.appendChild(controls); alarmsList.appendChild(listItem); }; // Handle form submission to create a new alarm if (alarmForm) { alarmForm.addEventListener('submit', function (e) { e.preventDefault(); const formData = new FormData(alarmForm); fetch('/api/alarms.php?action=create', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { if (data.success) { addAlarmToList(data.id, data.alarm_time, data.note_id, true); alarmForm.reset(); } else { alert('Error: ' + data.error); } }); }); } // Handle deleting an alarm const handleDeleteAlarm = (id) => { if (!confirm('Are you sure you want to delete this alarm?')) return; fetch(`/api/alarms.php?action=delete&id=${id}`, { method: 'GET' }) .then(response => response.json()) .then(data => { if (data.success) { document.querySelector(`li[data-id='${id}']`).remove(); } else { alert('Error: ' + data.error); } }); }; // Handle toggling an alarm's active state const handleToggleAlarm = (id, isActive) => { const formData = new FormData(); formData.append('id', id); formData.append('is_active', isActive ? 1 : 0); fetch('/api/alarms.php?action=toggle', { method: 'POST', body: formData }).then(response => response.json()) .then(data => { if (!data.success) { alert('Error updating alarm status.'); } }); }; // Function to check for due alarms const checkAlarms = () => { fetch('/api/alarms.php?action=check') .then(response => response.json()) .then(data => { if (data.success && data.alarms.length > 0) { const alarm = data.alarms[0]; // Assuming one alarm for now showNotification(alarm); // Also update the toggle on the main page const alarmToggle = document.querySelector(`li[data-id='${alarm.id}'] input[type='checkbox']`); if (alarmToggle) { alarmToggle.checked = false; } } }); }; // Function to show notification const showNotification = (alarm) => { const alarmTime = new Date(`1970-01-01T${alarm.alarm_time}`).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); const notificationTitle = `Alarm! It's ${alarmTime}`; const notificationBody = `Click to open your note.`; if (notificationPermission) { const notification = new Notification(notificationTitle, { body: notificationBody, icon: '/assets/images/bell.png', // Optional: add an icon sound: '/assets/sounds/alarm.mp3', // This doesn't work, sound is handled separately requireInteraction: true // Keeps notification open until user interacts }); notification.onclick = () => { window.open(`/note.php?id=${alarm.note_id}`, '_blank'); notification.close(); }; } // Fallback to modal alarmSound.play().catch(e => console.error("Audio playback failed:", e)); alarmModal.show(); dismissAlarmBtn.onclick = () => { alarmSound.pause(); alarmSound.currentTime = 0; alarmModal.hide(); }; }; // Initial fetch and periodic check fetchAlarms(); setInterval(checkAlarms, 5000); // Check every 5 seconds });