<?php include('include/headscript.php'); ?>
<?php
// Connessione al database
$conn = new mysqli($servername, $username, $password, $database);

// Verifica connessione
if ($conn->connect_error) {
    die("Errore di connessione: " . $conn->connect_error);
}

// Recupera l'elenco dei ruoli
$queryRoles = $conn->query("SELECT * FROM sharing_roles ORDER BY idrole DESC");
$roles = [];
while ($row = $queryRoles->fetch_assoc()) {
    $roles[] = $row;
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title>Gestione Ruoli Condivisione</title>
    <link href="assets/css/bootstrap.min.css" rel="stylesheet" type="text/css">
    <link href="assets/css/icons.css" rel="stylesheet" type="text/css">
    <link href="assets/css/style.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body class="fixed-left">

    <div id="wrapper">
        <?php include('include/navigationbar.php'); ?>
        <div class="content-page">
            <div class="content">
                <?php include('include/topbar.php'); ?>

                <div class="page-content-wrapper">
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-12">
                                <h4 class="page-title">Gestione Ruoli di Condivisione</h4>
                                <button class="btn btn-success mb-3" data-toggle="modal" data-target="#addRoleModal">
                                    <i class="mdi mdi-plus"></i> Aggiungi Ruolo
                                </button>
                                <table id="rolesTable" class="table table-striped table-bordered">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Nome</th>
                                            <th>Descrizione</th>
                                            <th>Permessi</th>
                                            <th>Azioni</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($roles as $role) { ?>
                                            <tr>
                                                <td><?php echo $role['idrole']; ?></td>
                                                <td><?php echo htmlspecialchars($role['role_name']); ?></td>
                                                <td><?php echo htmlspecialchars($role['description']); ?></td>
                                                <td><?php echo htmlspecialchars($role['permissions']); ?></td>
                                                <td>
                                                    <button class="btn btn-warning btn-sm" data-toggle="modal" data-target="#editRoleModal"
                                                        data-id="<?php echo $role['idrole']; ?>"
                                                        data-name="<?php echo htmlspecialchars($role['role_name']); ?>"
                                                        data-description="<?php echo htmlspecialchars($role['description']); ?>"
                                                        data-permissions="<?php echo htmlspecialchars($role['permissions']); ?>">
                                                        <i class="mdi mdi-pencil"></i>
                                                    </button>
                                                    <button class="btn btn-danger btn-sm delete-role"
                                                        data-id="<?php echo $role['idrole']; ?>">
                                                        <i class="mdi mdi-delete"></i>
                                                    </button>

                                                </td>
                                            </tr>
                                        <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div> <!-- container -->
                </div> <!-- Page content Wrapper -->
            </div> <!-- content -->
            <?php include('include/footer.php'); ?>
        </div> <!-- End Right content here -->
    </div> <!-- END wrapper -->

    <!-- Modale: Aggiungi Ruolo -->
    <div class="modal fade" id="addRoleModal" tabindex="-1" role="dialog" aria-labelledby="addRoleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form action="add-role.php" method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addRoleModalLabel">Aggiungi Ruolo</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="roleName">Nome Ruolo</label>
                            <input type="text" class="form-control" id="roleName" name="role_name" required>
                        </div>
                        <div class="form-group">
                            <label for="roleDescription">Descrizione</label>
                            <textarea class="form-control" id="roleDescription" name="description"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="rolePermissions">Permessi (JSON)</label>
                            <textarea class="form-control" id="rolePermissions" name="permissions"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Chiudi</button>
                        <button type="submit" class="btn btn-success">Salva</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modale: Modifica Ruolo -->
    <div class="modal fade" id="editRoleModal" tabindex="-1" role="dialog" aria-labelledby="editRoleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <form action="edit-role.php" method="POST">
                    <input type="hidden" id="editRoleId" name="idrole">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editRoleModalLabel">Modifica Ruolo</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="editRoleName">Nome Ruolo</label>
                            <input type="text" class="form-control" id="editRoleName" name="role_name" required>
                        </div>
                        <div class="form-group">
                            <label for="editRoleDescription">Descrizione</label>
                            <textarea class="form-control" id="editRoleDescription" name="description"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="editRolePermissions">Permessi (JSON)</label>
                            <textarea class="form-control" id="editRolePermissions" name="permissions"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Chiudi</button>
                        <button type="submit" class="btn btn-warning">Salva Modifiche</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="assets/js/jquery.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#rolesTable').DataTable();

            // Popola i campi del modale di modifica
            $('#editRoleModal').on('show.bs.modal', function(event) {
                var button = $(event.relatedTarget);
                var id = button.data('id');
                var name = button.data('name');
                var description = button.data('description');
                var permissions = button.data('permissions');

                $('#editRoleId').val(id);
                $('#editRoleName').val(name);
                $('#editRoleDescription').val(description);
                $('#editRolePermissions').val(permissions);
            });

            // Elimina ruolo con SweetAlert2
            $('.delete-role').on('click', function() {
                var roleId = $(this).data('id'); // Recupera l'id dal pulsante

                Swal.fire({
                    title: 'Sei sicuro?',
                    text: "Questa azione non può essere annullata!",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Sì, elimina!',
                    cancelButtonText: 'Annulla'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Effettua la chiamata per eliminare il ruolo
                        fetch(`delete-role.php?idrole=${roleId}`, {
                                method: 'GET'
                            })
                            .then(response => response.text())
                            .then(data => {
                                Swal.fire(
                                    'Eliminato!',
                                    'Il ruolo è stato eliminato con successo.',
                                    'success'
                                ).then(() => {
                                    // Ricarica la pagina per aggiornare la tabella
                                    location.reload();
                                });
                            })
                            .catch(error => {
                                Swal.fire(
                                    'Errore!',
                                    'Si è verificato un errore durante l\'eliminazione.',
                                    'error'
                                );
                            });
                    }
                });
            });
        });
    </script>

</body>

</html>