const sequelize = require("../config/dbconnection");
const opportunitiesModel = require("../models/opportunities");
const projectsModel = require("../models/Projects")
const Admin = require('../models/admin')
const moment = require("moment/moment");
const { portalName } = require("../constants/constant");

const getAllOpportunities = async (request,reply) => {
    let data={};
    data["opportunities"]= await opportunitiesModel.getAllOpportunities();
    data['project_types'] = await projectsModel.getAllProjectTypes(true);
    data['project_categories'] = await projectsModel.getAllProjectCategories(true);
    data['members'] = await projectsModel.fetchAllTeamMembers(true);
    return data;
}

const isEmailExist = async (request,reply) => {
    let {emailId}=request.body;
    const exist = await Admin.isEmailExist(emailId)
    if(exist){
        return true;
    }else{
        return false;
    }
}

const addOpportunity = async (request,reply) => {
    let opportunityData = {};
    let currentDate = Math.round(moment().valueOf() / 1000);
    opportunityData['name'] = request.body.values.name;
    opportunityData['stage_id'] = request.body.values.stage;
    opportunityData['amount'] = request.body.values.amount || null;
    opportunityData['probability'] = request.body.values.probability;
    opportunityData['close_date'] = request.body.values.close;
    opportunityData['lead_source_id'] = request.body.values.leadsrc;
    opportunityData['description'] = request.body.values.description || null;
    opportunityData['added_by']= request.body.userId;
    opportunityData['added_time']=currentDate;
    opportunityData['updated_by']=request.body.userId;
    opportunityData['updated_time']=currentDate;
    opportunityData['status']=1;
    console.log('opportunityData---',opportunityData);
    let modelStatus= await opportunitiesModel.addOpportunity(opportunityData);
    if(modelStatus){
        /*********************Notification Starts Here******************/
        // Notification
        let notificationMsg=`Opportunity "${opportunityData['name']}" has been added to ${portalName}.`;
        let notificationUrl="opportunities";

        // Alert to user of new added product
        const incrementResult_User = await Admin.incrementField(opportunityData.added_by,"noti_count",1);
        let notificationData_user = {
            user_id: opportunityData.added_by,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationMsg,
            status: 1,
            from_id: opportunityData.added_by,
        };
        const addNotificationResult_user = await Admin.addNotification(notificationData_user);
        
        // Alert to all admins of new added product
        
        let adminIds = await Admin.getAllAdminIds();
        let notificationData = {};
        for (const adminId of adminIds) {
            if (adminId != opportunityData.added_by) {
                const incrementResult = await Admin.incrementField(adminId,"noti_count",1);
                notificationData = {
                    user_id: adminId,
                    url: notificationUrl,
                    timestamp: currentDate,
                    message: notificationMsg,
                    status: 1,
                    from_id: opportunityData.added_by,
                };
                const addNotificationResult = await Admin.addNotification(notificationData);
            }
        }
        reply.send({ status: 1, message: "Opportunity created successfully.",notification : notificationMsg });
    } else {
        console.log("Failed to create opportunity. ");
        reply.send({ status: 0, message: "Failed to create opportunity." });
    }
}

const deleteOpportunity = async (request,reply) => {
    try{
        let {deleteId,status,userId} = request.body;
        let currentDate = Math.round(moment().valueOf() / 1000);
        let data = {};
        let template = {};
        data['status']=status;
        console.log("deleteId,status,userId",deleteId,status,userId);
        let notificationMsg;
        if(deleteId){
            let deleted= await opportunitiesModel.updateOpportunity(deleteId,data);
            template= await opportunitiesModel.getOpportunityById(deleteId);
            if(data['status']===2)
            {
                notificationMsg=`The opportunity ${template[0].name} has been deleted.`;
            }
            else if(data['status']===0)
            {
                notificationMsg=`The opportunity ${template[0].name} has been made inactive.`;
            }
            else
            {
                notificationMsg=`The opportunity ${template[0].name} has been made active.`;
            }
            if(deleted){
                // Notification
                let notificationUrl="opportunities";
                // Alert to user of new added product
                const incrementResult_User = await Admin.incrementField(userId,"noti_count",1);
                let notificationData_user = {
                    user_id: userId,
                    url: notificationUrl,
                    timestamp: currentDate,
                    message: notificationMsg,
                    status: 1,
                    from_id: userId,
                };
                const addNotificationResult_user = await Admin.addNotification(notificationData_user);
                
                // Alert to all admins of new added product
                
                let adminIds = await Admin.getAllAdminIds();
                let notificationData = {};
                for (const adminId of adminIds) {
                    if (adminId != userId) {
                        const incrementResult = await Admin.incrementField(adminId,"noti_count",1);
                        notificationData = {
                            user_id: adminId,
                            url: notificationUrl,
                            timestamp: currentDate,
                            message: notificationMsg,
                            status: 1,
                            from_id: userId,
                        };
                        const addNotificationResult = await Admin.addNotification(notificationData);
                    }
                }
                reply.send({ status: 1, message: notificationMsg });
            } else {
                console.log("Failed to delete opportunity. ");
                reply.send({ status: 0, message: "Failed to delete opportunity." });
            }
        }
    }
    catch(error){
        console.log("deleteOpportunity error",error)
    }
}

const viewOpportunity = async (request,reply) => {
    let data = {};
    let {id} = request.body;
    data = await opportunitiesModel.getOpportunityById(id);
    // $data['opportunity_teams']=$this->opportunity_model->get_all_team_members('ASC',$id);
    return data[0];
}

const editOpportunity = async (request,reply) => {
    try{
        let opportunityData = {};
        let id = request.body.editId;
        let currentDate = Math.round(moment().valueOf() / 1000);
        opportunityData['name'] = request.body.values.name;
        opportunityData['stage_id'] = request.body.values.stage;
        opportunityData['amount'] = request.body.values.amount || null;
        opportunityData['probability'] = request.body.values.probability;
        opportunityData['close_date'] = request.body.values.close;
        opportunityData['lead_source_id'] = request.body.values.leadsrc;
        opportunityData['description'] = request.body.values.description || null;
        opportunityData['updated_by']=request.body.userId;
        opportunityData['updated_time']=currentDate;
        opportunityData['status']=1;

        let modelStatus= await opportunitiesModel.updateOpportunity(id,opportunityData);

        if(modelStatus){
        /*********************Notification Starts Here******************/
        // Notification
        let notificationMsg=`Opportunity "${opportunityData['name']}" has been updated to ${portalName}`;
        let notificationUrl="opportunities";

        // Alert to user of new added product
        const incrementResult_User = await Admin.incrementField(opportunityData.updated_by,"noti_count",1);
        let notificationData_user = {
            user_id: opportunityData.updated_by,
            url: notificationUrl,
            timestamp: currentDate,
            message: notificationMsg,
            status: 1,
            from_id: opportunityData.updated_by,
        };
        const addNotificationResult_user = await Admin.addNotification(notificationData_user);
        
        // Alert to all admins of new added product
        
        let adminIds = await Admin.getAllAdminIds();
        let notificationData = {};
        for (const adminId of adminIds) {
            if (adminId != opportunityData.updated_by) {
                const incrementResult = await Admin.incrementField(adminId,"noti_count",1);
                notificationData = {
                    user_id: adminId,
                    url: notificationUrl,
                    timestamp: currentDate,
                    message: notificationMsg,
                    status: 1,
                    from_id: opportunityData.updated_by,
                };
                const addNotificationResult = await Admin.addNotification(notificationData);
            }
        }
        reply.send ({status : 1, message : "Opportunity updated successfully",notification : notificationMsg});
        }else{
        reply.send ({status : 0, message : "Failed to update opportunity."});
        }
    }
    catch(error){
        console.log("editOpportunity error",error)
    }
}

module.exports = { getAllOpportunities,isEmailExist,addOpportunity,deleteOpportunity,viewOpportunity,editOpportunity }