<?php

class salaries
{
    public static function cleanTmp()
    {
        // Nettoyage de la table temporaire des salairés
        db::query("TRUNCATE " . DB_T_TEMP_SALARIES);
        db::execute();
    }

    public static function getSalarieByidLocal(int $_idLocal)
    {
        // Récupération des données de l'excel au format Json
        db::query("SELECT * FROM " . DB_T_SALARIES . " WHERE idLocal = :idLocal");
        db::bind(':idLocal', $_idLocal);
        return db::single();
    }

    public static function getSalarieByLoginId(string $_loginId)
    {
        // Récupération des données de l'excel au format Json
        db::query("SELECT * FROM " . DB_T_SALARIES . " WHERE loginId = :loginId");
        db::bind(':loginId', $_loginId);
        return db::single();
    }

    public static function getSalarieById(int $_id)
    {
        // Récupération des données de l'excel au format Json
        db::query("SELECT * FROM " . DB_T_SALARIES . " WHERE id = :id");
        db::bind(':id', $_id);
        return db::single();
    }

    public static function getSalaries()
    {
        db::query("SELECT "
            . "idLocal, "
            . "loginId, "
            . "nom, "
            . "prenom, "
            . "sexe, "
            . "contrat, "
            . "IF(contrat = 1, 'Actif', 'Désactivé') AS texteContrat, "
            . "DATE_FORMAT(jourEntree, '%Y-%m-%d') AS jourEntree, "
            . "DATE_FORMAT(repriseContrat, '%Y-%m-%d') AS repriseContrat, "
            . "DATE_FORMAT(jourSortie, '%Y-%m-%d') AS jourSortie, "
            . "sel, "
            . "lieu, "
            . "cree, "
            . "maj, "
            . "IF(actif = 1, 'Actif', 'Désactivé') AS texteActif, "
            . "actif "
            . "FROM " . DB_T_SALARIES);
        return db::resultset();
    }

    public static function lastExcel()
    {
        db::query("SELECT MAX(id) AS id FROM " . DB_T_EXCEL);
        return db::single()["id"];
    }

    public static function lastExcelForSFTP()
    {
        db::query("SELECT MAX(id) AS id FROM " . DB_T_EXCEL . " WHERE forSFTP IS NOT NULL");
        return db::single()["id"];
    }

    public static function getExcelMd5(int $_id)
    {
        // Récupération des données de l'excel au format Json
        db::query("SELECT md5 FROM " . DB_T_EXCEL . " WHERE id = :id");
        db::bind(':id', $_id);
        return db::single()["md5"];
    }

    public static function insertExcel(array $_data)
    {
        db::query("INSERT INTO " . DB_T_EXCEL . " (nbSalaries, md5, json, dateData, id_user) VALUES (:nbSalaries, :md5, :json, :dateData, :id_user)");
        db::bind(':nbSalaries', $_data["nbSalaries"]);
        db::bind(':dateData', $_data["date"]);
        db::bind(':md5', $_data["md5File"]);
        db::bind(':json', base64_encode($_data["json"]));
        db::bind(':id_user', session::getId());

        try {
            db::execute();
            return TRUE;
        } catch (Exception $ex) {
            return FALSE;
        }
    }

    public static function getExcelJsonForSFTP(int $_id)
    {
        // Récupération des données de l'excel au format Json
        db::query("SELECT forSFTP, md5forSFTP, createForSFTP, contratForSFTP FROM " . DB_T_EXCEL . " WHERE id = :id");
        db::bind(':id', $_id);
        return db::single();
    }

    public static function deleteExcelJsonForSFTP(int $_id)
    {
        db::query("UPDATE " . DB_T_EXCEL . " SET "
            . "createForSFTP = NULL "
            . "WHERE id = :id");
        db::bind(':id', $_id);
        try {
            db::execute();
            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

    public static function getExcelJsonTransferForSFTP(string $_md5)
    {
        // Récupération des données de l'excel au format Json
        db::query("SELECT transfertForSFTP FROM " . DB_T_EXCEL . " WHERE md5forSFTP = :md5forSFTP");
        db::bind(':md5forSFTP', $_md5);
        return db::single()["transfertForSFTP"];
    }

    public static function getExcelJson(int $_id)
    {
        // Récupération des données de l'excel au format Json
        db::query("SELECT json FROM " . DB_T_EXCEL . " WHERE id = :id");
        db::bind(':id', $_id);
        return base64_decode(db::single()["json"]);
    }

    public static function getExcelName(int $_id)
    {
        // Récupération des données de l'excel au format Json
        db::query("SELECT 
        " .DB_T_EXCEL. ".md5, 
        " .DB_T_FILES. ".name 
        FROM " . DB_T_EXCEL . " 
        INNER JOIN " . DB_T_FILES . " ON " . DB_T_EXCEL . ".md5 = " . DB_T_FILES . ".id 
        WHERE " . DB_T_EXCEL . ".id = :id");
        db::bind(':id', $_id);
        return db::single()["name"];
    }

    public static function excelUpdateInProgress(int $_id, int $_action = 1)
    {
        db::query("UPDATE 
        " . DB_T_EXCEL . " 
        SET inProgress = :inProgress 
        WHERE id = :id");
        db::bind(':inProgress', $_action);
        db::bind(':id', $_id);
        try {
            db::execute();
            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

    public static function delete_excel(int $_id)
    {
        db::query("DELETE FROM " . DB_T_EXCEL . " WHERE id = :id");
        db::bind(':id', $_id);
        try {
            db::execute();
            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

    public static function excelGetInProgress()
    {
        db::query("SELECT 
        " .DB_T_EXCEL. ".id, 
        " .DB_T_EXCEL. ".md5, 
        " .DB_T_FILES. ".name 
        FROM " . DB_T_EXCEL . " 
        INNER JOIN " . DB_T_FILES . " ON " . DB_T_EXCEL . ".md5 = " . DB_T_FILES . ".id 
        WHERE " . DB_T_EXCEL . ".inProgress = 1");
        return db::single();
    }

    public static function getExcelArray(int $_id)
    {
        return json_decode(self::getExcelJson($_id));
    }

    public static function excelToMysql(array $_value)
    {
        if ($_value[4] == "Actif") {
            $_value[4] = 1;
        } else {
            $_value[4] = 0;
        }

        return array(
            "idLocal" => $_value[0],
            "loginId" => $_value[7],
            "nom" => core::cleanAccent($_value[1]),
            "prenom" => core::cleanAccent($_value[2]),
            "sexe" => $_value[3],
            "contrat" => $_value[4],
            "jourEntree" => $_value[5],
            "lieu" => core::cleanAccent($_value[6]),
            "actif" => 1
        );
    }

    public static function createTmp(string $_excel)
    {
        db::query("SELECT idLocal, loginId, nom, prenom, sexe, contrat, jourEntree, lieu, actif FROM " . DB_T_SALARIES);
        $row = db::resultset();
        if (!empty($row)) {
            foreach ($row as $salaries) {
                db::query("INSERT INTO " . DB_T_TEMP_SALARIES . " (idLocal, loginId, nom, prenom, sexe, contrat, jourEntree, lieu, actif, new, excel) "
                . "VALUES (:idLocal, :loginId, :nom, :prenom, :sexe, :contrat, :jourEntree, :lieu, :actif, :new, :excel)");
                db::bind(':idLocal', $salaries["idLocal"]);
                db::bind(':loginId', $salaries["loginId"]);
                db::bind(':nom', $salaries["nom"]);
                db::bind(':prenom', $salaries["prenom"]);
                db::bind(':sexe', $salaries["sexe"]);
                db::bind(':contrat', $salaries["contrat"]);
                db::bind(':jourEntree', $salaries["jourEntree"]);
                db::bind(':lieu', $salaries["lieu"]);
                db::bind(':actif', 0);
                db::bind(':new', 0);
                db::bind(':excel', $_excel);
                db::execute();
            }
        }
    }

    public static function updateInactiveTempSalarie()
    {
        db::query("UPDATE " . DB_T_TEMP_SALARIES . " SET "
            . "log = :log "
            . "WHERE actif = :actif");
        db::bind(':log', "DISABLE");
        db::bind(':actif', 0);
        try {
            db::execute();
            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

    public static function updateJsonExcel(array $_json)
    {
        db::query("UPDATE " . DB_T_EXCEL . " SET "
            . "goMysql = current_timestamp(), "
            . "log = :log "
            . "WHERE id = :id");
        db::bind(':log', $_json["json"]);
        db::bind(':id', $_json["excel"]);
        try {
            db::execute();
            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

    public static function update_temp_salaries(array $_new_salaries, string $_excel)
    {
        $cp["INSERT"]["SUCCESS"] = 0;
        $cp["INSERT"]["ERROR"] = 0;
        $cp["UPDATE"]["SUCCESS"] = 0;
        $cp["UPDATE"]["ERROR"] = 0;
        $changeStatutContrat = NULL;

        foreach ($_new_salaries as $key => $value) {
            $sql = $change = NULL;
            if ($key > 0) {
                $tmp = self::excelToMysql($value);
                if(!is_int($tmp["idLocal"])) {
                    alert::recError("Une valeur dans le fichie n'est pas conforme à l'attendu (Ligne " . $key . ")");
                    self::cleanTmp();
                    self::excelUpdateInProgress(self::lastExcel(), 0);
                    return FALSE;
                }
                $salarieByidLocal = self::getSalarieByidLocal($tmp["idLocal"]);

                if (isset($salarieByidLocal["idLocal"])) {
                    $tmp_sql = "";
                    if ($tmp["loginId"] != $salarieByidLocal["loginId"]) {
                        $tmp_sql .= "loginId = :loginId, ";
                        $change = 1;
                    }
                    if ($tmp["contrat"] != $salarieByidLocal["contrat"]) {
                        $tmp_sql .= "contrat = :contrat, ";
                        $change = 1;

                        // Indentifier les cas d'arrêt ou de reprise de contrat
                        if ($tmp["contrat"] == 0 and $salarieByidLocal["contrat"] == 1) {
                            $changeStatutContrat[$salarieByidLocal["idLocal"]] = "end";
                        } else {
                            $changeStatutContrat[$salarieByidLocal["idLocal"]] = "start";
                        }
                        // Indentifier les cas d'arrêt ou de reprise de contrat    
                    }
                    if ($tmp["lieu"] != $salarieByidLocal["lieu"]) {
                        $tmp_sql .= "lieu = :lieu, ";
                        $change = 1;
                    }
                    if ($tmp["actif"] != $salarieByidLocal["actif"]) {
                        $change = 1;
                    } else {
                        $forSFTP["actif"] = NULL;
                    }

                    $tmp_sql .= "actif = :actif, ";

                    if ($change == 1) {

                        db::query($sql = "UPDATE " . DB_T_TEMP_SALARIES . " SET " . $tmp_sql . " log = :log WHERE idLocal = :idLocal");

                        $log = NULL;

                        if ($tmp["loginId"] != $salarieByidLocal["loginId"]) {
                            db::bind(':loginId', $tmp["loginId"]);
                            if ($log == "") {
                                $log .= "UPDATE ";
                            }
                            $log .= "loginId ";
                        }
                        if ($tmp["contrat"] != $salarieByidLocal["contrat"]) {
                            db::bind(':contrat', $tmp["contrat"]);
                            if ($log == "") {
                                $log .= "UPDATE ";
                            }
                            $log .= "contrat ";
                        }
                        if ($tmp["lieu"] != $salarieByidLocal["lieu"]) {
                            db::bind(':lieu', $tmp["lieu"]);
                            if ($log == "") {
                                $log .= "UPDATE ";
                            }
                            $log .= "lieu ";
                        }
                        if ($tmp["actif"] != $salarieByidLocal["actif"]) {
                            if ($log == "") {
                                $log .= "UPDATE ";
                            }
                            $log .= "actif ";
                        }

                        db::bind(':actif', 1);

                        if ($change == 1) {
                            db::bind(':log', $log);
                        } else {
                            db::bind(':log', NULL);
                        }

                        db::bind(':idLocal', $tmp["idLocal"]);

                        try {
                            db::execute();
                            $cp["UPDATE"]["SUCCESS"]++;
                        } catch (Exception $ex) {
                            $cp["UPDATE"]["ERROR"]++;
                        }
                    } else {
                        db::query("UPDATE " . DB_T_TEMP_SALARIES . " SET actif = :actif WHERE idLocal = :idLocal");
                        db::bind(':actif', 1);
                        db::bind(':idLocal', $tmp["idLocal"]);
                        db::execute();
                    }
                } else {

                    db::query("INSERT INTO " . DB_T_TEMP_SALARIES . " (idLocal, loginId, nom, prenom, sexe, contrat, jourEntree, lieu, actif, new, excel, log) "
                        . "VALUES (:idLocal, :loginId, :nom, :prenom, :sexe, :contrat, :jourEntree, :lieu, :actif, :new, :excel, :log)");
                    db::bind(':idLocal', $tmp["idLocal"]);
                    db::bind(':loginId', $tmp["loginId"]);
                    db::bind(':nom', $tmp["nom"]);
                    db::bind(':prenom', $tmp["prenom"]);
                    db::bind(':sexe', $tmp["sexe"]);
                    db::bind(':contrat', $tmp["contrat"]);
                    db::bind(':jourEntree', $tmp["jourEntree"]);
                    db::bind(':lieu', $tmp["lieu"]);
                    db::bind(':actif', 1);
                    db::bind(':new', 1);
                    db::bind(':excel', $_excel);
                    db::bind(':log', "INSERT");
                    try {
                        db::execute();
                        $cp["INSERT"]["SUCCESS"]++;
                    } catch (Exception $ex) {
                        $cp["INSERT"]["ERROR"]++;
                    }
                }
            }
        }

        ($changeStatutContrat != NULL) ? self::recContratForSFTP($_excel, $changeStatutContrat) : "";

        if ($cp["INSERT"]["ERROR"] != 0 or $cp["INSERT"]["ERROR"] != 0) {
            alert::recError("Une erreur s'est produite lors de la mise en cache.");
            return TRUE;
        } else {
            alert::recSuccess("La mise en cache a été réalisée avec succès.");
            return TRUE;
        }
    }

    private static function recContratForSFTP(int $_idExcel, array $_data)
    {
        db::query("UPDATE " . DB_T_EXCEL . " SET "
            . "contratForSFTP = :contratForSFTP "
            . "WHERE id = :id");
        db::bind(':contratForSFTP', json_encode($_data));
        db::bind(':id', $_idExcel);
        try {
            db::execute();
            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

    public static function updateSalaries(int $_excel)
    {
        $cp["INSERT"]["SUCCESS"] = 0;
        $cp["INSERT"]["ERROR"] = 0;
        $cp["DISABLE"]["SUCCESS"] = 0;
        $cp["DISABLE"]["ERROR"] = 0;
        $cp["UPDATE"]["SUCCESS"] = 0;
        $cp["UPDATE"]["ERROR"] = 0;
        $cp["forSFTP"] = 0;

        $updateContrat = json_decode(self::getExcelJsonForSFTP($_excel)["contratForSFTP"], TRUE);

        $jourSortie = date("Y-m-d 00:00:00");
        $dateReprise = date("Y-m-d 00:00:00");

        db::query("SELECT idLocal, loginId, nom, prenom, sexe, contrat, jourEntree, lieu, actif, new, log FROM " . DB_T_TEMP_SALARIES);
        $row = db::resultset();

        if (!empty($row)) {
            foreach ($row as $key => $salaries) {
                $forSFTP = $reprise = NULL;

                if ($salaries["log"] == NULL) {

                    $forSFTP["action"] = "valide";
                    $forSFTP["idLocal"] = $salaries["idLocal"];
                    $forSFTP["loginId"] = $salaries["loginId"];
                    $forSFTP["contrat"] = $salaries["contrat"];
                    $forSFTP["jourEntree"] = $salaries["jourEntree"];
                    $forSFTP["jourSortie"] = NULL;
                    $forSFTP["repriseContrat"] = NULL;
                    $forSFTP["actif"] = 1;
                    $SFTP[$cp["forSFTP"]++] = $forSFTP;
                } elseif ($salaries["log"] == "INSERT") {
                    db::query("INSERT INTO " . DB_T_SALARIES . " (idLocal, loginId, nom, prenom, sexe, contrat, jourEntree, jourSortie, sel, lieu, actif) "
                        . "VALUES (:idLocal, :loginId, :nom, :prenom, :sexe, :contrat, :jourEntree, :jourSortie, :sel, :lieu, :actif)");

                    db::bind(':idLocal', $salaries["idLocal"]);
                    db::bind(':loginId', $salaries["loginId"]);
                    db::bind(':nom', $salaries["nom"]);
                    db::bind(':prenom', $salaries["prenom"]);
                    db::bind(':sexe', $salaries["sexe"]);
                    db::bind(':contrat', $salaries["contrat"]);
                    db::bind(':jourEntree', $salaries["jourEntree"]);
                    db::bind(':jourSortie', NULL);
                    db::bind(':sel', md5($salaries["idLocal"] . time() . rand(100000000000, 999999999999)));
                    db::bind(':lieu', $salaries["lieu"]);
                    db::bind(':actif', $salaries["actif"]);

                    try {
                        db::execute();
                        $cp["INSERT"]["SUCCESS"]++;
                    } catch (Exception $ex) {
                        $cp["INSERT"]["ERROR"]++;
                    }

                    $forSFTP["action"] = "insert";
                    $forSFTP["idLocal"] = $salaries["idLocal"];
                    $forSFTP["loginId"] = $salaries["loginId"];
                    $forSFTP["contrat"] = $salaries["contrat"];
                    $forSFTP["jourEntree"] = $salaries["jourEntree"];
                    $forSFTP["jourSortie"] = NULL;
                    $forSFTP["repriseContrat"] = NULL;
                    $forSFTP["actif"] = 1;
                    $SFTP[$cp["forSFTP"]++] = $forSFTP;
                } elseif ($salaries["log"] == "DISABLE") {
                    db::query("UPDATE " . DB_T_SALARIES . " SET "
                        . "jourSortie = :jourSortie, "
                        . "maj = CURRENT_TIMESTAMP(), "
                        . "actif = :actif "
                        . "WHERE idLocal = :idLocal");

                    db::bind(':jourSortie', $jourSortie);
                    db::bind(':actif', 0);
                    db::bind(':idLocal', $salaries["idLocal"]);

                    try {
                        db::execute();
                        $cp["DISABLE"]["SUCCESS"]++;
                    } catch (Exception $ex) {
                        $cp["DISABLE"]["ERROR"]++;
                    }

                    $forSFTP["action"] = "disabled";
                    $forSFTP["idLocal"] = $salaries["idLocal"];
                    $forSFTP["loginId"] = $salaries["loginId"];
                    $forSFTP["contrat"] = $salaries["contrat"];
                    $forSFTP["jourEntree"] = $salaries["jourEntree"];
                    $forSFTP["jourSortie"] = $jourSortie;
                    $forSFTP["repriseContrat"] = NULL;
                    $forSFTP["actif"] = 0;
                    $SFTP[$cp["forSFTP"]++] = $forSFTP;
                } else {

                    $forSFTP["action"] = "update";
                    $forSFTP["idLocal"] = $salaries["idLocal"];
                    $forSFTP["loginId"] = $salaries["loginId"];
                    $forSFTP["contrat"] = $salaries["contrat"];

                    if (is_array($updateContrat) and array_key_exists($salaries["idLocal"], $updateContrat)) {
                        if ($updateContrat[$salaries["idLocal"]] == "start") {
                            $forSFTP["jourEntree"] = $dateReprise;
                            $forSFTP["jourSortie"] = NULL;
                            $forSFTP["repriseContrat"] = $dateReprise;
                            $forSFTP["actif"] = 1;
                            $reprise = $dateReprise;
                        } elseif ($updateContrat[$salaries["idLocal"]] == "end") {
                            $forSFTP["jourEntree"] = $salaries["jourEntree"];
                            $forSFTP["jourSortie"] = $jourSortie;
                            $forSFTP["repriseContrat"] = NULL;
                            $forSFTP["actif"] = 0;
                        }
                    } else {
                        $forSFTP["jourEntree"] = $salaries["jourEntree"];
                        $forSFTP["jourSortie"] = NULL;
                        $forSFTP["repriseContrat"] = NULL;
                        $forSFTP["actif"] = $salaries["actif"];
                    }

                    $SFTP[$cp["forSFTP"]++] = $forSFTP;

                    db::query("UPDATE " . DB_T_SALARIES . " SET "
                        . "loginId = :loginId, "
                        . "contrat = :contrat, "
                        . "lieu = :lieu, "
                        . "repriseContrat = :repriseContrat, "
                        . "jourSortie = :jourSortie, "
                        . "maj = CURRENT_TIMESTAMP(), "
                        . "actif = :actif "
                        . "WHERE idLocal = :idLocal");

                    db::bind(':loginId', $salaries["loginId"]);
                    db::bind(':contrat', $salaries["contrat"]);
                    db::bind(':lieu', $salaries["lieu"]);
                    db::bind(':repriseContrat', $reprise);
                    db::bind(':jourSortie', NULL);
                    db::bind(':actif', $salaries["actif"]);
                    db::bind(':idLocal', $salaries["idLocal"]);

                    try {
                        db::execute();
                        $cp["UPDATE"]["SUCCESS"]++;
                    } catch (Exception $ex) {
                        $cp["UPDATE"]["ERROR"]++;
                    }
                }
            }

            if ($cp["INSERT"]["SUCCESS"] == 1) {
                alert::recSuccess("SUCCESS : " . $cp["INSERT"]["SUCCESS"] . " salarié traité.");
            } elseif ($cp["INSERT"]["SUCCESS"] > 1) {
                alert::recSuccess("SUCCESS : " . $cp["INSERT"]["SUCCESS"] . " salariés traités.");
            }
            if ($cp["DISABLE"]["SUCCESS"] == 1) {
                alert::recSuccess("DISABLE : " . $cp["DISABLE"]["SUCCESS"] . " salarié traité.");
            } elseif ($cp["DISABLE"]["SUCCESS"] > 1) {
                alert::recSuccess("DISABLE : " . $cp["DISABLE"]["SUCCESS"] . " salariés traités.");
            }
            if ($cp["UPDATE"]["SUCCESS"] == 1) {
                alert::recSuccess("UPDATE : " . $cp["UPDATE"]["SUCCESS"] . " salarié traité.");
            } elseif ($cp["UPDATE"]["SUCCESS"] > 1) {
                alert::recSuccess("UPDATE : " . $cp["UPDATE"]["SUCCESS"] . " salariés traités.");
            }
            if ($cp["INSERT"]["ERROR"] == 1) {
                alert::recSuccess("SUCCESS : " . $cp["INSERT"]["SUCCESS"] . " salarié non traité.");
            } elseif ($cp["INSERT"]["ERROR"] > 1) {
                alert::recSuccess("SUCCESS : " . $cp["INSERT"]["SUCCESS"] . " salariés non traités.");
            }
            if ($cp["DISABLE"]["ERROR"] == 1) {
                alert::recSuccess("DISABLE : " . $cp["DISABLE"]["SUCCESS"] . " salarié non traité.");
            } elseif ($cp["DISABLE"]["ERROR"] > 1) {
                alert::recSuccess("DISABLE : " . $cp["DISABLE"]["SUCCESS"] . " salariés non traités.");
            }
            if ($cp["UPDATE"]["ERROR"] == 1) {
                alert::recSuccess("UPDATE : " . $cp["UPDATE"]["SUCCESS"] . " salarié non traité.");
            } elseif ($cp["UPDATE"]["ERROR"] > 1) {
                alert::recSuccess("UPDATE : " . $cp["UPDATE"]["SUCCESS"] . " salariés non traités.");
            }

            (self::recForSFTP($SFTP, $_excel)) ? alert::recSuccess("Les données d'exportation pour ProWeb ont été enregistrées") : alert::recError("Les données d'exportation pour ProWeb n'ont pas pu être enregistrées");
        }
    }

    private static function recForSFTP(array $_array, int $_idExcel)
    {
        $json = json_encode($_array);

        db::query("UPDATE " . DB_T_EXCEL . " SET "
            . "forSFTP = :forSFTP ,"
            . "md5forSFTP = :md5forSFTP "
            . "WHERE id = :id");
        db::bind(':forSFTP', $json);
        db::bind(':md5forSFTP', md5($json));
        db::bind(':id', $_idExcel);
        try {
            db::execute();
            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

    public static function createRapport()
    {
        $log = NULL;

        db::query("SELECT idLocal, loginId, nom, prenom, contrat, jourEntree, lieu, excel, log FROM " . DB_T_TEMP_SALARIES . " WHERE log IS NOT NULL");
        $row = db::resultset();

        if ($row != NULL) {

            foreach ($row as $key => $salaries) {
                if ($salaries["log"] == "INSERT") {
                    $log["json"][] = array(
                        "action" => "INSERT",
                        "excel" => $salaries["excel"],
                        "idLocal" => $salaries["idLocal"],
                        "loginId" => $salaries["loginId"],
                        "nom" => $salaries["nom"],
                        "prenom" => $salaries["prenom"],
                        "jourEntree" => $salaries["jourEntree"],
                        "contrat" => $salaries["contrat"],
                        "lieu" => $salaries["lieu"]
                    );
                } elseif ($salaries["log"] == "DISABLE") {
                    $log["json"][] = array(
                        "action" => "DISABLE",
                        "excel" => $salaries["excel"],
                        "idLocal" => $salaries["idLocal"],
                        "loginId" => $salaries["loginId"],
                        "nom" => $salaries["nom"],
                        "prenom" => $salaries["prenom"],
                        "jourEntree" => $salaries["jourEntree"],
                        "contrat" => $salaries["contrat"],
                        "lieu" => $salaries["lieu"]
                    );
                } else {
                    $tmp_log = array("action" => "UPDATE", "excel" => $salaries["excel"], "nom" => $salaries["nom"], "prenom" => $salaries["prenom"]);
                    $tmp = explode(" ", $salaries["log"]);
                    foreach ($tmp as $key => $value) {
                        if ($key > 0) {
                            switch ($value) {
                                case "loginId":
                                    $tmp_log["loginId"] = $salaries["loginId"];
                                    break;
                                case "contrat":
                                    $tmp_log["contrat"] = $salaries["contrat"];
                                    break;
                                case "lieu":
                                    $tmp_log["lieu"] = $salaries["lieu"];
                                    break;
                            }
                        }
                    }

                    $log["json"][] = $tmp_log;
                }
            }

            $log["json"] = json_encode($log["json"]);
            $log["excel"] = $salaries["excel"];
        } else {
            $log["json"] = NULL;
            $log["excel"] = NULL;
        }

        return $log;
    }

    public static function countTmpSalaries()
    {
        db::query("SELECT COUNT(*) AS nb FROM " . DB_T_TEMP_SALARIES);
        return db::single()["nb"];
    }

    public static function dataForSFTP()
    {
        $lastExcel = self::lastExcelForSFTP();
        $forSFTP = self::getExcelJsonForSFTP($lastExcel);
        $csv = "OD_" . date("d-m-Y") . ".csv";

        $tmpSFTP = fopen(SFTP_LOCAL . $csv, "w");
        fputcsv($tmpSFTP, array("loginId", "jourSortie"), ";");

        foreach (json_decode($forSFTP["forSFTP"], TRUE) as $salarie) {

            $tmpSalarie = NULL;
// TODO Extract
            if (isset($salarie["loginId"]) and $salarie["loginId"] != "" and isset($salarie["jourSortie"])) {
                $tmpSalarie["loginId"] = $salarie["loginId"];
                $tmpSalarie["jourSortie"] = $salarie["jourSortie"];
                fputcsv($tmpSFTP, $tmpSalarie, ";");
            }
        }
        self::recDateForSFTP($lastExcel);
    }

    private static function recDateForSFTP(int $_idExcel)
    {
        db::query("UPDATE " . DB_T_EXCEL . " SET "
            . "createForSFTP = CURRENT_TIMESTAMP() "
            . "WHERE id = :id");
        db::bind(':id', $_idExcel);
        try {
            db::execute();
            return TRUE;
        } catch (Exception $e) {
            return FALSE;
        }
    }

    public static function ifSubmitLastForSFTP()
    {
        $lastExcel = self::lastExcel();
        $forSFTP = self::getExcelJsonForSFTP($lastExcel);
        return (@$forSFTP["md5forSFTP"] != NULL and @$forSFTP["createForSFTP"] == NULL) ? TRUE : FALSE;
    }

    public static function checkSalarieByMatricule(string $_string)
    {
        db::query("SELECT "
            . "id, "
            . "nom, "
            . "prenom, "
            . "contrat, "
            . "actif "
            . "FROM " . DB_T_SALARIES . " "
            . "WHERE idLocal = :idLocal");
        db::bind(':idLocal', intval($_string));
        $salarie = db::single();

        if (isset($salarie["id"])) {
            if ($salarie["actif"] == 0) {
                $return["error"] = "<div>Ce matricule n'est plus sous contrat Capgemini Consulting.</div>";
                $return["class"] = "danger";
            } elseif ($salarie["contrat"] == 0) {
                $return["error"] = "<div>Ce matricule est en suspension de contrat chez Capgemini Consulting mais peut-être pris en charge par le CSE.</div>";
                $return["class"] = "success";
            } else {
                $return["success"] = "<div>Ce matricule est sous contrat Capgemini Consulting.</div>";
                $return["class"] = "success";
            }
            $return["identity"] = $salarie["prenom"] . " " . $salarie["nom"];
        } else {
            $return["error"] = "<div>Ce matricule n'est pas ou plus rattaché à Capgemini Consulting.</div>";
            $return["class"] = "danger";
        }
        return $return;
    }
}
