const db = require("../config/db");

// 📌 Fetch All Questions
exports.getQuestions = async (req, res) => {
    try {
        const [results] = await db.execute("SELECT * FROM questions");
        res.json(results);
    } catch (err) {
        console.error("❌ Error fetching questions:", err);
        res.status(500).json({ error: "Database error", details: err });
    }
};

// 📌 Fetch Single Question
exports.getQuestionById = async (req, res) => {
    try {
        const { id } = req.params;
        const [result] = await db.execute("SELECT * FROM questions WHERE id = ?", [id]);

        if (result.length === 0) {
            return res.status(404).json({ message: "❌ Question not found" });
        }

        res.json(result[0]);
    } catch (err) {
        console.error("❌ Error fetching question:", err);
        res.status(500).json({ error: "Database error", details: err });
    }
};

// 📌 Submit a New Question
exports.submitQuestion = async (req, res) => {
    try {
        const { user_id, session_id, question_text, question_text_ar } = req.body;

        await db.execute(
            "INSERT INTO questions (user_id, session_id, question_text, question_text_ar, status) VALUES (?, ?, ?, ?, 'pending')",
            [user_id, session_id, question_text, question_text_ar]
        );

        res.json({ message: "✅ Question submitted successfully!" });
    } catch (err) {
        console.error("❌ Error submitting question:", err);
        res.status(500).json({ error: "Database error", details: err });
    }
};

// 📌 Approve a Question
exports.approveQuestion = async (req, res) => {
    try {
        const { id } = req.params;

        await db.execute("UPDATE questions SET status = 'approved' WHERE id = ?", [id]);

        res.json({ message: "✅ Question approved successfully!" });
    } catch (err) {
        console.error("❌ Error approving question:", err);
        res.status(500).json({ error: "Database error", details: err });
    }
};

// 📌 Reject a Question
exports.rejectQuestion = async (req, res) => {
    try {
        const { id } = req.params;

        await db.execute("UPDATE questions SET status = 'rejected' WHERE id = ?", [id]);

        res.json({ message: "✅ Question rejected successfully!" });
    } catch (err) {
        console.error("❌ Error rejecting question:", err);
        res.status(500).json({ error: "Database error", details: err });
    }
};

// 📌 Fetch Approved Questions for a Session
exports.getSessionQuestions = async (req, res) => {
    try {
        const { session_id } = req.params;
        const [results] = await db.execute(
            "SELECT * FROM questions WHERE session_id = ? AND status = 'approved'",
            [session_id]
        );

        res.json(results);
    } catch (err) {
        console.error("❌ Error fetching session questions:", err);
        res.status(500).json({ error: "Database error", details: err });
    }
};

// 📌 Update Question (Text, Arabic Text, Session ID, and Status)
exports.updateQuestion = async (req, res) => {
    try {
        const { id } = req.params;
        const { user_id, session_id, question_text, question_text_ar, status } = req.body;

        // 🔍 Check if the question exists
        const [existing] = await db.execute("SELECT * FROM questions WHERE id = ?", [id]);
        if (existing.length === 0) {
            return res.status(404).json({ message: "❌ Question not found" });
        }

        // 🔄 Update question details including status
        await db.execute(
            "UPDATE questions SET user_id = ?, session_id = ?, question_text = ?, question_text_ar = ?, status = ? WHERE id = ?",
            [user_id, session_id, question_text, question_text_ar, status, id]  // ✅ Include `status`
        );

        res.json({ message: "✅ Question updated successfully!" });
    } catch (err) {
        console.error("❌ Error updating question:", err);
        res.status(500).json({ error: "Database error", details: err });
    }
};