document.addEventListener('DOMContentLoaded', () => {
const notesContainer = document.getElementById('notes-container');
const noteModal = new bootstrap.Modal(document.getElementById('noteModal'));
const noteForm = document.getElementById('noteForm');
const noteIdInput = document.getElementById('noteId');
const noteTitleInput = document.getElementById('noteTitle');
const noteContentInput = document.getElementById('noteContent');
const aiBtn = document.getElementById('aiBtn');
const saveBtn = document.getElementById('saveBtn');
const fetchNotes = async () => {
const res = await fetch('api/notes.php');
const notes = await res.json();
renderNotes(notes);
};
const renderNotes = (notes) => {
if (notes.length === 0) {
notesContainer.innerHTML = '
Belum ada catatan
Klik "Catatan Baru" untuk memulai.
';
return;
}
notesContainer.innerHTML = '' +
notes.map(note => `
${escapeHtml(note.title || 'Tanpa Judul')}
${escapeHtml(note.content).substring(0, 100)}...
`).join('') + '
';
};
window.editNote = async (id) => {
const res = await fetch(`api/notes.php?id=${id}`);
const note = await res.json();
noteIdInput.value = note.id;
noteTitleInput.value = note.title;
noteContentInput.value = note.content;
noteModal.show();
};
window.deleteNote = async (id) => {
if (confirm('Hapus catatan ini?')) {
await fetch('api/notes.php', {
method: 'DELETE',
body: JSON.stringify({ id })
});
fetchNotes();
}
};
document.getElementById('newNoteBtn').addEventListener('click', () => {
noteForm.reset();
noteIdInput.value = '';
noteModal.show();
});
saveBtn.addEventListener('click', async () => {
const data = {
id: noteIdInput.value,
title: noteTitleInput.value,
content: noteContentInput.value
};
await fetch('api/notes.php', {
method: 'POST',
body: JSON.stringify(data)
});
noteModal.hide();
fetchNotes();
});
aiBtn.addEventListener('click', async () => {
const prompt = noteContentInput.value;
if (!prompt) return alert('Tulis sesuatu dulu agar AI bisa membantu.');
aiBtn.disabled = true;
aiBtn.innerHTML = 'Sedang berpikir...';
try {
const res = await fetch('api/ai_helper.php', {
method: 'POST',
body: JSON.stringify({ prompt, action: 'summarize' })
});
const data = await res.json();
if (data.success) {
noteContentInput.value += "\n\n--- Ringkasan AI ---" + data.text;
} else {
alert('Gagal: ' + data.error);
}
} catch (e) {
alert('Kesalahan koneksi AI');
} finally {
aiBtn.disabled = false;
aiBtn.innerHTML = '✨ Bantu dengan AI';
}
});
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
fetchNotes();
});