import { title } from "process";

const _ = require('lodash');
require('dotenv').config()
const mongoose = require("mongoose");
const { User } = require('../../models/user');
const { Role } = require('../../models/role');
const { Category } = require('../../models/admin/category');
const { apiResponse } = require("../../core/response/response")
const { BookingAppointment } = require('../../models/booking')
const { FAQ } = require('../../models/admin/faq')
const { Contact } = require('../../models/admin/contact')
const { Blog } = require('../../models/admin/blog')
const { Magazine } = require('../../models/admin/magazine')
const { Language } = require('../../models/admin/language')
const { dateFormat } = require('../../core/utilities/commonService');
const { SUCCESS, REDIRECTION, CLIENT_ERROR, SERVER_ERROR } = require("../../core/response/statusCode")
const { ERROR_MSG, SUCCESS_MSG } = require("../../core/response/messages")
const { sendEmail } = require('../../core/utilities/emailService');
const { addAdminTemplate, activateUserAccountTemplate, deactivateUserAccountTemplate } = require('../../core/email-templates/email-admin');
export { };

// customer count
exports.doctorCount = async (req, res) => {
    try {
        let userRole = await Role.findOne({ title: 'doctor' })
        let data = await User.countDocuments({ user_role: new mongoose.Types.ObjectId(userRole._id),is_account_active: true,is_completed:true,is_deleted:false })
        return apiResponse(res, false, [], '', SUCCESS.OK, 1, { count: data }, req)

    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR`], SERVER_ERROR.internalServerError, 0, [], req)
    }

}

// freelancer count
exports.patientCount = async (req, res) => {
    try {
        let userRole = await Role.findOne({ title: 'patient' })
        let data = await User.countDocuments({ user_role: new mongoose.Types.ObjectId(userRole._id),is_account_active:true,is_completed:true,is_deleted:false })
        return apiResponse(res, false, [], '', SUCCESS.OK, 1, { count: data }, req)

    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR`], SERVER_ERROR.internalServerError, 0, [], req)
    }

}

// hospital count
exports.hospitalCount = async (req, res) => {
    try {
        let userRole = await Role.findOne({ title: 'hospital' })
        let data = await User.countDocuments({ user_role: new mongoose.Types.ObjectId(userRole._id),is_completed:true,is_deleted:false })
        return apiResponse(res, false, [], '', SUCCESS.OK, 1, { count: data }, req)

    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR`], SERVER_ERROR.internalServerError, 0, [], req)
    }

}

// appointment count
exports.appointmentCount = async (req, res) => {
    try {
        // let userRole = await Role.findOne({ title: 'hospital' })
        let data = await BookingAppointment.countDocuments({is_deleted: false})
        return apiResponse(res, false, [], '', SUCCESS.OK, 1, { count: data }, req)

    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR`], SERVER_ERROR.internalServerError, 0, [], req)
    }

}

// total category
exports.categoryCount = async (req, res) => {
    try {
        // let userRole = await Role.findOne({ title: 'hospital' })
        let data = await Category.countDocuments({ is_deleted: false, is_active: true })
        return apiResponse(res, false, [], '', SUCCESS.OK, 1, { count: data }, req)

    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR`], SERVER_ERROR.internalServerError, 0, [], req)
    }

}

// magzine
exports.magazineCount = async (req, res) => {
    try {
        // let userRole = await Role.findOne({ title: 'hospital' })
        let data = await Magazine.countDocuments({ is_deleted: false, is_active: true })
        return apiResponse(res, false, [], '', SUCCESS.OK, 1, { count: data }, req)

    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR`], SERVER_ERROR.internalServerError, 0, [], req)
    }

}

// langudge
exports.languageCount = async (req, res) => {
    try {
        // let userRole = await Role.findOne({ title: 'hospital' })
        let data = await Language.countDocuments({ is_deleted: false, is_active: true })
        return apiResponse(res, false, [], '', SUCCESS.OK, 1, { count: data }, req)

    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR`], SERVER_ERROR.internalServerError, 0, [], req)
    }

}
// faq count
exports.faqCount = async (req, res) => {
    try {
        let data = await FAQ.countDocuments({})
        return apiResponse(res, false, [], '', SUCCESS.OK, 1, { count: data }, req)

    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR`], SERVER_ERROR.internalServerError, 0, [], req)
    }

}

// help & assistance

exports.contactUs = async (req, res) => {
    try {
        let data = await Contact.countDocuments({})
        return apiResponse(res, false, [], '', SUCCESS.OK, 1, { count: data }, req)

    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR`], SERVER_ERROR.internalServerError, 0, [], req)
    }

}





// // blog count
exports.blogCount = async (req, res) => {
    try {
        let data = await Blog.countDocuments({})
        return apiResponse(res, false, [], '', SUCCESS.OK, 1, { count: data }, req)

    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR`], SERVER_ERROR.internalServerError, 0, [], req)
    }

}

// filting top 10 users
exports.topTenUserListing = async (req, res) => {
    const { user_role } = req.body;
    let userRole = await Role.findOne({ title: user_role })
    let filteredQuery = {
        is_deleted: false,
        user_account_status: "APPROVED",
        is_completed: true,
        user_role: new mongoose.Types.ObjectId(userRole._id)
    }
    const [data, count] = await Promise.all([
        User.aggregate([
            { $match: filteredQuery },
            { $project: { _id: 1, is_completed: 1, first_name: 1, last_digit_phone: 1, last_name: 1, phone: 1, email: 1, dob: 1, gender: 1, phone_number: 1, profile_pic: 1, street_address: 1, country: 1, city: 1, state: 1, zip_code: 1, address: 1, location: 1, area_of_work_array: 1, category_names: 1, createdAt: 1 } },
            { $sort: { createdAt: -1 } }, // Sort by updatedAt in descending order
            { $limit: 10 }
        ]),
        await User.countDocuments(filteredQuery)
    ])



    return apiResponse(res, false, [], '', SUCCESS.OK, data.length, data, req);
}

// appointment listing
// exports.topAppintmentListing = async (req, res) => {
//     try {
//         const { status } = req.body
//         let filteredQuery = {}
//         filteredQuery['is_deleted'] = false
//         if (status) {
//             filteredQuery['status'] = (status == "All") ? { $in: ['PENDING', 'APPROVED', 'REJECTED'] } : "ACTIVE"
//         }
//         let page = req.query.page ? parseInt(req.query.page) - 1 : 0;
//         let limit = req.query.limit ? parseInt(req.query.limit) : 10
//         let skip = (page) * limit;
//         const [data, count] = await Promise.all([
//             BookingAppointment.aggregate([
//                 { $match: filteredQuery },
//                 { $sort: { createdAt: -1 } },
//                 { $skip: skip },
//                 { $limit: limit },

//                 {
//                     $lookup: {
//                         from: "users",
//                         as: "patient",
//                         let: { patient_id: "$patient_id" },
//                         pipeline: [
//                             {
//                                 $match: {
//                                     $and: [
//                                         {
//                                             $expr: { $eq: ["$$patient_id", "$_id"] },
//                                         },
//                                         // filteredQueryUsersTable
//                                     ]
//                                 },
//                             },
//                             { $project: { _id: 1, first_name: 1, last_name: 1, gender: 1, profile_pic: 1, category_names: 1 } },

//                         ],
//                     },
//                 },
//                 {
//                     $unwind: {
//                         path: '$patient',
//                         preserveNullAndEmptyArrays: true,
//                     },
//                 },
//                 {
//                     $lookup: {
//                         from: "users",
//                         as: "hospitalDoctor",
//                         let: { hospital_doctor_id: "$hospital_doctor_id" },
//                         pipeline: [
//                             {
//                                 $match: {
//                                     $and: [
//                                         {
//                                             $expr: { $eq: ["$$hospital_doctor_id", "$_id"] },
//                                         },
//                                         // filteredQueryUsersTable
//                                     ]
//                                 },
//                             },
//                             { $project: { _id: 1, first_name: 1, last_name: 1, gender: 1, profile_pic: 1, category_names: 1 } },

//                         ],
//                     },
//                 },
//                 {
//                     $unwind: {
//                         path: '$hospitalDoctor',
//                         preserveNullAndEmptyArrays: true,
//                     },
//                 },

//                 {
//                     $lookup: {
//                         from: "categories",
//                         as: "bookingSpeciality",
//                         let: { booking_speciality: "$booking_speciality" },
//                         pipeline: [
//                             {
//                                 $match: {
//                                     $and: [
//                                         {
//                                             $expr: { $eq: ["$$booking_speciality", "$_id"] },
//                                         },
//                                         // filteredQueryUsersTable
//                                     ]
//                                 },
//                             },
//                             { $project: { _id: 1, title_en: 1, title_ar: 1, title_fr: 1, image: 1,  } },

//                         ],
//                     },
//                 },
//                 {
//                     $unwind: {
//                         path: '$bookingSpeciality',
//                         preserveNullAndEmptyArrays: true,
//                     },
//                 },

//                 {
//                     $lookup: {
//                         from: "roles",
//                         as: "bookingType",
//                         let: { booking_role_type: "$booking_role_type" },
//                         pipeline: [
//                             {
//                                 $match: {
//                                     $and: [
//                                         {
//                                             $expr: { $eq: ["$$booking_role_type", "$_id"] },
//                                         },
//                                         // filteredQueryUsersTable
//                                     ]
//                                 },
//                             },
//                             { $project: { _id: 1, title: 1, } },

//                         ],
//                     },
//                 },
//                 {
//                     $unwind: {
//                         path: '$bookingType',
//                         preserveNullAndEmptyArrays: true,
//                     },
//                 },


//                 { $project: { _id: 1, patient_id: 1, hospital_doctor_id: 1, booking_date: 1, slot: 1, booking_role_type: 1, booking_speciality: 1, document_file: 1, status: 1, rejected_reason: 1, createdAt: 1,  patient: "$patient", applyJobsCount: { $size: "$applyJobsCount" },hospitalDoctor:"$hospitalDoctor",bookingType:"$bookingType" } },
//             ]),
//             await BookingAppointment.countDocuments(filteredQuery),

//         ])

//         return apiResponse(res, false, [], '', SUCCESS.OK, count, data, req)
//     } catch (error) {
//         return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR`], SERVER_ERROR.internalServerError, 0, [], req)
//     }

// }
exports.topAppintmentListing = async (req, res) => {
    var title_lang = 'en';
    const lang = req.headers["accept-language"] || 'en';

    let startDate = new Date();
    let endDate = new Date(startDate.getFullYear(), startDate.getMonth() + 1, 0);



    try {
        const { patient_name, doctor_hospital_name, list_type, custom_booking_date, custom_slot } = req.body;

        let filteredQuery = {
        }

        let concatFilter = {

        }

        let filteredQueryWithRescheduled = {
        }

        let patient_name_regex = new RegExp(patient_name, 'i');
        let doctor_hospital_name_regex = new RegExp(doctor_hospital_name, 'i');
        let custom_slot_regex = new RegExp(custom_slot, 'i');

        let booking_date = new Date(dateFormat(custom_booking_date, 'yyyy-MM-dd'));
        booking_date.setDate(booking_date.getDate() + 1)


        const filter_createdAtBooking = (custom_booking_date && custom_booking_date != 'undefined') ? { booking_date: { $gte: new Date(dateFormat(custom_booking_date, 'yyyy-MM-dd')), $lt: new Date(dateFormat(booking_date, 'yyyy-MM-dd')) } } : {};

        const filter_createdAtRescheduled = (custom_booking_date && custom_booking_date != 'undefined') ? { reschedule_date: { $gte: new Date(dateFormat(custom_booking_date, 'yyyy-MM-dd')), $lt: new Date(dateFormat(booking_date, 'yyyy-MM-dd')) } } : {};

        const filter_custom_slot = (custom_slot && custom_slot != 'undefined') ? { slot: custom_slot_regex } : {};
        const filter_custom_reschedule_slot = (custom_slot && custom_slot != 'undefined') ? { reschedule_slot: custom_slot_regex } : {};



        filteredQuery = { ...filter_createdAtBooking, ...filter_custom_slot }
        filteredQueryWithRescheduled = { ...filter_createdAtRescheduled, ...filter_custom_reschedule_slot }




        // if (list_type == "All") {

        //     //Don't need to check status in all case
        // } else if (list_type == "UPCOMING") {

        //     filteredQuery['booking_date'] = { $gte: startDate, $lt: endDate }
        //     filteredQuery['status'] = "APPROVED";

        //     filteredQueryWithRescheduled['reschedule_date'] = { $gte: startDate, $lt: endDate }
        //     filteredQueryWithRescheduled['status'] = "APPROVED";
        // } else {
        //     // PENDING | APPROVED | REJECTED | COMPLETED
        //     filteredQuery['status'] = list_type;
        //     filteredQueryWithRescheduled['status'] = list_type;
        // }




        let matchCondition = {
            $or: [
                filteredQuery,
                filteredQueryWithRescheduled
            ]
        }



        let page, limit: number;
        page = req.query.page ? parseInt(req.query.page) - 1 : 0;
        limit = req.query.limit ? parseInt(req.query.limit) : 10;
        let skip = parseInt(page) * limit;





        const filter_patient_name = (patient_name && patient_name != 'undefined') ? { patient_name: patient_name_regex } : {};

        const filter_doctor_hospital_name = (doctor_hospital_name && doctor_hospital_name != 'undefined') ? { doctor_hospital_name: doctor_hospital_name_regex } : {};

        concatFilter = { ...filter_patient_name, ...filter_doctor_hospital_name }

        const [data, count, pending_count] = await Promise.all([
            BookingAppointment.aggregate([
                { $match: matchCondition },
                { $sort: { createdAt: -1 } },
                { $skip: skip },
                { $limit: limit },
                {
                    $lookup: {
                        from: "users",
                        as: "patient",
                        let: { patient_id: "$patient_id" },
                        pipeline: [
                            {
                                $match: {
                                    $and: [
                                        {
                                            $expr: { $eq: ["$$patient_id", "$_id"] },
                                        },
                                        // filteredQueryUsersTable
                                    ]
                                },
                            },
                            {
                                $project: {
                                    _id: 1,
                                    first_name: 1,
                                    last_name: 1,
                                    email: 1,
                                    phone_number: 1,
                                    social_security_number: 1,
                                    dob: 1,
                                    profile_pic: 1,
                                    qualification: 1,
                                    clinic_contact: 1,
                                    additional_qualification: 1,
                                    year_of_practice: 1, country: 1,
                                    state: 1,
                                    gender: 1,
                                    street_address: 1,
                                    zip_code: 1,
                                    concat_name: {
                                        $concat: [
                                            {
                                                $cond: {
                                                    if: {
                                                        $eq: ['$first_name', null]
                                                    },
                                                    then: '',  // Replace with your default value or an empty string
                                                    else: '$first_name'
                                                }
                                            },
                                            ' ',
                                            {
                                                $cond: {
                                                    if: {
                                                        $eq: ['$last_name', null]
                                                    },
                                                    then: '',  // Replace with your default value or an empty string
                                                    else: '$last_name'
                                                }
                                            }
                                        ]
                                    }
                                }
                            },

                        ],
                    },
                },
                { "$unwind": "$patient" },
                {
                    $lookup: {
                        from: "categories",
                        as: "booking_speciality",
                        let: { booking_speciality: "$booking_speciality" },
                        pipeline: [
                            {
                                $match: {
                                    $expr: { $eq: ["$$booking_speciality", "$_id"] },
                                }
                            },
                            {
                                $project: {
                                    _id: 1,
                                    title_en: 1,
                                    title_ar: 1,
                                    title_fr: 1,
                                    image: 1
                                }
                            }
                        ],
                    },

                },
                {
                    $unwind: {
                        path: '$booking_speciality',
                        preserveNullAndEmptyArrays: true,
                    },
                },
                {
                    $lookup: {
                        from: "users",
                        as: "doctor_hospital",
                        let: { hospital_doctor_id: "$hospital_doctor_id" },
                        pipeline: [
                            {
                                $match: {

                                    $expr: { $eq: ["$$hospital_doctor_id", "$_id"] },
                                }
                            },
                            {
                                $lookup: {
                                    from: "roles",
                                    as: "userRole",
                                    let: { userRole_id: "$user_role" },
                                    pipeline: [
                                        {
                                            $match: {
                                                $and: [
                                                    {
                                                        $expr: { $eq: ["$$userRole_id", "$_id"] },
                                                    },
                                                    // filteredQueryUsersTable
                                                ]
                                            },
                                        },
                                        { $project: { _id: 1, title: 1 } },

                                    ],
                                },
                            },
                            { "$unwind": "$userRole" },
                            {
                                $lookup: {
                                    from: "categories",
                                    as: "selected_speciality",
                                    let: { primary_specialty: "$primary_specialty" },
                                    pipeline: [
                                        {
                                            $match: {
                                                //$expr: { $in: ["$_id", "$$primary_specialty"] }
                                                "$expr": {
                                                    "$cond": {
                                                        "if": { "$isArray": "$$primary_specialty" },
                                                        "then": { "$in": ["$_id", "$$primary_specialty"] },
                                                        "else": { "$eq": ["$primary_specialty", "$_id"] }
                                                    }
                                                }
                                            }
                                        },
                                        {
                                            $project: {
                                                _id: 1,
                                                title_ar: 1,
                                                title_en: 1,
                                                title_fr: 1,
                                                image: 1
                                            }
                                        }
                                    ],
                                },

                            },
                            {
                                $lookup: {
                                    from: "languages",
                                    as: "selected_language",
                                    let: { spoken_language: "$spoken_language" },
                                    pipeline: [
                                        {
                                            $match: {
                                                "$expr": {
                                                    "$cond": {
                                                        "if": { "$isArray": "$$spoken_language" },
                                                        "then": { "$in": ["$_id", "$$spoken_language"] },
                                                        "else": { "$eq": ["$spoken_language", "$_id"] }
                                                    }
                                                }
                                            }
                                        },
                                        {
                                            $project: {
                                                _id: 1,
                                                title: 1
                                            }
                                        }
                                    ],
                                },

                            },

                            {
                                $project: {
                                    _id: 1,
                                    first_name: 1,
                                    last_name: 1,
                                    email: 1,
                                    phone_number: 1,
                                    social_security_number: 1,
                                    dob: 1,
                                    qualification: 1,
                                    additional_qualification: 1,
                                    year_of_practice: 1, country: 1,
                                    city: 1,
                                    clinic_contact: 1,
                                    state: 1,
                                    gender: 1,
                                    profile_pic: 1,
                                    street_address: 1,
                                    spoken_language: 1,
                                    zip_code: 1, branch_of_medicines: 1,
                                    additional_specialty: 1,
                                    selected_speciality: "$selected_speciality",
                                    selected_language: "$selected_language",
                                    user_role: "$userRole.title",
                                    clinic_name: 1,
                                    clinic_open_time: 1,
                                    clinic_close_time: 1,
                                    clinic_timing: 1,
                                    is_fulltime: 1,
                                    doctor_hospital_name: {

                                        $cond: {
                                            if: {
                                                $eq: ['$userRole.title', 'doctor']
                                            },
                                            then: {
                                                $concat: [
                                                    {
                                                        $cond: {
                                                            if: {
                                                                $eq: ['$first_name', null]
                                                            },
                                                            then: '',  // Replace with your default value or an empty string
                                                            else: '$first_name'
                                                        }
                                                    },
                                                    ' ',
                                                    {
                                                        $cond: {
                                                            if: {
                                                                $eq: ['$last_name', null]
                                                            },
                                                            then: '',  // Replace with your default value or an empty string
                                                            else: '$last_name'
                                                        }
                                                    }
                                                ]
                                            },
                                            else: '$clinic_name'
                                        }


                                    }
                                }
                            }
                        ]
                    }
                },

                {
                    $unwind: {
                        path: '$doctor_hospital',
                        preserveNullAndEmptyArrays: true,
                    },
                },

                { $project: { _id: 1, booking_id: 1, slot: 1, booking_date: 1, status: 1, createdAt: 1, rejected_reason: 1, doctor_hospital: "$doctor_hospital", document_file_from_doctor: 1, rejected_by: 1, booking_speciality: "$booking_speciality", reschedule_date: 1, reschedule_slot: 1, reschedule_by: 1, patient: "$patient", patient_name: "$patient.concat_name", doctor_hospital_name: "$doctor_hospital.doctor_hospital_name" } },
                {
                    $match: concatFilter
                },



            ]),
            BookingAppointment.countDocuments(matchCondition),
            BookingAppointment.countDocuments({
                status: "PENDING"
            })
        ]);

        return res.json({ count: count, pending_count: pending_count, data: data, errors: [], is_error: false, message: "", responseCode: 200 })
        //   return apiResponse(res, false, [], '', SUCCESS.OK, count, pending_count, data, req)



    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR-${lang}`], SERVER_ERROR.internalServerError, 0, [], req)
    }
}
// gigs listing
// exports.topGigsListing = async (req, res) => {
//     try {
//         const { status } = req.body
//         let filteredQuery = {}
//         filteredQuery['is_deleted'] = false
//         filteredQuery['is_active'] = true
//         let page = req.query.page ? parseInt(req.query.page) - 1 : 0;
//         let limit = req.query.limit ? parseInt(req.query.limit) : 10
//         let skip = (page) * limit;
//         const [data, count] = await Promise.all([
//             GIGS.aggregate([
//                 { $match: filteredQuery },
//                 { $sort: { createdAt: -1 } },
//                 { $skip: skip },
//                 { $limit: limit },

//                 {
//                     $lookup: {
//                         from: "users",
//                         as: "freelancer",
//                         let: { user_id: "$user_id" },
//                         pipeline: [
//                             {
//                                 $match: {
//                                     $and: [
//                                         {
//                                             $expr: { $eq: ["$$user_id", "$_id"] },
//                                         },
//                                         // filteredQueryUsersTable
//                                     ]
//                                 },
//                             },
//                             { $project: { _id: 1, first_name: 1, last_name: 1, gender: 1, profile_pic: 1, category_names: 1 } },

//                         ],
//                     },
//                 },
//                 {
//                     $unwind: {
//                         path: '$freelancer',
//                         preserveNullAndEmptyArrays: true,
//                     },
//                 },
//                 // {
//                 //     $lookup: {
//                 //         from: "apply-jobs",
//                 //         as: "applyJobsCount",
//                 //         let: { job_id: "$_id" },
//                 //         pipeline: [
//                 //             {
//                 //                 $match: {
//                 //                     $and: [
//                 //                         {
//                 //                             $expr: { $eq: ["$$job_id", "$job_id"] },
//                 //                         },
//                 //                         { is_active: true },
//                 //                         { is_deleted: false }
//                 //                     ]
//                 //                 },
//                 //             },
//                 //             { $project: { _id: 1, } },

//                 //         ],
//                 //     },
//                 // },


//                 { $project: { _id: 1, user_id: 1, title: 1, job_description: 1, category: 1, start_date: 1, end_date: 1, job_price: 1, experience_level: 1, job_pic: 1, status: 1, createdAt: 1, porposal_freelancer_id: 1, apply_job_id: 1, freelancer: "$freelancer" } },
//             ]),
//             await Job.countDocuments(filteredQuery),

//         ])

//         return apiResponse(res, false, [], '', SUCCESS.OK, count, data, req)
//     } catch (error) {
//         return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR`], SERVER_ERROR.internalServerError, 0, [], req)
//     }

// }


exports.contactUsListing = async (req, res) => {
    const lang = req.headers["accept-language"] || 'en'
    try {

        const { name, email, subject, message, createdAt, phone, updatedAt } = req.body
        var filteredQuery = {}
        let page, limit: number;
        let name_regex = new RegExp(name, 'i');
        let subject_regex = new RegExp(subject, 'i');
        let message_regex = new RegExp(message, 'i');
        let email_regex = new RegExp(email, 'i');
        let phone_regex = new RegExp(phone, 'i');
        if (req.query.search) {
            var createdDate = new Date(dateFormat(createdAt, 'yyyy-MM-dd'));
            var updatedDate = new Date(dateFormat(updatedAt, 'yyyy-MM-dd'));
            createdDate.setDate(createdDate.getDate() + 1)
            updatedDate.setDate(updatedDate.getDate() + 1)
            page = req.query.page ? parseInt(req.query.page) - 1 : 0;
            limit = 10;
            const filter_phone = (phone && phone != 'undefined') ? { phone: phone_regex } : {};
            const filter_name = (name && name != 'undefined') ? { first_name: name_regex } : {};
            const filter_subject = (subject && subject != 'undefined') ? { subject: subject_regex } : {};
            const filter_message = (message && message != 'undefined') ? { message: message_regex } : {};
            const filter_email = (email && email != 'undefined') ? { email: email_regex } : {};
            const filter_createdAt = (createdAt && createdAt != 'undefined') ? { createdAt: { $gte: new Date(dateFormat(createdAt, 'yyyy-MM-dd')), $lt: new Date(dateFormat(createdDate, 'yyyy-MM-dd')) } } : {};
            const filter_updatedAt = (updatedAt && updatedAt != 'undefined') ? { updatedAt: { $gte: new Date(dateFormat(updatedAt, 'yyyy-MM-dd')), $lt: new Date(dateFormat(updatedDate, 'yyyy-MM-dd')) } } : {};
            filteredQuery = { ...filter_name, ...filter_phone, ...filter_subject, ...filter_message, ...filter_email, ...filter_createdAt, ...filter_updatedAt, is_deleted: false }
        } else {
            page = req.query.page ? parseInt(req.query.page) - 1 : 0;
            limit = 10;
            filteredQuery = {
                is_deleted: false
            }
        }

        const [data, count] = await Promise.all([
            Contact.find(filteredQuery).sort({ createdAt: -1 }).skip(page * limit).limit(limit).populate("user_id", "first_name last_name"),
            Contact.countDocuments(filteredQuery)
        ]);
        return apiResponse(res, false, [], '', SUCCESS.OK, count, data, req)
    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR-${lang}`], SERVER_ERROR.internalServerError, 0, [], req)
    }
}


// appointment count status
exports.appointmentDashboardCount = async (req, res) => {
    const { status } = req.body
    let totalAppointment = await BookingAppointment.countDocuments({})

    let data = {
        totalCount: totalAppointment,
        pendingCount: await BookingAppointment.countDocuments({ status: "PENDING" }),
        rejectedCount: await BookingAppointment.countDocuments({ status: "REJECTED" }),
        approvedCount: await BookingAppointment.countDocuments({ status: "APPROVED", "reschedule_date": { $eq: null } }),
        completedCount: await BookingAppointment.countDocuments({ status: "COMPLETED" }),
        rescheduleCount: await BookingAppointment.countDocuments({ status: "RESCHEDULED", reschedule_date: { $ne: null } })

    }
    return apiResponse(res, false, [], '', SUCCESS.OK, 0, data, req)
}


// user count on monthly basis
exports.userCountOnMonthlyBasics = async (req, res) => {
    const lang = req.headers["accept-language"] || 'en'
    try {
        const { input_year } = req.body
        
        let doctorCount
        let patientCount
        let hospitalCount
        const userRoleDoctor = await Role.findOne({ title: "doctor" });

        const filteredQueryDoctor = {
            is_deleted: false,
            user_account_status: "APPROVED",
            is_completed: true,
            user_role: new mongoose.Types.ObjectId(userRoleDoctor._id),
            createdAt: {
                $gte: new Date(input_year, 0, 1), // Start of the input year
                $lt: new Date(input_year + 1, 0, 1) // Start of the next year // Start of the next year
            }
        };
        if (filteredQueryDoctor) {
            const monthlyCounts = await User.aggregate([
                { $match: filteredQueryDoctor },
                { $project: { month: { $month: "$createdAt" } } }, // Extract the month from createdAt
                { $group: { _id: "$month", count: { $sum: 1 } } }, // Group by month and count the documents
                { $sort: { _id: 1 } } // Sort by month
            ]);

            // Format the result to include month names
            const monthNames = [
                "January", "February", "March", "April", "May", "June",
                "July", "August", "September", "October", "November", "December"
            ];

            doctorCount = Array.from({ length: 12 }, (_, i) => {
                const monthData = monthlyCounts.find(item => item._id === i + 1);
                return {
                    month: monthNames[i],
                    count: monthData ? monthData.count : 0
                };
            });
        }




        // patient count
        const userRolePatient = await Role.findOne({ title: "patient" });

        const patientFilteredQuery = {
            is_deleted: false,
            user_account_status: "APPROVED",
            is_completed: true,
            user_role: new mongoose.Types.ObjectId(userRolePatient._id),
            createdAt: {
                $gte: new Date(input_year, 0, 1), // Start of the input year
                $lt: new Date(input_year + 1, 0, 1) // Start of the next year // Start of the next year
            }
        };
        if (patientFilteredQuery) {
            let monthlyCounts = await User.aggregate([
                { $match: patientFilteredQuery },
                { $project: { month: { $month: "$createdAt" } } }, // Extract the month from createdAt
                { $group: { _id: "$month", count: { $sum: 1 } } }, // Group by month and count the documents
                { $sort: { _id: 1 } } // Sort by month
            ]);
            // Format the result to include month names
            const monthNames = [
                "January", "February", "March", "April", "May", "June",
                "July", "August", "September", "October", "November", "December"
            ];
            patientCount = Array.from({ length: 12 }, (_, i) => {
                const monthData = monthlyCounts.find(item => item._id === i + 1);
                return {
                    month: monthNames[i],
                    count: monthData ? monthData.count : 0
                };
            });
        }

        // hospital count
        const userRolehospital = await Role.findOne({ title: "hospital" });

        const hospitalFilteredQuery = {
            is_deleted: false,
            user_account_status: "APPROVED",
            is_completed: true,
            user_role: new mongoose.Types.ObjectId(userRolehospital._id),
            createdAt: {
                $gte: new Date(input_year, 0, 1), // Start of the input year
                $lt: new Date(input_year + 1, 0, 1) // Start of the next year // Start of the next year
            }
        };
        if (hospitalFilteredQuery) {
            let monthlyCounts = await User.aggregate([
                { $match: hospitalFilteredQuery },
                { $project: { month: { $month: "$createdAt" } } }, // Extract the month from createdAt
                { $group: { _id: "$month", count: { $sum: 1 } } }, // Group by month and count the documents
                { $sort: { _id: 1 } } // Sort by month
            ]);
            const monthNames = [
                "January", "February", "March", "April", "May", "June",
                "July", "August", "September", "October", "November", "December"
            ];
            hospitalCount = Array.from({ length: 12 }, (_, i) => {
                const monthData = monthlyCounts.find(item => item._id === i + 1);
                return {
                    month: monthNames[i],
                    count: monthData ? monthData.count : 0
                };
            });
        }




        // Format the result to include month names


        let data = {
            doctor: doctorCount,
            hospital: hospitalCount,
            patient: patientCount
        }

        return apiResponse(res, false, [], '', SUCCESS.OK, 0, data, req)
    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR-${lang}`], SERVER_ERROR.internalServerError, 0, [], req)
    }

}

// appointment count on monthly basis
exports.appointmentCountOnMonthlyBasics = async (req, res) => {
    const lang = req.headers["accept-language"] || 'en'
    try {
        const { input_year } = req.body
        // Replace with the desired input year

        const startOfYear = new Date(input_year, 0, 1);
        const endOfYear = new Date(input_year + 1, 0, 1);
        const filteredQuery = {
            // is_deleted: false,


            createdAt: {
                $gte: startOfYear, // Start of the input year
                $lt: endOfYear // Start of the next year
            }
        };
        
        const monthlyCounts = await BookingAppointment.aggregate([
            { $match: filteredQuery },
            { $project: { month: { $month: "$createdAt" } } }, // Extract the month from createdAt
            { $group: { _id: "$month", count: { $sum: 1 } } }, // Group by month and count the documents
            { $sort: { _id: 1 } } // Sort by month
        ]);

        // Format the result to include month names
        const monthNames = [
            "January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December"
        ];

        const result = Array.from({ length: 12 }, (_, i) => {
            const monthData = monthlyCounts.find(item => item._id === i + 1);
            return {
                month: monthNames[i],
                count: monthData ? monthData.count : 0
            };
        });

      


        // Format the result to include month names




        return apiResponse(res, false, [], '', SUCCESS.OK, 0, result, req)
    } catch (error) {
        return apiResponse(res, true, [], ERROR_MSG[`SYSTEM-ERROR-${lang}`], SERVER_ERROR.internalServerError, 0, [], req)
    }

}

