const Admin = require ('../models/admin')
const Projects = require ('../models/Projects')
const Login = require ('../models/login');
const ContactsModel = require('../models/contacts');
const TwilioCallModel = require('../models/twilioModel')
const { portalName } = require("../constants/constant");
const moment = require("moment");
let currentDate = Math.round(moment().valueOf() / 1000);

const getAllContactDetails = async(request,reply) => {
    let data={};
    let {userPermissions}=request.body;
    console.log('userPermissions--',userPermissions);
    data["contacts"]= await ContactsModel.getAllContacts();
    let explodedPermissions;
    let privilegeResult = await Login.isPrivileged(userPermissions)
    if (privilegeResult) {
        explodedPermissions = privilegeResult.map(entry => entry.privileges);
      }
    data['exploded_permissions']=explodedPermissions;
    data['project_types'] = await Projects.getAllProjectTypes(true);
    data['project_categories'] = await Projects.getAllProjectCategories(true);
    data['members'] = await Projects.fetchAllTeamMembers(true);
    data['states'] = await Admin.getAllStates();
	data['countries'] = await Admin.getAllCountries();
	data['industries'] = await Admin.getAllIndustries();
    return data;
}

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

const addContact = async (request,reply) => {
    let contactData = {};
    const {values,userId} = request.body;
    contactData['name'] = values.name || null;
    contactData['email_id'] = values.email || null;
    contactData['phone'] = values.phone && String(values.phone).replace(/[^0-9]/g, '') || null;
    contactData['address'] = values.address || null;
    contactData['city'] = values.city || null;
    contactData['state_id'] = values.state || null;
    contactData['zip_code'] = values.code || null;
    contactData['country'] = values.country || null;
    contactData['description'] = values.description || null;
    contactData['added_by']=userId;
    contactData['added_time']=currentDate;
    contactData['updated_by']=userId;
    contactData['updated_time']=currentDate;
    contactData['status']=1;

    let addContactResult= await ContactsModel.addContact(contactData); //save data to database

    if(addContactResult){
        /*********************Notification Starts Here******************/
        // Notification
        let notificationMsg=`Contact "${contactData['name']}" has been added to "${portalName}".`;
        let notificationUrl="contacts";
        // Alert to user of new added contact
        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 admins of new added contact
        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);
        }
        }
        /*******************Notification Ends Here**********************************/
        reply.send({status:1, message:"Contact created successfully", notification:notificationMsg})
    }else{
        reply.send({status:1, message:"Failed to create contact."});
    }
}

const deleteContact = async (request,reply) => {
    try{
    let {contactId,status,userId} = request.body;
    let contact={};
    let notificationMsg;
    let notificationUrl="contacts";
    contact['status'] = status || 0;
    if(contactId){
        let deleted = await ContactsModel.updateContact(contactId,contact);
        contact= await ContactsModel.getContactById(contactId);
        // Notification-----start----------------------------------------------------------------------------------
        if(contact['status']===2)
        {
            notificationMsg=`The contact ${contact['name']} has been deleted.`;
        }
        else if(contact['status']===0)
        {
            notificationMsg=`The contact ${contact['name']} has been made inactive.`;
        }
        else if(contact['status']===1)
        {
            notificationMsg=`The contact ${contact['name']} has been made active.`;
        }
        if(deleted){
        // Alert to user of new added contact
        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 admins of new added contact
        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);
        }
        }
        // Notification-----end------------------------------------------------------------------------------------
            reply.send({status : 1, message : notificationMsg});
        }else{
            reply.send({status : 0, message : "Unable to delete the contact!"});
        }
    }
    }
    catch(error){
        console.log("delete Contact error",error)
    }
}

const getContactById = async (request,reply) => {
    const {editId} = request.body;
    let data= await ContactsModel.getContactById(editId);
    reply.send({status:1,contactData:data});
}

const editContact = async (request,reply) => {
    let ajax=0;
    let contactData = {};
    const {values,userId,editId} = request.body;
    values.name && (contactData['name'] = values.name);
    values.email && (contactData['email_id'] = values.email);
    values.phone && (contactData['phone'] = String(values.phone).replace(/[^0-9]/g, ''));
    values.address && (contactData['address'] = values.address);
    values.city && (contactData['city'] = values.city);
    values.state && (contactData['state_id'] = values.state);
    values.code && (contactData['zip_code'] = values.code);
    values.country && (contactData['country'] = values.country);
    values.description && (contactData['description'] = values.description);
    contactData['updated_by']=userId;
    contactData['updated_time']=currentDate;
    contactData['status']=1;

    let updateContactResult= await ContactsModel.updateContact(editId,contactData); //save data to database
    // console.log("updateContactResult--",updateContactResult);
    if(updateContactResult[0] > 0){
    /*********************Notification Starts Here******************/
    // Notification
    let notificationMsg=`Contact "${contactData['name']}" has been updated to "${portalName}".`;
    let notificationUrl="contacts";

    // Alert to user of new added contact
    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 admins of new added contact
    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);
    }
    }
    /*******************Notification Ends Here**********************************/
        reply.send({status:1,message:"Contact updated successfully",notification:notificationMsg});
    }
    else if(updateContactResult[0] === 0){
        reply.send({status:2,message:"Nothing to update"});
    }
    else {
        reply.send({status:0,message:"Failed to update contact"});
    }
}

const viewContact = async (request,reply) => {
    let {id} = request.body;
    // let status=0,task_source=2
    let data = {};
    data['contact']= await ContactsModel.getContactById(id);
    // data['contact_partners']=$this->contact_model->get_contact_partners_by_ids(array(),$id);
    // data['contact_teams']=$this->contact_model->get_all_team_members('ASC',$id);

    data['states'] = await Admin.getAllStates();
	data['countries'] = await Admin.getAllCountries();
    data['call_notes'] = await ContactsModel.getAllCallNotes(id);
    // $data['twilio_calls'] =array();
    // $data['twilio_sms'] =array();
    // $data['twilio_whatsapp'] =array();
    if(data['contact']['phone']){
        data['twilio_calls'] = await TwilioCallModel.getAllCalls(` AND (tc.from = '+${data['contact']['phone']}' OR tc.to='+${data['contact']['phone']}')`,'ASC');
        
        // const fromPhoneNumber = data['contact']['phone'].replace("+", "");
        // data['twilio_sms'] = await TwilioCallModel.getAllSms(fromPhoneNumber,'ASC'); 
    //  data['twilio_sms'] = await twilioModel.getAllSmsList(`(from='+".str_replace("+", "", $data['contact']['phone'])."' or to='+".str_replace("+", "", $data['contact']['phone'])."')`,'ASC'); 
    //  $data['twilio_whatsapp'] = $this->twilio_call_model->get_all_whatsapp_list("(from='+".str_replace("+", "", $data['contact']['phone'])."' or to='+".str_replace("+", "", $data['contact']['phone'])."')",'ASC'); 
    
    }
    
    /************* Assigned Tasks *****************/
    /************* Taken from function named 'assingned' in Tasks controller**************/
    //$status = intval($status);
    // $field_name="";
    // if($task_source==1){
    //   $field_name="partner_id";
    // }

    // if($task_source==2){
    //   $field_name="contact_id";
    // }

    // if($task_source==3){
    //   $field_name="lead_id";
    // }

    // $data['tasks']=$this->Model_task->get_user_assigned_tasks($field_name,$status, $id);
    // $data['page_url']='assigned';
    // $data['add_url']='add-task';
    // /************End Assigned Tasks****************/
    // $exploded_permissions=array();
    //   if($this->admin_model->is_privileged($this->session->userdata('user_permissions'))){
    //     $user_permissions=$this->admin_model->is_privileged($this->session->userdata('user_permissions'));
    //     $exploded_permissions=array_column($user_permissions,'privileges');
    //   }
    // $data['exploded_permissions']=$exploded_permissions;
    // $data['task_source']=$task_source;
    reply.send({status:1,message:"Data fetched successfully",result:data})
}

module.exports = { getAllContactDetails, addContact, isEmailExist, deleteContact, getContactById, editContact,viewContact }