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

class QueueDetail {
    static async getQueueDetails(searchQuery = '') {

        const searchPattern = searchQuery ? `%${searchQuery}%` : '%'; 

        const query = `
            SELECT p.patient_id AS id,
                    CONCAT(p.fname, ' ', p.lname) AS patient_name,
                    t.treatment_name AS treatment,
                    p.phone AS phone,
                    'ไม่มี' AS treatment_history
            FROM queuedetail qd
            JOIN treatment t ON qd.treatment_id = t.treatment_id
            JOIN patient p ON qd.patient_id = p.patient_id
            WHERE CONCAT(p.fname, ' ', p.lname) LIKE ? OR p.patient_id LIKE ?;
        `;


        return new Promise((resolve, reject) => { 
            db.query(query, [searchPattern, searchPattern], (error, results) => {
                if (error) {
                    reject(error);
                }
                resolve(results);  // ส่งผลลัพธ์กลับไปยัง callback
            });
        });
    }

    static async getQueueDetailById(queuedetail_id) {
        const query = `
            SELECT qd.queuedetail_id, qd.date AS treatment_date,
                CONCAT(p.fname, ' ', p.lname) AS patient_name,
                t.treatment_name
            FROM queuedetail qd
            JOIN patient p ON qd.patient_id = p.patient_id
            JOIN treatment t ON qd.treatment_id = t.treatment_id
            WHERE qd.queuedetail_id = ?
        `;

        return new Promise((resolve, reject) => {
            db.query(query, [queuedetail_id], (error, results) => {
                if (error) {
                    reject(error);
                }
                if (results.length === 0) {
                    resolve(null);
                } else {
                    resolve(results[0]);
                }
            });
        });
    }
}

module.exports = QueueDetail;