const Safety = require("../models/safety");
const { addBaseUrlToImages } = require("../utils/imageHelper");

// Lấy dữ liệu Safety từ MongoDB
const getSafetyData = async () => {
	const safety = await Safety.findOne().sort({ updatedAt: -1 });
	if (!safety) {
		return null;
	}
	return safety.toObject();
};

// API endpoint cho frontend
exports.api = async (req, res) => {
	try {
		const safety = await getSafetyData();
		if (!safety) {
			return res.status(404).json({ error: "Safety data not found" });
		}
		const baseUrl = process.env.BACKEND_URL || `${req.protocol}://${req.get("host")}`;
		const processedData = addBaseUrlToImages(safety, baseUrl);
		res.json(processedData);
	} catch (err) {
		console.error("Safety API error:", err);
		res.status(500).json({ error: "Error loading safety data" });
	}
};

// Hiển thị danh sách Safety cho admin
exports.index = async (req, res) => {
	try {
		const items = await Safety.find().sort({ updatedAt: -1 }).limit(10);
		// Lấy bản ghi mới nhất hoặc object rỗng nếu chưa có dữ liệu
		const latest = items && items.length > 0 ? items[0] : null;
		const data = latest ? (latest.toObject ? latest.toObject() : latest) : {
			hero: { title: "", banner: "" },
			approach: {},
			approachImgs: [],
			approachStats: [],
			approachFeatures: [],
			approachCards: [],
			philosophy: {},
			philosophyCards: [],
			security: {},
			securityCards: []
		};
		res.render("admin/safety/index", {
			layout: "layouts/main",
			title: "Safety Management",
			items,
			data,
			frontendUrl: process.env.FRONTEND_URL || req.protocol + "://" + req.get("host"),
			currentPath: req.path,
			user: req.session.user,
		});
	} catch (err) {
		console.error(err);
		req.flash("error_msg", "Error loading Safety data");
		res.redirect("/admin/dashboard");
	}
};

// Hiển thị form tạo mới Safety
exports.createForm = async (req, res) => {
	try {
		res.render("admin/safety/create", {
			layout: "layouts/main",
			title: "Create Safety",
			currentPath: req.path,
			user: req.session.user,
		});
	} catch (err) {
		console.error(err);
		req.flash("error_msg", "Error loading create form");
		res.redirect("/admin/safety");
	}
};

// Tạo mới Safety
exports.create = async (req, res) => {
	try {
		const safetyData = req.body; // Tùy chỉnh parse nếu cần
		const newSafety = new Safety(safetyData);
		await newSafety.save();
		req.flash("success_msg", "Safety created successfully");
		res.redirect("/admin/safety");
	} catch (err) {
		console.error("Create error:", err);
		req.flash("error_msg", `Create error: ${err.message || "Unknown"}`);
		res.redirect("/admin/safety/create");
	}
};

// Cập nhật Safety
exports.update = async (req, res) => {
	try {
		const { hero, approach, philosophy, security } = req.body;

		// Parse JSON strings
		const parseJson = (data) => {
			if (!data) return null;
			if (typeof data === "string") {
				try {
					return JSON.parse(data);
				} catch (e) {
					return null;
				}
			}
			return data;
		};

		const heroData = parseJson(hero);
		const approachData = parseJson(approach);
		const philosophyData = parseJson(philosophy);
		const securityData = parseJson(security);

		// Tìm hoặc tạo safety record
		const items = await Safety.find().sort({ updatedAt: -1 }).limit(1);
		let safety = items && items.length > 0 ? items[0] : null;

		if (!safety) {
			// Tạo mới
			safety = new Safety({
				hero: heroData || { title: "", banner: "" },
				approach: approachData || {},
				philosophy: philosophyData || {},
				security: securityData || {}
			});
		} else {
			// Cập nhật
			if (heroData) safety.hero = heroData;
			if (approachData) safety.approach = approachData;
			if (philosophyData) safety.philosophy = philosophyData;
			if (securityData) safety.security = securityData;
		}

		await safety.save();

		req.flash("success_msg", "Safety updated successfully");
		res.redirect("/admin/safety");
	} catch (err) {
		console.error("Update error:", err);
		req.flash("error_msg", `Update error: ${err.message || "Unknown"}`);
		res.redirect("/admin/safety");
	}
};

// Xóa Safety
exports.delete = async (req, res) => {
	try {
		const safety = await Safety.findById(req.params.id);
		if (!safety) {
			req.flash("error_msg", "Safety record not found");
			return res.redirect("/admin/safety");
		}
		await Safety.findByIdAndDelete(req.params.id);
		req.flash("success_msg", "Safety record deleted successfully");
		res.redirect("/admin/safety");
	} catch (err) {
		console.error("Delete error:", err);
		req.flash("error_msg", `Delete error: ${err.message || "Unknown"}`);
		res.redirect("/admin/safety");
	}
};
