<?php
$page_title = 'Pengingat';
include 'includes/header.php';
?>

<div class="container">
    <div class="card">
        <h2>🔔 Buat Pengingat</h2>
        <form id="reminderForm">
            <div class="form-group">
                <label for="reminderTitle">Judul Pengingat</label>
                <input type="text" id="reminderTitle" placeholder="Contoh: Bayar Listrik" required>
            </div>

            <div class="form-group">
                <label for="reminderDate">Tanggal & Waktu</label>
                <input type="datetime-local" id="reminderDate" required>
            </div>

            <div class="form-group">
                <label for="reminderNote">Catatan (Opsional)</label>
                <textarea id="reminderNote" placeholder="Detail pengingat..." rows="3"></textarea>
            </div>

            <div class="form-group">
                <label for="reminderSound">Nada Pengingat</label>
                <select id="reminderSound" style="padding:12px;border:2px solid var(--border);border-radius:8px;width:100%;">
                    <option value="bell">🔔 Bell (Default)</option>
                    <option value="chime">🎵 Chime</option>
                    <option value="digital">📱 Digital Beep</option>
                    <option value="soft">🎶 Soft Tone</option>
                    <option value="alert">⚠️ Alert</option>
                </select>
                <button type="button" onclick="testSound()" style="margin-top:10px;padding:8px 16px;background:var(--primary);color:white;border:none;border-radius:6px;cursor:pointer;">
                    🔊 Test Suara
                </button>
            </div>

            <button type="submit" class="btn btn-primary btn-full">
                <span>➕</span>
                Buat Pengingat
            </button>
        </form>
    </div>

    <div class="card">
        <h2>📋 Daftar Pengingat</h2>
        <div id="remindersList"></div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>

<script>
    let reminders = [];
    let activeAlarms = new Map();

    const notificationSounds = {
        bell: 'https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3',
        chime: 'https://assets.mixkit.co/active_storage/sfx/2571/2571-preview.mp3',
        digital: 'https://assets.mixkit.co/active_storage/sfx/2354/2354-preview.mp3',
        soft: 'https://assets.mixkit.co/active_storage/sfx/2576/2576-preview.mp3',
        alert: 'https://assets.mixkit.co/active_storage/sfx/2863/2863-preview.mp3'
    };

    function testSound() {
        const soundType = document.getElementById('reminderSound').value;
        const audio = new Audio(notificationSounds[soundType]);
        audio.volume = 0.5;
        audio.play().catch(e => console.log('Audio play failed:', e));
    }

    // PERBAIKAN: Load dengan bypass cache
    async function loadData() {
        try {
            const timestamp = new Date().getTime();
            const response = await fetch('api.php?action=load&t=' + timestamp, {
                cache: 'no-store'
            });

            if (!response.ok) {
                console.error('Load failed:', response.status);
                return false;
            }

            const data = await response.json();
            reminders = data.reminders || [];
            displayReminders();

            reminders.forEach(reminder => {
                if (reminder.alarmActive) {
                    setupAlarm(reminder);
                }
            });

            return true;
        } catch (error) {
            console.error('Error loading data:', error);
            return false;
        }
    }

    // PERBAIKAN: Save dengan return response dan load ulang
    async function saveReminders() {
        try {
            const response = await fetch('api.php?action=save_reminders', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ reminders }),
                cache: 'no-store'
            });

            if (!response.ok) {
                console.error('Save failed:', response.status);
                return false;
            }

            const result = await response.json();

            // PENTING: Setelah save, load data segar
            if (result.success) {
                const loaded = await loadData();
                return loaded;
            }

            return false;
        } catch (error) {
            console.error('Error saving:', error);
            return false;
        }
    }

    function displayReminders() {
        const container = document.getElementById('remindersList');
        const now = new Date();

        if (reminders.length === 0) {
            container.innerHTML = '<p style="text-align:center;color:var(--text-secondary);padding:20px;">Belum ada pengingat</p>';
            return;
        }

        container.innerHTML = reminders.map((reminder, index) => {
            const reminderDate = new Date(reminder.date);
            const isExpired = reminderDate < now;

            return `
                <div style="background:var(--bg);padding:15px;border-radius:8px;margin-bottom:10px;border-left:4px solid ${isExpired ? '#f44336' : '#2196F3'};">
                    <div style="display:flex;justify-content:space-between;align-items:start;margin-bottom:10px;">
                        <div>
                            <h4 style="margin:0 0 5px 0;">${reminder.title}</h4>
                            <p style="margin:0;font-size:0.9em;color:var(--text-secondary);">
                                📅 ${reminderDate.toLocaleDateString('id-ID')} - ${reminderDate.toLocaleTimeString('id-ID')}
                            </p>
                        </div>
                        <button onclick="deleteReminder(${index})" class="btn btn-danger" style="padding:5px 10px;background:#f44336;color:white;border:none;border-radius:4px;cursor:pointer;">🗑️</button>
                    </div>
                    ${reminder.note ? `<p style="margin:10px 0;font-size:0.9em;color:var(--text-secondary);">💬 ${reminder.note}</p>` : ''}
                </div>
            `;
        }).join('');
    }

    async function deleteReminder(index) {
        if (confirm('Hapus pengingat ini?')) {
            reminders.splice(index, 1);
            const saved = await saveReminders();
            if (!saved) {
                alert('❌ Gagal menghapus pengingat!');
            }
        }
    }

    function setupAlarm(reminder) {
        const checkInterval = setInterval(() => {
            const now = new Date();
            const reminderDate = new Date(reminder.date);

            if (now >= reminderDate && !activeAlarms.has(reminder.id)) {
                playAlarm(reminder);
                activeAlarms.set(reminder.id, true);
                clearInterval(checkInterval);
            }
        }, 1000);
    }

    function playAlarm(reminder) {
        const audio = new Audio(notificationSounds[reminder.sound || 'bell']);
        audio.loop = true;
        audio.volume = 0.8;
        audio.play();

        alert(`🔔 Pengingat: ${reminder.title}${reminder.note ? '\n' + reminder.note : ''}`);
        audio.pause();
    }

    document.getElementById('reminderForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const reminder = {
            id: Date.now().toString(),
            title: document.getElementById('reminderTitle').value,
            date: document.getElementById('reminderDate').value,
            note: document.getElementById('reminderNote').value,
            sound: document.getElementById('reminderSound').value,
            alarmActive: true
        };

        reminders.push(reminder);

        // PERBAIKAN: Tunggu save selesai baru reset
        const saved = await saveReminders();

        if (saved) {
            this.reset();
            alert('✅ Pengingat berhasil dibuat dan ditampilkan!');
        } else {
            alert('❌ Gagal membuat pengingat!');
            reminders.pop();
        }
    });

    // Load data saat halaman dimuat
    loadData();

    // Auto-refresh setiap 3 detik
    setInterval(loadData, 3000);
</script>
