<?php

class document
{
    
    static public function uploadFile(array $_temp){
        $tmp = file::record($_temp, DIR_DATAS_DOCS);
        if($tmp != FALSE){
            return $tmp;
        } else {
            return FALSE;
        }
    }

    static public function readFile(string $_id){
        return file::download($_id, DIR_DATAS_DOCS);
    }

    static public function deleteFile(string $_id){
        db::query("DELETE FROM ". DB_T_DOCUMENT_FILES ." WHERE id_files = :id_files");
        db::bind(':id_files', $_id);
        db::execute();

        file::delete($_id, DIR_DATAS_DOCS);
    }

    static public function deleteFiles(float $_id){
        foreach (self::getFiles($_id) as $file) {

            db::query("DELETE FROM ". DB_T_DOCUMENT_FILES ." WHERE id_files = :id_files");
            db::bind(':id_files', $file["id"]);
            db::execute();

            file::delete($file["id"], DIR_DATAS_DOCS);
        }
    }

    static public function getTypes(){
        db::query("SELECT "
            . "id, label "
            . "FROM " . DB_T_TYPE_DOCUMENT . " "
            . "ORDER BY " . DB_T_TYPE_DOCUMENT . ".id ASC");

        foreach (db::resultset() as $value) {
            $return[$value["id"]] = $value["label"];
        }
        return $return;
    }

    public static function delete(float $_id)
    {
        try {
            db::query("DELETE FROM ". DB_T_DOCUMENT_TAGS ." WHERE id_documents = :id_documents");
            db::bind(':id_documents', $_id);
            db::execute();

            self::deleteFiles($_id);
            
            db::query("DELETE FROM " . DB_T_DOCUMENTS . " WHERE id = :id");
            db::bind(':id', $_id);
            db::execute();
            
            alert::recSuccess("Le document vient d'être supprimé");
            return TRUE;
        } catch (Exception $ex) {
            alert::recError("Erreur à la suppression du document");
            return FALSE;
        }
    }

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

    private static function addFile(float $_idDocument, string $_idFile, int $_principal = NULL)
    {
        db::query("INSERT INTO " . DB_T_DOCUMENT_FILES . " (id_documents, id_files, principal) VALUES (:id_documents, :id_files, :principal)");
        db::bind(':id_documents', $_idDocument);
        db::bind(':id_files', $_idFile);
        db::bind(':principal', $_principal);
        try {
            db::execute();
            return TRUE;
        } catch (Exception $ex) {
            echo "error";
            echo $ex;
            exit();
            return FALSE;
        }
    }

    private static function addTags(float $_idDocument, string $_tags = NULL, float $_type)
    {
        db::query("DELETE FROM " . DB_T_DOCUMENT_TAGS . " WHERE id_documents = :id_documents AND id_type_tags = :id_type_tags");
        db::bind(':id_documents', $_idDocument);
        db::bind(':id_type_tags', $_type);
        db::execute();
        
        if($_tags != NULL){ 
            $tags = explode(",", $_tags);

            $sqlMaj = "";
            foreach ($tags as $tag) {
                $sqlMaj .= " (:id_documents, ".$tag.", :id_type_tags),";
            }

            $sqlMaj = substr($sqlMaj, 0, -1);

            db::query("INSERT INTO " . DB_T_DOCUMENT_TAGS . " (id_documents, id_tags, id_type_tags) VALUES" . $sqlMaj);
            db::bind(':id_documents', $_idDocument);
            db::bind(':id_type_tags', $_type);
            try {
                db::execute();
                return TRUE;
            } catch (Exception $ex) {
                return FALSE;
            }
        }
    }

    public static function getOrphanTags(){
        db::query("SELECT
        " . DB_T_TAGS . ".id
        FROM " . DB_T_TAGS . "
        LEFT JOIN " . DB_T_DOCUMENT_TAGS . " ON tags.id = " . DB_T_DOCUMENT_TAGS . ".id_tags
        WHERE " . DB_T_DOCUMENT_TAGS . ".id_tags IS NULL AND " . DB_T_TAGS . ".id_type = 2");
        return db::resultset();
    }

    public static function cleanOrphanTags(){
        foreach (self::getOrphanTags() as $value) {
            db::query("DELETE FROM ". DB_T_TAGS ." WHERE id = :id");
            db::bind(':id', $value["id"]);
            db::execute();
        }
    }
    
    public static function add()
    {   
        session::setTemp(core::getPost(), "document");
        $file = core::getFiles("document-import");
        $md5 = md5_file($file["tmp_name"]);
        if(file::findM5($md5) == TRUE){
            alert::recError("Ce fichier a déjà été utilisé : " . $file["name"]);
        } else {
            db::query("INSERT INTO " . DB_T_DOCUMENTS . " (id_type, titre, date, deadline, description, montant, id_user) VALUES (:id_type, :titre, :date, :deadline, :description, :montant, :id_user)");
            db::bind(':id_type', core::getPost("id_type"));
            db::bind(':titre', core::getPost("titre"));
            db::bind(':date', core::getPost("date"));
            db::bind(':deadline', core::getPost("deadline"));
            db::bind(':description', core::getPost("description"));
            db::bind(':montant', !empty(core::getPost("montant")) ? floatval(core::getPost("montant")) : 0.0);
            db::bind(':id_user', session::getId());
            
            try {
                db::execute();
                $lastId = db::lastInsertId();
            } catch (Exception $ex) {
                alert::recError("Erreur à l'enregistrement de la fiche : " . core::getPost("titre"));
                if(debug::isFile("debug")) { alert::recError("Stack : " . $ex); }
                return FALSE;
            }

            try {
                $idFile = self::uploadFile($file);
            } catch (Exception $ex) {
                alert::recError("Erreur à l'enregistrement de la pièce jointe : " . $idFile);
                if(debug::isFile("debug")) { alert::recError("Stack : " . $ex); }
                return FALSE;
            }

            try {
                self::addFile($lastId, $idFile, 1);
            } catch (Exception $ex) {
                alert::recError("Erreur à l'enregistrement de la liaison : " . $idFile);
                if(debug::isFile("debug")) { alert::recError("Stack : " . $ex); }
                return FALSE;
            }

            try { 
                $tagsUser = tags::textToId(core::getPost("tagsUser"), 1);
                self::addTags($lastId, $tagsUser, 1);

                $tagsSupplier = tags::textToId(core::getPost("tagsSupplier"), 2);
                self::addTags($lastId, $tagsSupplier, 2);
                
            } catch (Exception $ex) {
                alert::recError("Erreur à l'enregistrement de la liaison : " . $idFile);
                if(debug::isFile("debug")) { alert::recError("Stack : " . $ex); }
                return FALSE;
            }

            return $lastId;
        }
    }

    public static function update()
    {
        if(core::ifFiles("attachement-document") == TRUE){ 
            $file = core::getFiles("attachement-document"); 
            $md5 = md5_file($file["tmp_name"]);
        } 
        if(isset($md5) AND file::findM5($md5) == TRUE){
            alert::recError("Le fichier \"" . $file["name"] . "\" a déjà été utilisé");
            session::setTemp(core::getPost(), "document");
        } else {
            if(isset($md5)){
                try {
                    $idFile = self::uploadFile($file);
                } catch (Exception $ex) {
                    alert::recError("Erreur à l'enregistrement de la pièce jointe : " . $idFile);
                    return FALSE;
                }

                try {
                    self::addFile(core::getPost("id"), $idFile, 0);
                } catch (Exception $ex) {
                    alert::recError("Erreur à l'enregistrement de la liaison : " . $idFile);
                    return FALSE;
                }
            }
            
            if(core::getPost("delete-attachement")){
                foreach (core::getPost("delete-attachement") as $deleteAttach) {
                    self::deleteFile($deleteAttach);
                }
            }

            if(core::getPost("default-attachement")){
                self::principalFile(core::getPost("id"), core::getPost("default-attachement"));
            }

            try { 
                $tagsUser = tags::textToId(core::getPost("tagsUser"), 1);
                self::addTags(core::getPost("id"), $tagsUser, 1);
                
                $tagsSupplier = tags::textToId(core::getPost("tagsSupplier"), 2);
                self::addTags(core::getPost("id"), $tagsSupplier, 2);
            } catch (Exception $ex) {
                alert::recError("Erreur à l'enregistrement de la liaison : " . core::getPost("id"));
                return FALSE;
            }

            if(core::ifPost("date_done") AND core::getPost("date_done") != ""){
                $sql = ", id_user_done = :id_user_done, date_done = :date_done ";
            } else {
                $sql = "";
            }
            
            db::query("UPDATE " . DB_T_DOCUMENTS . " SET "
                    . "id_type = :id_type, "
                    . "titre = :titre, "
                    . "date = :date, "
                    . "deadline = :deadline, "
                    . "description = :description, "
                    . "montant = :montant "
                    . $sql
                    . "WHERE id = :id");
            
            db::bind(':id_type', core::getPost("id_type"));
            db::bind(':titre', core::getPost("titre"));
            db::bind(':date', core::getPost("date"));
            db::bind(':deadline', core::getPost("deadline"));
            db::bind(':description', core::getPost("description"));
            db::bind(':montant', core::getPost("montant"));
            db::bind(':id', core::getPost("id"));

            if(core::ifPost("date_done") AND core::getPost("date_done") == TRUE){
                db::bind(':id_user_done', session::getId());
                db::bind(':date_done', core::getPost("date_done"));
            }
            
            try {
                    db::execute();
                    alert::recSuccess("Document mis à jour avec succès");
                    return TRUE;
                } catch (Exception $ex) {
                    alert::recError("Erreur de mise à jour du document : " . $ex);
                    return FALSE;
                }
        }
    }

    static public function printFile(string $_id) {
        $filePatch = file::download($_id, DIR_DATAS_DOCS);
        
        if (file_exists($filePatch) && is_readable($filePatch)) {
    
            $file_info = new finfo(FILEINFO_MIME_TYPE);
            $mime_type = $file_info->file($filePatch);
    
            // Vérification si le fichier est de type XML
            if ($mime_type === 'application/xml' || $mime_type === 'text/xml') {
                // Chargement du contenu XML
                $xml_content = file_get_contents($filePatch);
                xml::print($xml_content);
            } else {
                // Si ce n'est pas un fichier XML, comportement normal pour servir le fichier
                header('Content-Type: ' . $mime_type);
                header('Content-Length: ' . filesize($filePatch));
                readfile($filePatch);
            }
        } else {
            echo "Le fichier n'a pas été trouvé ou n'est pas lisible.";
        }
    }

    static public function getFile(string $_id) {
        $filePatch = file::download($_id, DIR_DATAS_DOCS);
        
        if (file_exists($filePatch) && is_readable($filePatch)) {
            $file_info = new finfo(FILEINFO_MIME_TYPE);
            $mime_type = $file_info->file($filePatch);
            header('Content-Type: ' . $mime_type);
            header('Content-Length: ' . filesize($filePatch));
            readfile($filePatch);
        } else {
            echo "Le fichier n'a pas été trouvé ou n'est pas lisible.";
        }
    }

    static public function get(float $_id){
        db::query("SELECT "
            . "" . DB_T_DOCUMENTS . ".id, "
            . "" . DB_T_DOCUMENTS . ".id_type, "
            . "" . DB_T_DOCUMENTS . ".titre, "
            . "" . DB_T_DOCUMENTS . ".date, "
            . "" . DB_T_DOCUMENTS . ".deadline, "
            . "" . DB_T_DOCUMENTS . ".description, "
            . "" . DB_T_DOCUMENTS . ".montant, "
            . "" . DB_T_DOCUMENTS . ".id_user_done, "
            . "" . DB_T_DOCUMENTS . ".date_done, "
            . "CONCAT(" . DB_T_USER . ".prenom, ' ', " . DB_T_USER . ".nom) AS doneUser "
            . "FROM " . DB_T_DOCUMENTS . " "
            . "LEFT JOIN " . DB_T_USER . " ON " . DB_T_USER . ".id = " . DB_T_DOCUMENTS . ".id_user_done "
            . "WHERE " . DB_T_DOCUMENTS . ".id = :id");
        db::bind(':id', $_id);
        $document = db::single();

        $document["tagsSupplier"] = self::getTags($_id, 2);
        $document["tagsUser"] = self::getTags($_id, 1);

        $files = self::getFiles($_id);

        return array("document" => $document, "files" => $files);
    }

    static public function getTags(float $_idDocument, float $_idTypeTags){
        db::query("SELECT "
            . "" . DB_T_TAGS . ".label "
            . "FROM " . DB_T_DOCUMENT_TAGS . " "
            . "INNER JOIN " . DB_T_TAGS . " ON " . DB_T_TAGS . ".id = " . DB_T_DOCUMENT_TAGS . ".id_tags "
            . "WHERE " . DB_T_DOCUMENT_TAGS . ".id_documents = :idDocument AND " . DB_T_DOCUMENT_TAGS . ".id_type_tags = :idTypeTags "
            . "ORDER BY " . DB_T_DOCUMENT_TAGS . ".creer ASC");
        db::bind(':idDocument', $_idDocument);
        db::bind(':idTypeTags', $_idTypeTags);
        $tmp = db::resultset();

        if(isset($tmp[0])){
            $return = NULL;
            foreach ($tmp as $value) {
                $return .= $value["label"].",";
            }
    
            $return = substr($return, 0, -1);
            return $return;
        } else {
            return NULL;
        }
        
    }

    static public function getFiles(float $_idDocument){
        db::query("SELECT "
            . "" . DB_T_FILES . ".id, "
            . "" . DB_T_FILES . ".name, "
            . "" . DB_T_FILES . ".size, "
            . "" . DB_T_FILES . ".creer, "
            . "" . DB_T_FILES . ".id_user, "
            . "CONCAT(" . DB_T_USER . ".prenom, ' ', " . DB_T_USER . ".nom) AS user, "
            . "" . DB_T_DOCUMENT_FILES . ".principal "
            . "FROM " . DB_T_DOCUMENT_FILES . " "
            . "INNER JOIN " . DB_T_FILES . " ON " . DB_T_FILES . ".id = " . DB_T_DOCUMENT_FILES . ".id_files "
            . "INNER JOIN " . DB_T_USER . " ON " . DB_T_USER . ".id = " . DB_T_FILES . ".id_user "
            . "WHERE " . DB_T_DOCUMENT_FILES . ".id_documents = :id "
            . "ORDER BY " . DB_T_FILES . ".creer");
        db::bind(':id', $_idDocument);
        $tmp = db::resultset();

        if(isset($tmp[0])){
            foreach ($tmp as $file) {
                if($file["principal"] == TRUE){
                    $return["principal"] = $file;
                } else {
                    $return[] = $file;
                }
            }

            if(empty($return["principal"])){
                $return["principal"] = $return[0];
                self::principalFile($_idDocument, $return["principal"]["id"]);
                unset($return[0]);
            }
            return $return;
        } else {
            return NULL;
        }
    }

    static public function principalFile(float $_idDocument, string $_idFile){
        db::query("UPDATE " . DB_T_DOCUMENT_FILES . " SET principal = :principal WHERE id_documents = :id_documents");
        db::bind(':principal', 0);
        db::bind(':id_documents', $_idDocument);
        db::execute();

        db::query("UPDATE " . DB_T_DOCUMENT_FILES . " SET principal = :principal WHERE id_documents = :id_documents AND id_files = :id_files");
        db::bind(':principal', 1);
        db::bind(':id_documents', $_idDocument);
        db::bind(':id_files', $_idFile);
        db::execute();
    }

    static public function getAssign(float $_id = NULL){

        $idUser = is_null($_id) ? session::getId() : $_id;
        $tags = user::getIdTags($idUser);

        $where = NULL;
        foreach ($tags AS $key => $value) {
            if($key == 0){
                $where = "WHERE " . DB_T_DOCUMENTS . ".id_user_done IS NULL AND (" . DB_T_DOCUMENT_TAGS . ".id_tags = " . $value . "";
            } else {
                $where .= " OR " . DB_T_DOCUMENT_TAGS . ".id_tags = " . $value . "";
            }
        }
        $where .= ")";

        db::query("SELECT 
        " . DB_T_DOCUMENTS . ".id, 
        " . DB_T_DOCUMENTS . ".titre, 
        " . DB_T_DOCUMENTS . ".date,        
        " . DB_T_DOCUMENTS . ".deadline, 
        " . DB_T_DOCUMENTS . ".description, 
        " . DB_T_DOCUMENTS . ".montant, 
            ( SELECT GROUP_CONCAT(" . DB_T_TAGS . ".label SEPARATOR ', ') 
            FROM  " . DB_T_DOCUMENT_TAGS . " 
            INNER JOIN " . DB_T_TAGS . " ON " . DB_T_TAGS . ".id = " . DB_T_DOCUMENT_TAGS . ".id_tags
            WHERE id_documents = " . DB_T_DOCUMENTS . ".id AND " . DB_T_DOCUMENT_TAGS . ".id_type_tags = 2 
            ORDER BY " . DB_T_DOCUMENT_TAGS . ".creer) AS tags, 
            ( SELECT GROUP_CONCAT(" . DB_T_TAGS . ".label SEPARATOR ', ') 
            FROM  " . DB_T_DOCUMENT_TAGS . " 
            INNER JOIN " . DB_T_TAGS . " ON " . DB_T_TAGS . ".id = " . DB_T_DOCUMENT_TAGS . ".id_tags
            WHERE id_documents = " . DB_T_DOCUMENTS . ".id AND " . DB_T_DOCUMENT_TAGS . ".id_type_tags = 1 
            ORDER BY " . DB_T_DOCUMENT_TAGS . ".creer) AS assign, 
        " . DB_T_TYPE_DOCUMENT . ".label 
        FROM " . DB_T_DOCUMENT_TAGS . " 
        INNER JOIN " . DB_T_DOCUMENTS . " ON " . DB_T_DOCUMENTS . ".id = " . DB_T_DOCUMENT_TAGS . ".id_documents
        INNER JOIN " . DB_T_TYPE_DOCUMENT . " ON " . DB_T_TYPE_DOCUMENT . ".id = " . DB_T_DOCUMENTS . ".id_type
        " . $where);

        return db::resultset();
    }

    static public function printAttachement(array $_attachs){
        $principal = $_attachs["principal"];
        echo '<ol class="list-group list-group-numbered">';
        echo '  <li class="list-group-item d-flex justify-content-between align-items-start" id="attach-'.$principal["id"].'">
                    <div class="ms-2 me-auto">
                        <div><span class="fw-bold">'.$principal["name"].'</span> ('.core::convertBytes($principal["size"]).')</div>
                        Chargé le '.core::convertDate($principal["creer"]).' par '.$principal["user"].'
                        <div id="select-attach-'.$principal["id"].'" style="color:red;"></div>
                    </div>
                        <div class="btn-group">
                            <button type="button" title="Voir le document" class="btn btn btn-outline-secondary" onclick="window.open(\'/document.php?id=' . $principal["id"] . '\', \'_blank\')">' . icon::getFont(["icon" => "bi bi-eye-fill"]) . '</button>
                            <button type="button" title="Télécharger le document" class="btn btn btn-outline-secondary" onclick="downloadFile(\'/document.php?id=' . $principal["id"] . '&download=1\', \''.$principal["name"].'\')">' . icon::getFont(["icon" => "bi bi-arrow-down-square-fill"]) . '</button>
                        </div>
                            </li>';
        foreach ($_attachs as $key => $attach) {
                if($key != "principal"){
                    echo '  <li class="list-group-item d-flex justify-content-between align-items-start" id="attach-'.$attach["id"].'">
                                <div class="ms-2 me-auto">
                                    <div><span class="fw-bold">'.$attach["name"].'</span> ('.core::convertBytes($attach["size"]).')</div>
                                    Chargé le '.core::convertDate($attach["creer"]).' par '.$attach["user"].'
                                    <div id="select-attach-'.$attach["id"].'"></div>
                                </div><div class="btn-group">
                                    <button type="button" title="Voir le document" class="btn btn btn-outline-secondary" onclick="window.open(\'/document.php?id=' . $attach["id"] . '\', \'_blank\')">' . icon::getFont(["icon" => "bi bi-eye-fill"]) . '</button>
                                    <button type="button" title="Télécharger le document" class="btn btn btn-outline-secondary" onclick="downloadFile(\'/document.php?id=' . $attach["id"] . '&download=1\', \''.$attach["name"].'\')">' . icon::getFont(["icon" => "bi bi-arrow-down-square-fill"]) . '</button>
                                    <button type="button" title="Document mis en avant" class="btn btn btn-outline-primary" onclick="defaultAttachment(\''.$attach["id"].'\')" id="button-default-'.$attach["id"].'">' . icon::getFont(["icon" => "bi bi-star-fill"]) . '</button>
                                    <button type="button" title="Supprimer ce document" class="btn btn-outline-danger" onclick="deleteAttachment(\''.$attach["id"].'\')" id="button-delete-'.$attach["id"].'">' . icon::getFont(["icon" => "bi bi-trash"]) . '</button>
                                </div>
                            </li>';
                }          
        }
        echo '</ol><br />';
    }

    static public function myAssign(?array $_tags = NULL){

        if($_tags == NULL){
            return NULL;
        } else {
            $where = NULL;
            foreach ($_tags AS $key => $value) {
                if($key == 0){
                    $where = "WHERE " . DB_T_DOCUMENTS . ".id_user_done IS NULL AND (" . DB_T_DOCUMENT_TAGS . ".id_tags = " . $value . "";
                } else {
                    $where .= " OR " . DB_T_DOCUMENT_TAGS . ".id_tags = " . $value . "";
                }
            }
            $where .= ")";
        }

        db::query("SELECT "
            . "COUNT(" . DB_T_DOCUMENT_TAGS . ".id_tags) AS nb "
            . "FROM " . DB_T_DOCUMENT_TAGS  . " "
            . "INNER JOIN " . DB_T_DOCUMENTS . " ON " . DB_T_DOCUMENTS . ".id = " . DB_T_DOCUMENT_TAGS . ".id_documents "
            . $where);
        return db::single()["nb"];
    }
    
    static public function badgeAlert(){
        $return = self::myAssign(user::getIdTags(session::getId()));
        return $return > 0 ? $return : NULL;
    }

    static public function assignMailDocument(){
        db::query("SELECT "
                    . "" . DB_T_USER . ".id, "
                    . "" . DB_T_USER . ".email, "
                    . "CONCAT(" . DB_T_USER . ".prenom, ' ', " . DB_T_USER . ".nom) AS name "
                    . "FROM " . DB_T_USER_TAGS . " "
                    . "INNER JOIN " . DB_T_USER . " ON " . DB_T_USER . ".id = " . DB_T_USER_TAGS . ".id_user "
                    . "WHERE (" . DB_T_USER_TAGS . ".id_tags = 1 OR " . DB_T_USER_TAGS . ".id_tags = 2) AND " . DB_T_USER . ".deleted = 0 "
                    . "GROUP BY " . DB_T_USER . ".id");
        return db::resultset();
    }

    public static function sendEmailCronAssign(array $_data){
        $list = self::getAssign($_data["id"]);
        $nb = count($list);
        
        $titre = $nb > 1 ? $nb . " documents en attentes de validation" : "Un document en attente de validation";
        
        $message = "Cet email est un récapitulatif des documents qui vous ont été assignés sur le CMS du CSE Invent.<br />A ce jour ";
        $message .= $nb > 1 ? $nb . " documents sont en attentes de validation." : "un seul document est en attente de validation.";
        $message .= "<br />Ce bilan sera mis à jour une fois par semaine et sera envoyé à l'ensemble des personnes assignées à ces documents.";
        
        $tmp = [
            "name" => $_data["name"],
            "subject" => $titre,
            "message" => $message,
            "table" => self::getMailArray($list)
        ];

        $data = [
            "to" => $_data["email"],
            "name" => $_data["name"],
            "subject" => $titre,
            "template" => self::templateMail($tmp)
        ];

        try {
            email::send($data);
            historique::recRef("script");
            historique::add(array(
                "idType" => historique::getIdRef("CRON"),
                "idUser" => NULL,
                "idPage" => historique::getIdRef("script"),
                "log" => "Email d'assignation envoyé à " . $data["name"])
            );
        } catch (\Throwable $th) {
            debug::log($th);
        }
    }

    public static function templateMail(array $_data)
    {
        $logo_url = empty($_data["logo_url"]) ? "https://" . DOMAIN_CMS . "/img/logo.png" : $_data["logo_url"];
        $date = empty($_data["date"]) ? core::printDateTxt() : $_data["date"];
        $name = empty($_data["name"]) ? NULL : $_data["name"];
        $subject = empty($_data["subject"]) ? NULL : $_data["subject"];
        $message = empty($_data["message"]) ? NULL : $_data["message"];
        $cms_url = empty($_data["cms_url"]) ? "https://" . DOMAIN_CMS : $_data["cms_url"];
        $table = empty($_data["table"]) ? NULL : $_data["table"];
        
        $template = email::loadTemplate('cms.documents.html');

        if ($template === false) {
            echo "Impossible de lire le template d'email.";
            return false;
        }

        // Remplacer les variables dans le template
        $template = str_replace([
                        '{{logo_url}}', 
                        '{{date}}', 
                        '{{name}}', 
                        '{{subject}}', 
                        '{{message}}',
                        '{{cms_url}}',
                        '{{table}}'
                    ], [
                        $logo_url, 
                        $date, 
                        $name, 
                        $subject, 
                        $message,
                        $cms_url,
                        $table
                    ], $template);

        // Si debug
        if(debug::isFile("email")){
            debug::log($template);
        }

        return $template;
    }

    private static function getMailArray(array $_array){
        $return = NULL;
        foreach ($_array as $value) {
            $return .= ' <tr>
                            <td>' . core::convertDate($value["date"], FALSE) . '</td>
                            <td>' . $value["titre"] . '</td>
                            <td>' . $value["label"] . '</td>
                            <td>' . $value["deadline"] . '</td>
                            <td>' . $value["assign"] . '</td>
                            <td style="text-align:right;">' . core::formatEuro($value["montant"]) . '</td>
                        </tr>';
        }
        return $return;
    }

}