const mysqlConnection = require('../config/database'); // Note Model - จัดการการทำงานกับฐานข้อมูลสำหรับโน้ต class Note { // ดึงโน้ตทั้งหมด static getAll(callback) { mysqlConnection.query( `SELECT note.*, user.name as user_name, category.name as category_name FROM note LEFT JOIN user ON note.user_id = user.id LEFT JOIN category ON note.category_id = category.id`, (err, results) => { if (err) { return callback(err, null); } return callback(null, results); } ); } // สร้างโน้ตใหม่ // noteData ประกอบด้วย: title, content, userId, categoryId static create(noteData, callback) { mysqlConnection.query( "INSERT INTO note (title, content, user_id, category_id) VALUES (?,?,?,?)", [noteData.title, noteData.content, noteData.userId, noteData.categoryId], (err, result) => { if (err) { return callback(err, null); } return callback(null, result); } ); } // อัพเดทโน้ตที่มีอยู่แล้ว // id: รหัสของโน้ตที่ต้องการแก้ไข // noteData ประกอบด้วย: title, content, categoryId static update(id, noteData, callback) { mysqlConnection.query( "UPDATE note SET title = ?, content = ?, category_id = ? WHERE id = ?", [noteData.title, noteData.content, noteData.categoryId, id], (err, result) => { if (err) { return callback(err, null); } return callback(null, result); } ); } // ลบโน้ต // id: รหัสของโน้ตที่ต้องการลบ static delete(id, callback) { mysqlConnection.query( "DELETE FROM note WHERE id = ?", [id], (err, result) => { if (err) { return callback(err, null); } return callback(null, result); } ); } // ดึงโน้ตตาม user_id // userId: รหัสของผู้ใช้ที่ต้องการดูโน้ต static getByUserId(userId, callback) { mysqlConnection.query( `SELECT note.*, category.name as category_name FROM note LEFT JOIN category ON note.category_id = category.id WHERE note.user_id = ?`, [userId], (err, results) => { if (err) { return callback(err, null); } return callback(null, results); } ); } // Search notes by title or content static search(searchTerm, callback) { let sql = `SELECT note.*, user.name as user_name, category.name as category_name FROM note LEFT JOIN user ON note.user_id = user.id LEFT JOIN category ON note.category_id = category.id WHERE note.title LIKE ? OR note.content LIKE ? ORDER BY note.created_at DESC`; mysqlConnection.query(sql, [`%${searchTerm}%`, `%${searchTerm}%`], (err, results) => { if (err) { return callback(err, null); } callback(null, results); }); } } module.exports = Note;