const { check, validationResult } = require('express-validator');
const db = require('../models');
const VacationController = require('../controllers/vacationController');
const FunctionController = require('../controllers/functionController');
const { Op } = require('sequelize');
const excel = require('exceljs');
const fs = require('fs');
const XlsxPopulate = require('xlsx-populate');

const EmployeeModel = db.employee;
const ChildEmployeeModel = db.childEmployee;
const EmployeeFunctionModel = db.employeeFunction;


//  VALIDER LES INFOS D'INSCRIPTION
var dataToValidateRegistration = [
    check('nameEmployee', "Nom est obligatoire")
        .notEmpty()
        .withMessage('Nom obligatoire')
        .trim()
        .toUpperCase(),
    check('lastNameEmployee')
        .optional(),            
    check('villeEmployee')
        .optional()
        .isString(),            
    check('nbrChild')
        .optional()
        .toInt(),
    check('contactAirtel', "Contact invalid")
        .optional()
        .isLength({ min: 10, max: 10 })
        .isMobilePhone(),
    check('contactTelma', "Contact invalid")
        .optional()
        .isLength({ min: 10, max: 10 })
        .isMobilePhone(),
    check('contactOrange', "Contact invalid")
        .optional()
        .isLength({ min: 10, max: 10 })
        .isMobilePhone(),
    check('contactFlotte', "Contact invalid")
        .optional()
        .isLength({ min: 10, max: 10 })
        .isMobilePhone(),    
    check('heredIllness')
        .optional()
        .isString()
];

const createEmployee = async ( req, res, next) => {    
    console.log(req.body)
    const superAdmin = await db.admin.findOne({ where: { role: "Super admin" }});
    // Rassembler toutes les informations de l'employee
    let employeeInfo = {
        id: req.body.id,        
        matricule: req.body.matricule,
        name_employee: req.body.nameEmployee,
        last_name_employee: req.body.lastNameEmployee,
        sexe_employee: req.body.sexEmployee=='Masculin' ? 'M' : 'F',
        birth_employee: req.body.ddnEmployee == '' ? null : req.body.ddnEmployee,
        birth_place_employee: req.body.placeDdnEmployee,
        address_employee: req.body.addrEmployee,
        ville_employee: req.body.villeEmployee,
        cinemployee: req.body.CINEmployee,
        date_cinemployee: req.body.dateCINEmployee == '' ? null : req.body.dateCINEmployee,
        cinplace_employee: req.body.placeCINEmployee,
        marital_status_employee: req.body.martialStatus,
        nbr_child: parseInt(req.body.nbrChild),
        contact_airtel: req.body.contactAirtel,
        contact_telma: req.body.contactTelma,
        contact_orange: req.body.contactOrange,
        contact_flotte: req.body.contactFlotte,
        num_cnaps: req.body.numCNAPS == '' ? 0 : req.body.numCNAPS ,
        driver_licence: req.body.permisDeConduire,
        hereditary_illness: req.body.heredIllness,
        person_contact_emergency: req.body.personContactEmergency,
        contact_person_emergency: req.body.contactPersonEmergency,
        hiring_date: req.body.hiringDate === '' ? new Date() : req.body.hiringDate,
        category: req.body.category,
        AdmnistratorId: req.body.boss ? req.body.boss : null,
    };

    let employeeResult = await EmployeeModel.findOne({ where:{ matricule: employeeInfo.matricule }});

    //ENREGISTRER L'EMPLOYEE
    try {
        employeeInfo.AdmnistratorId = superAdmin.id;     
        if(employeeResult) {
            console.log(employeeResult)
            let r = await EmployeeModel.update(employeeInfo, {
                id: employeeResult.id
            })
            var employee = await EmployeeModel.findOne({
                where: {id : employeeResult.id}
            });            
        }   
        else {

            var employee = await EmployeeModel.create(employeeInfo);
            
            let newVacation = await VacationController.newVacation(employee.id);
            let infoCongee = {
                employeeId: employee.id,
                totalVacation: newVacation.totalVacation,
                endDate: employee.hiring_date,
                AdmnistratorId: superAdmin.id
            };        
            let vacationInitial = VacationController.save(infoCongee);        
        }

   } catch ( err ) {
       console.log(err)
       res.status(422).json({ message: `Error + ${err}`})
   }
   console.log(employee)
    
    //   AUTORISATION DE DEMANDER ET DE VALIDER
    var allSuperieurs = await db.admin.findAll({
        where: {
            [Op.or]: [
                { role: 'Manager'},
                { role: 'Super admin'}
            ]
        }
    });
    employeeInfo.applicants = allSuperieurs.slice();        
    employeeInfo.validatores = allSuperieurs.slice();

    //  Reconstruit la relation    
    for(let i = 0; i < employeeInfo.applicants.length; i++) {
        const applicant = employeeInfo.applicants[i];
  
        //  L'applicant est aussi validateur ?        
        const isValidator = employeeInfo.validatores.some(validator =>
            validator.id === applicant.id
        );
        
        //  S'il est vraiment validateur
        if (isValidator) {
            await db.adminEmployee.create({
                employeeId: employee.id,
                AdmnistratorId: employeeInfo.applicants[i].id,
                isApplicant: true,
                isValidator: true
            });
        }
        else {
            await db.adminEmployee.create({
                employeeId: employee.id,
                AdmnistratorId: employeeInfo.applicants[i].id,
                isApplicant: true,
                isValidator: false
            });
        }
    }    

    //  SAUVEGARDER LES ENFANTS
    childSaved = [];    
    employee.nbr_child = employee.nbr_child ?? 0;
    if( employee.nbr_child != 0 )
    {
        for(let i = 0; i< employee.nbr_child; i++)
        {
            if( req.body.ddnChild && req.body.sexeChild ) {
                let childInfo = {
                    birthChild: req.body.ddnChild[i],
                    sexe: req.body.sexeChild[i],
                    employeeId: employee.id
                };
                childSaved.push(
                    await ChildEmployeeModel.create(childInfo)
                );
            }
        }
    }


    //  ENREGISTRER LA FONCTION
    try{
        
        if( req.body.dateFunct && req.body.function != 0 ) {              
            //  Verifier que l'admin ne modifie pas sur la fonction
            let result = await EmployeeFunctionModel.findAll({
                limit: 1,
                where: { 
                    employeeId: employee.id,
                    functionId: req.body.function,
                    date: req.body.dateFunct
                },
                order: [ 
                    ['date', 'DESC'] 
                ]
            });            
            if(result.length == 0){
                let infoFunction = {
                    functionId: req.body.function,
                    employeeId: employee.id,
                    date: req.body.dateFunct
                };
                let employeeFunction = await EmployeeFunctionModel.create(infoFunction);
                console.log(employeeFunction)
            }
        }
    }catch(err) {
        console.log(err);
    }   

     //ENREGISTRER LE CV ET LE PHOTO
    
    if(req.files) {  
        if(req.files.photo) {
            const { fieldname, filename, path, mimetype } = req.files.photo[0];
            if(fieldname === 'photo') {
                let r = await db.photo.create({
                    filename,
                    path,
                    mimetype,
                    employeeId: employee.id
                });
            }                                          
        }      

        if(req.files.cv) {
            const { fieldname, filename, path, mimetype } = req.files.cv[0];
            if(fieldname == 'cv') {
                if( !path.includes('.xlsx')) {
                    await db.cv.create({
                        filename,
                        path,
                        mimetype,
                        employeeId: employee.id
                    })        
                }            
            }
        }
    }


    //  Envoyer l'employee cree dans le requete suivant
    return employee;
    // res.send(employee);    
    // res.render(`/employee/${employee.id}`);    
}

const separateNames = (names) => {
    const nameParts = names.split(" ");
    const name = nameParts[0];
    const lastName = nameParts.slice(1).join(" ");
    return { name, lastName };
  }

const importEmployeeExcel = async ( req, res ) => {  
    var superAdmin = await db.admin.findOne({ where: { role: 'Super admin' }});        
    // Vérifier les erreurs de validation
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }
    
    try {
        const file = req.file;
        // const workbook = new excel.Workbook();
        
        // await workbook.xlsx.readFile(file.path);
        
        // const worksheet = workbook.worksheets[0];
        // const rows = worksheet.getSheetValues();  

        XlsxPopulate.fromFileAsync(file.path)
            .then(workbook => {
                workbook.sheets().forEach(sheet => {
                    const usedRange = sheet.usedRange();
                    console.log(sheet.cell(3,11).value().text());
                    for(let rowIndex = 0; rowIndex < usedRange.length ; rowIndex++) {
                        const row = usedRange[rowIndex];
                        console.log(row);
                    }
                })
            })
                
        // const workbook = await XlsxPopulate.fromFileAsync(file.path);
        // const sheet = workbook.sheet(0);

        // const rowCount = sheet.usedRange().endCell().rowNumber();
        // const colCount = sheet.usedRange().endCell().columnNumber();

        // console.log(rowCount);
        // console.log(colCount);        
        // for(let row = 2;( row <= rowCount && typeof(sheet.cell(row, 1).value()) == 'string' ); row++) {
        //     let matricule = sheet.cell(row, 1).value();
        //     let soldeMois = sheet.cell(row, 5).value();
        //     let congesPris = sheet.cell(row, 11).value();
        //     let congesReste = sheet.cell(row, 12).value();
        //     let congesPrisDate = sheet.cell(row, 11).note;

        //     console.log(matricule);
        //     console.log(soldeMois);
        //     console.log(congesPris);
        //     console.log(congesReste);
        //     console.log(congesPrisDate);
        // }        
            
        // console.log(rows.length);
        // for( i = 2;( i < rows.length && typeof(rows[i][1]) == 'string' ); i++ ) {            
        //     const row = rows[i];                   
        //     // console.log(row[5])
        //     console.log(row[11])

            
        //     // //  Prend tout les donnees d'un employee             
        //     // const { name, lastName } = separateNames(row[2]);
        //     // //  Chef
        //     // // console.log(row);  
        //     // // let boss = await db.admin.findOne({ where: { matriculeEmployee : row[8]}});
        //     // const employeeData = {
        //     //     matricule: row[1],
        //     //     nameEmployee: name,
        //     //     lastNameEmployee: lastName,
        //     //     hiringDate: (typeof(row[4]) == 'object') ? row[4].result : moment(),
        //     //     // boss: boss.id,
        //     // }


        //     // //  Fonction             
        //     // let nomFonction = (typeof(row[3]) == 'object') ? row[3].result : row[3];
        //     // if( nomFonction ) {
        //     //     //  Prend la fonction meme nom            
        //     //     let fonction = await db.function.findOne({ where: { nameFunction: nomFonction} });
        //     //     if(fonction) {
        //     //         //  Date de debut de fonction comme date d'embauche
        //     //         employeeData.dateFunct = employeeData.hiringDate;
        //     //         //  Id de la fonction trouvee dans le recherche ci dessus
        //     //         employeeData.function = fonction.id;
        //     //     }            
        //     // }
            
        //     // req.body = employeeData;            
        //     // //  creer l'employee
        //     // let employee = await createEmployee(req, res);        
        //     // let total = (typeof(row[6]) == 'object') ? row[6].result : row[6];            
        //     // const vacationData = {
        //     //     employeeId: employee.id,
        //     //     totalVacation: VacationController.roundValue(total),
        //     //     endDate: moment(),
        //     //     AdmnistratorId: superAdmin.id,                
        //     // }            

        //     // let result = await db.vacation.create(vacationData);
        //     // console.log(result)
        // }              

        // Supprimer le fichier après le traitement
        fs.unlinkSync(file.path);

        return res.redirect('/employee/')
    }
    catch(err) {
        console.log(err)
        return res.redirect('/');
    }    
}

const informationImport = async ( req, res ) => {  
    var superAdmin = await db.admin.findOne({ where: { role: 'Super admin' }});        
    // Vérifier les erreurs de validation
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }
    
    try {
        const file = req.file;
        const workbook = new excel.Workbook();
        
        await workbook.xlsx.readFile(file.path);
        
        const worksheet = workbook.worksheets[0];
        const rows = worksheet.getSheetValues();      
        
        for( i = 2; i < rows.length - 1; i++ ) {            
            const row = rows[i];  

            let marital = '';
            switch(row[13]) {
                case 'marié':
                    marital = 'married';
                    break;
                case 'célibataire':
                    marital = 'single';
                    break;                                    
            }             
            const employeeData = {
                matricule: row[2],                                
                name_employee: row[3],
                last_name_employee: row[4],
                sexe_employee: row[5] == 'Femme' ? 'F' : 'M',
                birth_employee: row[6],
                birth_place_employee: row[8],
                address_employee: row[9],                                
                cinemployee: row[10],
                date_cinemployee: row[11],
                cinplace_employee: row[12],
                marital_status_employee: marital,
                nbr_child: row[14],
                contact_airtel: row[17],
                contact_telma: row[16],
                contact_orange: row[18],
                contact_flotte: row[19],
                num_cnaps: row[20],
                driver_licence: row[21] ? row[21].split("").join(',') : null,
                hereditary_illness: row[28],
                person_contact_emergency: row[29],
                contact_person_emergency: row[30],
                hiring_date: row[24],
                debauch_date: row[25],
                category: row[23],
                // nbr_interims: req.body.nbrInterim,
            }
            
            req.body = employeeData;

            let employee = await db.employee.findOne({ where: {
                matricule: employeeData.matricule
            }})
            
            if(employee) {
                let r = await db.employee.update(employeeData, { where: { id: employee.id }});                
                console.log(r);
            }            
        }              

        // Supprimer le fichier après le traitement
        fs.unlinkSync(file.path);

        return res.redirect('/')
    }
    catch(err) {
        console.log(err)
        return res.redirect('/');
    }    
}

const getAllEmployee = async () => {
    return await EmployeeModel.findAll();
}

const getOneEmployee = async (id) => {
    return await EmployeeModel.findOne({
        where : { id: id}
    });
}

const updateEmployee = async (req, res) => {                
    // Rassembler toutes les informations de l'employee
    const superAdmin = await db.admin.findOne({ where: { role: "Super admin" }});
    console.log(req.body);
    let employeeInfo = {
        id: req.body.id,
        matricule: req.body.matricule,
        name_employee: req.body.nameEmployee,
        last_name_employee: req.body.lastNameEmployee,
        sexe_employee: req.body.sexEmployee,
        birth_employee: req.body.ddnEmployee == '' ? null : req.body.ddnEmployee,
        birth_place_employee: req.body.placeDdnEmployee,
        address_employee: req.body.addrEmployee,
        ville_employee: req.body.villeEmployee,
        cinemployee: req.body.CINEmployee,
        date_cinemployee: req.body.dateCINEmployee == '' ? null : req.body.dateCINEmployee,
        cinplace_employee: req.body.placeCINEmployee,
        marital_status_employee: req.body.martialStatus,
        nbr_child: parseInt(req.body.nbrChild),
        contact_airtel: req.body.contactAirtel,
        contact_telma: req.body.contactTelma,
        contact_orange: req.body.contactOrange,
        contact_flotte: req.body.contactFlotte,
        num_cnaps: req.body.numCNAPS ,
        driver_licence: req.body.permisDeConduire,
        hereditary_illness: req.body.heredIllness,
        person_contact_emergency: req.body.personContactEmergency,
        contact_person_emergency: req.body.contactPersonEmergency,
        hiring_date: req.body.hiringDate === '' ? null : req.body.hiringDate,
        category: req.body.category,
        nbr_interims: req.body.nbrInterim,
    };    

    

    //  Super admin, manager
    var allSuperieurs = await db.admin.findAll({
        where: {
            [Op.or]: [
                { role: 'Manager'},
                { role: 'Super admin'}
            ]
        }
    });            
    
    switch(req.body.role) {
        case '':    
            //  Demandeur
            employeeInfo.applicants = [...allSuperieurs];        
            employeeInfo.validatores = [...allSuperieurs];
            if(req.body.applicant && req.body.applicant !== 'superieur') {
                //  User ou admin demandeur de conge
                let applicantPerso = await db.admin.findOne({
                    where: { id: req.body.applicant }
                });
                
                if(applicantPerso && applicantPerso.role == 'User') {                
                    //  Trouver l'admin qui encadre cet user, c'est leur validateur                
                    var applicantLeader = await db.admin.findAll({
                        where: { id: applicantPerso.leader }
                    });
                    employeeInfo.AdmnistratorId = applicantPerso.id;
                    if(applicantLeader) {
                        //  Le chef de l'User valide le conge de l'employee
                        employeeInfo.applicants.push(applicantLeader);
                        employeeInfo.validatores.push(applicantLeader);
                    }
                    employeeInfo.applicants.push(applicantPerso);      
                    
                }
                else if( applicantPerso && applicantPerso.role == 'Admin' ) {
                    var admin = await db.admin.findOne({ where:{ id: req.body.applicant }});
                    employeeInfo.AdmnistratorId = admin.id;
                    if(admin) {
                        employeeInfo.applicants.push(admin);
                        employeeInfo.validatores.push(admin);                        
                    }                                        
                }                       
            }        
            else {
                employeeInfo.AdmnistratorId = null;
            }
            break;
        //  Il faut connaitre leur validateur, demandeur lui meme
        case 'User': 
            employeeInfo.applicants = [...allSuperieurs];

            let user = await db.admin.findOne({ where: { id: req.body.postId }});
            let userLeader = await db.admin.findOne({
                where: { id: user.leader }
            });
            if(userLeader) {
                employeeInfo.applicants.push(user);
                employeeInfo.applicants.push(userLeader);
                employeeInfo.AdmnistratorId = userLeader.id;    
                employeeInfo.validatores.push(userLeader);    
            }
            
            employeeInfo.validatores = [...allSuperieurs];
            
            break;
        case 'Admin': 
            var self = await db.admin.findOne({ where:{ id: req.body.postId }});
            employeeInfo.applicants = [...allSuperieurs];
            employeeInfo.applicants.push(self);            

            employeeInfo.validatores = [...allSuperieurs];
            break;
        case 'Manager':
            var self = await db.admin.findOne({ where:{ id: req.body.postId }});
            var superAdmins = await db.admin.findAll({ where: { role: 'Super admin'}});
            employeeInfo.applicants = [...superAdmins];
            employeeInfo.applicants.push(self);

            employeeInfo.validatores = [...superAdmins];
            break;
        case 'Super admin':
            var self = await db.admin.findOne({ where:{ id: req.body.postId }});
            var superAdmins = await db.admin.findAll({ where: { role: 'Super admin'}});
            employeeInfo.applicants = [...superAdmins];
            
            employeeInfo.validatores = [...superAdmins];
            break;
    }
    
    //  ENREGISTREMENT DES VALIDATEURS ET DEMANDEURS
    //  Detruit tous les relations entre l'employee et les admins 
    console.log(employeeInfo)   
    await db.adminEmployee.destroy({where: { employeeId: employeeInfo.id }});

    //  Reconstruit la relation    
    for(let i = 0; i < employeeInfo.applicants.length; i++) {
        const applicant = employeeInfo.applicants[i];
  
        //  L'applicant est aussi validateur ?        
        const isValidator = employeeInfo.validatores.some(validator =>
            validator.id === applicant.id
        );
        
        //  S'il est vraiment validateur
        if (isValidator) {
            await db.adminEmployee.create({
                employeeId: employeeInfo.id,
                AdmnistratorId: employeeInfo.applicants[i].id,
                isApplicant: true,
                isValidator: true
            });
        }
        else {
            await db.adminEmployee.create({
                employeeId: employeeInfo.id,
                AdmnistratorId: employeeInfo.applicants[i].id,
                isApplicant: true,
                isValidator: false
            });
        }
    }    

    //  METTRE A JOURS L'EMPLOYEE ET LE CONGE
    try {
        
        var employee = await EmployeeModel.findOne({where : { id: employeeInfo.id }});
        let lastHiringDate = employee.hiring_date;
        
        console.log(employeeInfo);
        let r = await EmployeeModel.update(employeeInfo, {where:{id: employeeInfo.id}});
        employee = await EmployeeModel.findOne({where : { id: employeeInfo.id }});        

        //  S'il y a une modification de date d'embauche
        if( lastHiringDate !== employee.hiring_date ) {            
            let vacation = await VacationController.newVacation(employee.id);
            let infoCongee = {
                employeeId: employee.id,
                totalVacation: vacation.totalVacation,
                endDate: employee.hiring_date,
                AdmnistratorId: superAdmin.id
            };                        
            console.log(vacation)
            let vacationInitial = await VacationController.save(infoCongee);                                 
        }
    }catch(err) {
        console.log(err)
        res.status(422).json({ message: `Error + ${err}`})
    }
     

    //  METTRE A JOUR LES ENFANTS
    // childSaved = [];            
    if( employee.nbr_child != 0 )
    {
        for(let i = 0; i< employee.nbr_child; i++)
        {
            // Si le nombre d'enfant est declarer mais l'enfant n'est pas enregistrer
            let birthChild = Array.isArray(req.body.ddnChild) ? req.body.ddnChild[i] : req.body.ddnChild;
            if(req.body.idChild[i] == 0 && birthChild !== '') {
                let childInfo = {                    
                    birthChild: birthChild,
                    sexe: req.body.sexeChild[i],
                    employeeId: employee.id
                };            
                
                let result = await db.childEmployee.create( childInfo );
                // console.log(result)
            }
            //  Mise a jour
            else {                      
                let childInfo = {
                    id: req.body.idChild[i],                                        
                    birthChild: Array.isArray(req.body.ddnChild) ? req.body.ddnChild[i] : req.body.ddnChild,
                    sexe: req.body.sexeChild[i],
                    employeeId: employee.id
                };                            
                // Mise a jour                
                let r = await db.childEmployee.update( childInfo, { where: { id: childInfo.id }})                
    
                // Retoure apres la mise a jour
                let result = await db.childEmployee.findOne({ where:{ id: childInfo.id }});
                // console.log(result)
            }
        }
    }

    // MISE A JOUR INTERIMAIRE
    interimsSaved = [];
    if(employee.nbr_interims != 0) {
        for(let i = 0; i< employee.nbr_interims; i++)
        {
            // Si le nombre d'enfant est declarer mais l'enfant n'est pas enregistrer
            let interimId = Array.isArray(req.body.interimId) ? req.body.interimId[i] : req.body.interimId;
            let idInterim = Array.isArray(req.body.idInterim) ? req.body.idInterim[i] : req.body.idInterim;
            if(idInterim == 0 ) {
                let interimInfo = {                    
                    interimId: interimId,                    
                    employeeId: employee.id
                };            
                
                let result = await db.interim.create( interimInfo );
                // console.log(result)
            }
            //  Mise a jour
            // else {                      
            //     let interimInfo = {
            //         id:  Array.isArray(req.body.idInterim) ? req.body.idInterim[i] : req.body.idInterim,                                        
            //         interimId: Array.isArray(req.body.interimId) ? req.body.interimId[i] : req.body.interimId,                    
            //         employeeId: employee.id
            //     };                            
            //     // Mise a jour                
            //     let r = await db.childEmployee.update( interimInfo, { where: { id: interimInfo.id }})                
    
            //     // Retoure apres la mise a jour
            //     let result = await db.childEmployee.findOne({ where:{ id: interimInfo.id }});
            //     // console.log(result)
            // }
        }
    }
    
    // Mise a jour de fonction
    try{
        if( req.body.dateFunct && req.body.function ) {

            //  Verifier que l'admin ne modifie pas sur la fonction
            let result = await EmployeeFunctionModel.findAll({
                limit: 1,
                where: { 
                    employeeId: req.body.id,
                    functionId: req.body.function,
                    date: req.body.dateFunct
                },
                order: [ 
                    ['date', 'DESC'] 
                ]
            });
            
            // console.log(result.length)
            //  S'il a mise a jour le fonction
            console.log(result)
            if(result.length === 0){
                let infoFunction = {
                    functionId: req.body.function,
                    employeeId: req.body.id,
                    date: req.body.dateFunct
                };
                let employeeFunction = await EmployeeFunctionModel.create(infoFunction);
            }
        }
    }catch(err) {
        console.log(err);
    }
    
    //ENREGISTRER LE CV ET LE PHOTO
    if(req.files) {  
        if(req.body.idPhoto && req.files.photo) {            
            const { fieldname, filename, path, mimetype } = req.files.photo[0];
            if(fieldname === 'photo') {
                await db.photo.update({
                    filename,
                    path,
                    mimetype,
                    employeeId: employee.id
                },
                { where: { id: req.body.idPhoto} });
            }
        }
        else if(req.files.photo) {            
            const { fieldname, filename, path, mimetype } = req.files.photo[0];
            if(fieldname === 'photo') {
                let r = await db.photo.create({
                    filename,
                    path,
                    mimetype,
                    employeeId: employee.id
                });
            }                                          
        }      

        if(req.files.cv) {
            const { fieldname, filename, path, mimetype } = req.files.cv[0];
            if(fieldname == 'cv') {
                if( !path.includes('.xlsx')) {
                    await db.cv.create({
                        filename,
                        path,
                        mimetype,
                        employeeId: employee.id
                    })        
                }            
            }
        }
    }
    //  FIN CV
    return employee;    
}

const deleteEmployee = async (req, res) => {
    const ID = req.params.id;
    const employeeToDelete = await EmployeeModel.findOne({ where: { id: ID }});

    if(!employeeToDelete) {        
        return res.status(404).json({ message: 'Employee non trouvé!' });
    }

    //  SUPPRIMER S'IL EST ADMINISTRATEUR
    let isAdmin = await db.admin.findOne({ where: { matriculeEmployee: employeeToDelete.matricule }});
    if(isAdmin) {
        //  SUPRIMER LA RELATION AVEC L'ADMINEMPLOYEE
        await db.adminEmployee.destroy({ where: { employeeId: employeeToDelete.id }});
        await db.adminEmployee.destroy({ where: { AdmnistratorId: isAdmin.id }});
        await db.token.destroy({ where: { AdmnistratorId: isAdmin.id }});
        await db.admin.destroy({ where: { id: isAdmin.id }});
    }

    //  SUPPRIMER LEUR ENFANT
    await db.childEmployee.destroy({ where: { employeeId: employeeToDelete.id }});

    //  SUPPRIMER LEUR CV
    await db.cv.destroy({ where: { employeeId: employeeToDelete.id }});

    //  SUPPRIMER LEUR RELATION AVEC FONCTION
    await db.employeeFunction.destroy({ where: { employeeId: employeeToDelete.id }});

    //  SUPPRIMER LEUR CONGE
    await db.vacation.destroy({ where: { employeeId: employeeToDelete.id }});

    //  SUPPRIMER LEUR CONGE REJETER
    await db.vacationRejected.destroy({ where: { employeeId: employeeToDelete.id }});

    //  SUPPRIMER L'EMPLOYEE
    await db.employee.destroy({ where: { id: employeeToDelete.id }});

    res.status(200).json({success:"Success",message: "Employee successfully deleted"});
    
}

const deleteInterim = async ( req, res) => {
    const ID = req.params.id;
    const interim = await db.interim.findOne({ where:{ id: ID }});
    if(!interim) {
        return res.redirect('/employee/');
    }

    var employee = await db.employee.findOne({ where:{ id: interim.employeeId }});
    if(!employee) {
        return res.redirect('/employee/');        
    }

    employee.nbr_interims -= 1;
    console.log(employee.nbr_interims)
    await db.employee.update( { nbr_interims: employee.nbr_interims }, { where: {id: employee.id }});

    await interim.destroy();

    res.status(200).json({
        success: "Success",
        message: "Interim successfully deleted"
    })
}

const listCanApplicant = async (adminId) => {
    // verify admin existing
    let admin = await db.admin.findOne({ where: { id: adminId }});
    if(!admin) {
        return [];
    }
    
    // get all employee that admin can applicant
    let adminEmployees = await db.adminEmployee.findAll({
        where: {
            [Op.and]: [
                { isApplicant: true },
                { AdmnistratorId: admin.id }
            ]
        }
    });
    
    // get employees
    var employees = [];
    let employee;
    for(let i = 0; i < adminEmployees.length; i++) {
        if(adminEmployees[i].employeeId) {
            employee = await db.employee.findByPk(adminEmployees[i].employeeId);
            if(employee) {
                let r = await FunctionController.getFunctionEmployee(employee.id);
                if(r) {
                    employee.fonction = r.nameFunction;
                }
                else {
                    employee.fonction = '';
                }
                employees.push(employee);                
            }
        }
    };    

    return employees
}

const listCanNotApplicant = async (adminId) => {
    // verify admin existing
    let admin = await db.admin.findOne({ where: { id: adminId }});
    if(!admin) {
        return [];
    }
    
    // get all employee that admin can applicant
    let adminEmployees = await db.adminEmployee.findAll({
        where: {
            [Op.and]: [
                { isApplicant: true },
                { AdmnistratorId: admin.id }
            ]
        }
    });
    
    // get employees
    var employees = await db.employee.findAll();
    var data = [];

    for(const employee of employees) {
        const id = employee.id;

        // Verifier si l'ID employee n'existe pas dans adminEmployee
        if(!adminEmployees.some(value => value.employeeId === id)) {
            let r = await FunctionController.getFunctionEmployee(employee.id);
            if(r) {
                employee.fonction = r.nameFunction;
            }
            else {
                employee.fonction = '';
            }
            data.push(employee);
        }
    }
    
    
    return data
}

const listCanValidate = async (adminId) => {
    // verify admin existing
    let admin = await db.admin.findOne({ where: { id: adminId }});
    if(!admin) {        
        return [];
    }

    // get all employee that admin can applicant
    let adminEmployees = await db.adminEmployee.findAll({
        where: {
            [Op.and]: [
                { isValidator: true },
                { AdmnistratorId: admin.id }
            ]
        }
    });

    // get employees
    let employees = [];
    let employee;
    for(let i = 0; i < adminEmployees.length; i++) {
        if(adminEmployees[i].employeeId) {
            employee = await db.employee.findByPk(adminEmployees[i].employeeId);
            if(employee) {
                let r = await FunctionController.getFunctionEmployee(employee.id);
                if(r) {
                    employee.fonction = r.nameFunction;
                }
                else {
                    employee.fonction = '';
                }
                employees.push(employee);                
            }
        }
    };    

    return employees
}

const listCanNotValidate = async (adminId) => {
    // verify admin existing
    let admin = await db.admin.findOne({ where: { id: adminId }});
    if(!admin) {
        return [];
    }
    
    // get all employee that admin can validate
    let adminEmployees = await db.adminEmployee.findAll({
        where: {
            [Op.and]: [
                { isValidator: true },
                { AdmnistratorId: admin.id }
            ]
        }
    });
    
    // get employees
    var employees = await db.employee.findAll();
    var data = [];

    for(const employee of employees) {
        const id = employee.id;

        // Verifier si l'ID employee n'existe pas dans adminEmployee
        if(!adminEmployees.some(value => value.employeeId === id)) {
            let r = await FunctionController.getFunctionEmployee(employee.id);
            if(r) {
                employee.fonction = r.nameFunction;
            }
            else {
                employee.fonction = '';
            }
            data.push(employee);
        }
    }
    
    
    return data
}

module.exports = {
    createEmployee,
    importEmployeeExcel,
    dataToValidateRegistration,
    getAllEmployee,
    getOneEmployee,
    updateEmployee,
    deleteEmployee,
    deleteInterim,
    informationImport,
    listCanApplicant,
    listCanNotApplicant,
    listCanValidate,
    listCanNotValidate,
}
