<?PHP
namespace Views;

class UsersHtml
{
    static public function afficherListeUtilisateur($result, $depClass, $roleClass, $sql)
    {
        include_once("Views/FunctionHtml.php");
        include_once("Classe/FunctionClasse.php");
        include("Parametre/" . getPath(1) . "/" . getPath(1) . ".php");
        $displayOld = false;
?>
        <main class="<?php echo $mainClass; ?> ms-sm-auto px-md-4 py-4" id="main-content" style="display: none;">
            <div class="card card-mh-90vh">
                <div class="card-header">
                    <b>Liste des utilisateurs</b>
                </div>
                <div class="card-body">

                    <?php
                    if (isset($_GET["msg"])) {
                        $msg = $_GET["msg"];

                        // Define messages and their alert types with Font Awesome icons
                        $alerts = [
                            "updated" => ["success", "fas fa-check-circle", "Utilisateur mis à jour avec succès."],
                            "deleted" => ["success", "fas fa-check-circle", "Utilisateur supprimé avec succès."],
                            "added" => ["success", "fas fa-check-circle", "Utilisateur ajouté avec succès."],
                            "errorsupr" => ["warning", "fas fa-exclamation-triangle", "Erreur suppression, réessayez plus tard ou contactez " . $errorMsgService . "."],
                            "erroraddedit" => ["warning", "fas fa-exclamation-triangle", "Erreur inconnu, réessayez plus tard ou contactez " . $errorMsgService . "."],
                            "errorajax" => ["warning", "fas fa-exclamation-triangle", "Erreur inconnu, réessayez plus tard ou contactez " . $errorMsgService . "."]
                        ];

                        // Display alert if message exists in array
                        if (array_key_exists($msg, $alerts)) {
                            list($alertType, $icon, $message) = $alerts[$msg];
                            echo '<div class="alert alert-' . $alertType . '" id="alertMessageUser" role="alert">
                <i class="' . $icon . ' me-2"></i> ' . $message . '
              </div>';
                        }
                    }
                    ?>
                    <table id="gridUtilisateurs" class="display" style="width:100%">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Nom d'utilisateur</th>
                                <th>Prénom</th>
                                <th>Nom</th>
                                <th>Email</th>
                                <th>Téléphone</th>
                                <th>Rôle</th>
                                <th>Date création</th>
                                <th>Dernière connexion</th>
                                <th>Actif</th>
                                <th>Commentaires</th>
                                <th>Options</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php

                            foreach ($result as $row) {
                                echo '
                                <tr>
                                    <td style="text-align: center;" width="60px"><b>' . $row["id"] . '</b></td>
                                    <td><b>' . strtoupper($row["username"]) . '</b></td>
                                    <td>' . ($row["prenom"] ?? '') . '</td>
                                    <td>' . ($row["nom"] ?? '') . '</td>
                                    <td>' . ($row["email"] ?? '') . '</td>
                                    <td>' . ($row["telephone"] ?? '') . '</td>';

                                // Display role information
                                $role = isset($row["nom_role"]) ? $row["nom_role"] : "Non défini";
                                echo '<td title="' .  htmlspecialchars($role) . '">' . $role . '</td>';

                                // Format date creation
                                $dateCreation = isset($row["date_creation"]) ? date('d/m/Y H:i', strtotime($row["date_creation"])) : '';
                                echo '<td>' . $dateCreation . '</td>';

                                // Format last connection
                                $lastConnection = isset($row["derniere_connexion"]) && $row["derniere_connexion"] ? 
                                    date('d/m/Y H:i', strtotime($row["derniere_connexion"])) : 'Jamais';
                                echo '<td>' . $lastConnection . '</td>';

                                // Active status toggle
                                $checked = $row["actif"] == 0 ? "checked" : ""; // Note: inverted logic - checked means locked
                                $classCheckBox = $row["id"] != 1 ?  'user-edit-locked-link' : '';
                                $disabled = $row["id"] == 1 ?  'disabled' : '';
                                $title = $row["actif"] == 0 ?  'compte utilisateur verrouillé' : 'compte utilisateur actif';
                                echo '
                                    <td style="text-align: center;" width="100px">
                                    <div class="form-check form-switch" style="text-align: center;">
                                    <input  class="form-check-input ' . $classCheckBox . '"  type="checkbox" id="flexSwitchCheckDefault' . $row["id"] . '" title="' . $title . '" data-id="' . $row["id"] . '" ' . $checked . ' ' . $disabled . '>
                                    </div>
                                    </td>';

                                // Display description/comments
                                echo '<td>' . ($row["description"] ?? '') . '</td>';

                                echo '
                                    <td style="text-align: center;">
                                    <a class="user-edit-link" title="Modifier utilisateur ID : ' . $row["id"] . '" data-id="' . $row["id"] . '"><span class="fas fa-edit m-1" style="color: green;"></span></a>
                                    <a class="user-delete-link" title="Supprimer utilisateur ID : ' . $row["id"] . '" data-id="' . $row["id"] . '"><span class="fas fa-trash m-1" style="color: red;"></span></a>
                                    </td>
                                </tr>';
                            }
                            ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <th>ID</th>
                                <th>Nom d'utilisateur</th>
                                <th>Prénom</th>
                                <th>Nom</th>
                                <th>Email</th>
                                <th>Téléphone</th>
                                <th>Rôle</th>
                                <th>Date création</th>
                                <th>Dernière connexion</th>
                                <th>Actif</th>
                                <th>Commentaires</th>
                                <th>Options</th>
                            </tr>
                        </tfoot>
                    </table>

                    <?php
                    if ($roleDeveloppeur && $displayQuery) {
                        echo '<div class="row"><div class="alert alert-info text-monospace"><span class="fas fa-terminal"></span>' . $sql . "</div></div>";
                    }

                    ?>
                </div>

                <div class="modal fade" id="modalFormAddEditUser" tabindex="-1" aria-labelledby="modalFormAddEditUserLabel"
                    aria-hidden="true" data-bs-backdrop="static">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="modalFormAddEditUserLabel">Utilisateurs - Ajout/Modification</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <form name="formAddEditUser" id="formAddEditUser" action="#" method="post" enctype="multipart/form-data" autocomplete="off">
                                <div class="alert alert-warning m-3" id="alertMessageUserModal" role="alert"></div>
                                <div class="modal-body">
                                    <input type="hidden" id="idUserToEdit" name="idUserToEdit" value="" />
                                    <input type="hidden" id="page" name="page" value="user" />
                                    <input type="hidden" id="typeSend" name="typeSend" value="" />

                                    <div class="mb-3 row">
                                        <div class="col-md-12 mb-3">
                                            <label class="form-label">Nom d'utilisateur <span class="text-danger">*</span></label>
                                            <input class="form-control capitalize" type="text" name="username" id="username" required value="" />
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Nom de famille <span class="text-danger">*</span></label>
                                            <input class="form-control capitalize" type="text" name="lastname" id="lastname" required value="" />
                                            <div id="lastnameError" class="invalid-feedback">Ce champ est requis.</div>
                                        </div>

                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Prénom <span class="text-danger">*</span></label>
                                            <input class="form-control capitalize" type="text" name="firstname" id="firstname" required value="" />
                                            <div id="firstnameError" class="invalid-feedback">Ce champ est requis.</div>
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <div class="col-md-12 mb-3">
                                            <label class="form-label">Courriel (optionnel)</label>
                                            <input class="form-control  uncapitalize" type="email" name="email" id="email" value="" />
                                            <div id="emailError" class="invalid-feedback">Ce champ est requis.</div>
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <div class="col-md-12 mb-3">
                                            <label class="form-label">Commentaire (optionnel)</label>
                                            <textarea class="form-control" name="comment" id="comment" rows="2"
                                                style="resize: vertical;"> </textarea>
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <div class="col-md-12 mb-3">
                                            <label class="form-label">Numéro de licence (optionnel)</label>
                                            <input class="form-control" type="text" name="num_licence" id="num_licence" value="" />
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <div class="col-md-12 mb-3">
                                            <label class="form-label">Département</label>
                                            <div class="border p-2" id="divDepartements">
                                            </div>
                                            <div id="firstnameError" class="invalid-feedback">Veuillez choisir au moins un département.</div>
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <div class="col-md-12 mb-3">
                                            <label class="form-label">Fin contrat (optionnel)</label>
                                            <input class="form-control" type="date" name="finContrat" id="finContrat" value="" />
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <div class="col-md-12 mb-3">
                                            <label class="form-label">Rôles</label>
                                            <div class="border p-2" id="divRoles">
                                            </div>
                                            <div id="firstnameError" class="invalid-feedback">Veuillez choisir au moins un rôle.</div>
                                        </div>
                                    </div>

                                    <div class="mb-3 row">
                                        <div class="col-md-12 mb-3">
                                            <div class="form-check">
                                                <input type="checkbox" class="form-check-input" name="resetPassword" id="resetPassword" value=1 />
                                                <label class="form-check-label" for="resetPassword">Réinitialiser le mot de passe</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </form>
                            <div class="modal-footer d-flex justify-content-between align-items-center">
                                <small class="text-muted"><span class="text-danger">*</span> Champs obligatoires</small>
                                <div>
                                    <button type="button" id="confirmSubmitUser" class="btn btn-primary">Enregistrer</button>
                                    <button type="button" id="cancelSubmitUser" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal fade" id="confirmDeletionModalUser" tabindex="-1" aria-labelledby="confirmDeletionModalLabelUser"
                    aria-hidden="true" data-bs-backdrop="static">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="confirmDeletionModalLabelUser">Confirmer la suppression</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="alert alert-warning m-3" id="alertMessageModalDeleteUser" role="alert"></div>
                            <div class="modal-body" id="confirmDeletionBodyUser">
                                Vouslez-vous vraiment supprimer cet utilisateur ?
                            </div>
                            <div class="modal-footer">
                                <input type="hidden" name="typeConfirmDeletionUser" value="" />
                                <input type="hidden" name="idUserToDelete" value="" />
                                <button type="button" class="btn btn-danger" id="confirmDeletionUser">Oui, Supprimer</button>
                                <button type="button" class="btn btn-secondary" id="dismissDeletionUser" data-bs-dismiss="modal">Non</button>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal fade" id="confirmModalVerifie" tabindex="-1" aria-labelledby="confirmModalVerifieLabel" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="confirmModalVerifieLabel">Confirmer le changement</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fermer"></button>
                            </div>
                            <div class="modal-body">
                                Êtes-vous sûr de vouloir changer ce statut ?
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" id="cancelChange" data-bs-dismiss="modal">Annuler</button>
                                <button type="button" class="btn btn-primary" id="confirmChange">Confirmer</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>

<?PHP
    }
}
?>
