const QueueDetail = require('../models/QueueDetail');
const TreatmentHistory = require('../models/TreatmentHistory')


class DentistController {
    //แสดงหน้า my treatment
    static async showQueueDetailsById(req, res) {
        const searchQuery = req.query.search || ''; // รับคำค้นหาจาก url query
        try{
            const queueDetails = await QueueDetail.getQueueDetails(searchQuery); // ส่งคำค้นหาที่ได้ไปยังเมธอดใน Model

            res.render('treatment', { queueDetails }); // แสดงหน้ารักษาพร้อมผลลัพธ์ที่กรองแล้ว
        } catch (error) {
            console.error("Error fetching queue details:", error.message);
            res.status(500).send("Error fetching queue details");
        }
    }
    


    //แสดงประวัติการรักษา
    static async showTreatmentHistory(req, res) {
        const patientId = req.params.id;

        if (!patientId) {
            console.error("Patient ID is missing or invalid.");
            return res.status(400).send("Invalid Patient ID.");
        }

        try {
            //ดึงข้อมูลจากตาราง treatmenthistoryและค้นหา
            const treatmentHistory = await TreatmentHistory.getTreatmentHistory(patientId);

            if (!treatmentHistory || treatmentHistory.length === 0) {
                console.log('No treatment history found.');
                return res.render('treatmenthistory', { 
                    message: "ไม่พบการรักษา", 
                    patientId,
                    treatmentHistory:[] // สำหรับประวัติการรักษาเมื่อไม่พบข้อมูล
                });
            }

            res.render('treatmenthistory', { 
                treatmentHistory, 
                patientId,
                message: null // ไม่มีข้อความเมื่อมีข้อมูล
            });
        } catch (error) {
            console.error("Error fetching treatment history:", error.message);
            res.status(500).send("Error fetching treatment history");
        }
    }



    static async showAddTreatmentForm(req, res) {
        const queuedetail_id = req.params.queuedetail_id;
    
        // ตรวจสอบว่า queuedetail_id ถูกต้องหรือไม่
        if (!queuedetail_id) {
            console.error("queuedetail_id is missing or invalid.");
            return res.status(400).send("Invalid queuedetail_id.");
        }
    
        try {
            // ดึงข้อมูลจาก queuedetail โดยใช้ queuedetail_id
            const queueDetail = await QueueDetail.getQueueDetailById(queuedetail_id);
    
            if (!queueDetail) {
                return res.status(404).send('ไม่พบข้อมูลการรักษา');
            }
    
            // ใช้ patient_id ที่ได้จาก queueDetail
            const patientId = queueDetail.patient_id;
            if (!patientId) {
                console.error("Patient ID is missing.");
                return res.status(400).send("Patient ID is missing.");
            }
    
            // ตรวจสอบว่า `patient_id` นี้มีการจองใหม่ที่ยังไม่ได้บันทึกการรักษาหรือไม่
            const treatmentHistory = await TreatmentHistory.getTreatmentHistory(patientId);
    
            // ถ้าการบันทึกของ queuedetail_id อยู่ใน treatmentHistory
            if (treatmentHistory && treatmentHistory.length > 0) {
                // ตรวจสอบการจองล่าสุดจาก patient_id
                const newQueueDetail = await QueueDetail.getQueueDetailsByPatientId(patientId);

                if (!newQueueDetail) {
                    // ถ้าไม่มีการจองใหม่
                    return res.render('addtreatmenthis', {
                        message: 'ไม่พบการจองใหม่สำหรับผู้ป่วยนี้',
                        patient_id: patientId,
                    });
                }

                // เปรียบเทียบว่า newQueueDetail ถูกบันทึกใน treatmentHistory หรือไม่
                const isAlreadyBooked = treatmentHistory.some(th => 
                    th.queuedetail_id === newQueueDetail.queuedetail_id 
                );

                if (isAlreadyBooked) {
                    // ถ้าการจองนี้ถูกบันทึกแล้วใน `treatmenthistory`
                    return res.render('addtreatmenthis', {
                        message: 'ไม่พบการจองใหม่สำหรับผู้ป่วยนี้',
                        patient_id: patientId,
                    });
                }

                // ถ้ามีการจองใหม่ที่ยังไม่ได้บันทึก ให้แสดงข้อมูลการจอง
                res.render('addtreatmenthis', {
                    queuedetail_id: newQueueDetail.queuedetail_id,
                    treatment_date: newQueueDetail.treatment_date,
                    patient_name: newQueueDetail.patient_name,
                    treatment_name: newQueueDetail.treatment_name,
                });
            } else {
                // หากไม่มีการจองใหม่ที่ยังไม่ได้บันทึกการรักษา
                return res.render('addtreatmenthis', {
                    message: 'ไม่พบการจองใหม่สำหรับผู้ป่วยนี้',
                    patient_id: patientId,
                });
            }
    
        } catch (error) {
            console.error("Error fetching queue details:", error.message);
            res.status(500).send("Error fetching queue details");
        }
    }
    
    

    // เพิ่มประวัติการรักษาใหม่
    static async addTreatmentHistory(req, res) {
        const { queuedetail_id, dentist_name, tm_details, followUpdate } = req.body;

        try {
            // เรียกใช้ฟังก์ชันใน Model เพื่อเพิ่มข้อมูลลงในฐานข้อมูล
            await TreatmentHistory.addTreatmentHistory(queuedetail_id, dentist_name, tm_details, followUpdate);

            res.redirect('/dentist/treatment');
        } catch (error) {
            console.error("Error saving treatment history:", error.message);
            res.status(500).send("Error saving treatment history");
        }
    }



    //แสดงฟอร์มแก้ไขข้อมูล
    static async showEditTreatmentForm(req, res) {
        const treatmenthistoryId = req.params.id;
    
        try {
            const treatmentHistory = await TreatmentHistory.getTreatmentHistoryById(treatmenthistoryId); // ดึงข้อมูลการรักษาตาม ID
            if (!treatmentHistory) {
                return res.status(404).send('ไม่พบประวัติการรักษา');
            }
    
            // ส่งข้อมูลไปยังหน้า EJS เพื่อให้แสดงฟอร์มแก้ไข
            res.render('edittreatmenthis', { treatmentHistory });
        } catch (error) {
            console.error("Error fetching treatment history for edit:", error.message);
            res.status(500).send("Error fetching treatment history for edit");
        }
    }



    //อัปเดตข้อมูล
    static async updateTreatmentHistory(req, res) {
        const { treatmenthistory_id, dentist_name, tm_details, followUpdate } = req.body;
        
        console.log("Received data:", req.body); // แสดงค่าที่ได้รับจากฟอร์ม

        try {
            // เรียกใช้ฟังก์ชัน updateTreatmentHistory ใน Model
            await TreatmentHistory.updateTreatmentHistory(treatmenthistory_id, dentist_name, tm_details, followUpdate);

            // ดึงข้อมูล patient_id จาก treatmenthistory_id
            const treatmentHistory = await TreatmentHistory.getTreatmentHistoryById(treatmenthistory_id);
            const patient_id = treatmentHistory.patient_id;  // ดึง patient_id จากข้อมูลการรักษาที่อัปเดต
    
            // หากอัปเดตสำเร็จ ให้รีไดเร็กต์ไปที่หน้าประวัติการรักษา
            res.redirect(`/dentist/treatmenthistory/${patient_id}`);
        } catch (error) {
            console.error("Error updating treatment history:", error.message);
            res.status(500).send("Error updating treatment history");
        }
    }


    
    // ลบประวัติการรักษา
    static async deleteTreatmentHistory(req, res) {
        const treatmenthistoryId = req.params.id;

        try {
            // ดึงข้อมูล patient_id จาก treatmenthistory_id
            const treatmentHistory = await TreatmentHistory.getTreatmentHistoryById(treatmenthistoryId);
            const patient_id = treatmentHistory.patient_id;  // ดึง patient_id จากข้อมูลการรักษาที่ถูกลบ
            
            // เรียกใช้ฟังก์ชันใน Model เพื่อทำการลบข้อมูลจากฐานข้อมูล
            await TreatmentHistory.deleteTreatmentHistory(treatmenthistoryId);

            // รีไดเร็กต์ไปยังหน้าประวัติการรักษาของผู้ป่วยนั้น
            res.redirect(`/dentist/treatmenthistory/${patient_id}`);
        } catch (error) {
            console.error("Error deleting treatment history:", error.message);
            res.status(500).send("Error deleting treatment history");
        }
    }
    
    
}
module.exports = DentistController;