const { addBaseUrlToImages } = require('../utils/imageHelper'); const About = require('../models/about'); // Get about data from MongoDB const getAboutData = async () => { const about = await About.findOne().sort({ updatedAt: -1 }); // Trả về object rỗng với cấu trúc cơ bản nếu không có dữ liệu if (!about) { return { banner: { image: '', title: '', text: '' }, about: { title: '', paragraphs: [], list_items: [], button: { text: '', url: '' }, image: '', quote: { mark_image: '', title: '', text: '', author: '' } }, values: { background_image: '', items: [] }, education: { images: { student1: '', student2: '' }, subtitle: '', title: '', text: '' }, advantages: { title: '', items: [] }, academic_board: { title: '', members: [] } }; } return about; }; // Display about management page exports.index = async (req, res) => { try { const data = await getAboutData(); res.render('admin/about', { title: 'About Management', data }); } catch (err) { console.error(err); req.flash('error_msg', 'Error loading about data'); res.redirect('/admin/dashboard'); } }; // Update about data exports.update = async (req, res) => { try { // Lấy document hiện tại từ MongoDB const currentData = await getAboutData(); // Danh sách các section cần cập nhật const sections = ['banner', 'about', 'values', 'education', 'advantages', 'academic_board']; const errors = []; let hasChanges = false; // Tạo đối tượng dữ liệu mới dựa trên dữ liệu hiện tại const updatedData = { ...currentData.toObject() }; // Xử lý từng section sections.forEach(section => { try { // Kiểm tra nếu section không được gửi lên if (!req.body[section]) { console.warn(`No data for section: ${section}`); return; } // Parse dữ liệu JSON từ form const newSectionData = JSON.parse(req.body[section]); // So sánh dữ liệu mới với dữ liệu hiện tại const currentSectionData = currentData[section]; const sectionHasChanges = JSON.stringify(newSectionData) !== JSON.stringify(currentSectionData); // Nếu có thay đổi, cập nhật vào đối tượng dữ liệu mới if (sectionHasChanges) { updatedData[section] = newSectionData; hasChanges = true; } } catch (error) { console.error(`Error processing section ${section}:`, error); errors.push(`Error processing ${section} data: ${error.message}`); } }); // Nếu có lỗi, thông báo và chuyển hướng if (errors.length > 0) { req.flash('error_msg', `Data processing error: ${errors[0]}`); return req.session.save(() => res.redirect('/admin/about')); } // Nếu không có thay đổi, thông báo và chuyển hướng if (!hasChanges) { req.flash('info_msg', 'No changes were made'); return req.session.save(() => res.redirect('/admin/about')); } try { // Cập nhật hoặc tạo mới document trong MongoDB if (currentData._id) { await About.findByIdAndUpdate(currentData._id, updatedData, { new: true }); } else { await About.create(updatedData); } // Success notification and redirect req.flash('success_msg', 'About data updated successfully'); return req.session.save(() => res.redirect('/admin/about')); } catch (dbError) { console.error('Database error:', dbError); req.flash('error_msg', `Database error: ${dbError.message || 'Unknown'}`); return req.session.save(() => res.redirect('/admin/about')); } } catch (err) { console.error('Update error:', err); req.flash('error_msg', `Update error: ${err.message || 'Unknown'}`); return req.session.save(() => res.redirect('/admin/about')); } }; // API to get about data exports.api = async (req, res) => { try { const aboutData = await getAboutData(); const baseUrl = process.env.BACKEND_URL || `${req.protocol}://${req.get('host')}`; const processedData = addBaseUrlToImages(aboutData, baseUrl); res.json(processedData); } catch (err) { console.error(err); res.status(500).json({ error: 'Error loading about data' }); } };