<?php
require_once __DIR__ . '/config/connexion.php';

// Récupérer la liste des utilisateurs depuis users_table
$users = [];
$res = $conn->query("SELECT user_email, first_name, last_name FROM users_table");
while ($row = $res->fetch_assoc()) {
    $users[] = [
        'user_email' => $row['user_email'],
        'fullname' => trim($row['first_name'] . ' ' . $row['last_name'])
    ];
}

// Récupérer la liste des pages depuis la table menu_items (MySQL)
$pages = [];
// Exclure pages publiques (access=1) et spéciales (access=3)
$res = $conn->query("SELECT link, title FROM menu_items WHERE (access NOT IN (1,3) OR access IS NULL) ORDER BY title ASC");
while ($row = $res->fetch_assoc()) {
    if (!empty($row['link']) && !empty($row['title'])) {
        $pages[] = [
            'link' => $row['link'],
            'title' => $row['title']
        ];
    }
}

// Récupérer l'utilisateur sélectionné
$selected_user = isset($_GET['user']) ? $_GET['user'] : '';

// Mettre à jour les permissions via AJAX
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user'], $_POST['page'], $_POST['allowed'])) {
    $user = $_POST['user'];
    $page = $_POST['page'];
    $allowed = $_POST['allowed'] === '1';

    if ($allowed) {
        // Ajouter la permission si elle n'existe pas
        $stmt = $conn->prepare("INSERT IGNORE INTO user_permissions (user_email, page) VALUES (?, ?)");
        $stmt->bind_param("ss", $user, $page);
        $stmt->execute();
        $stmt->close();
    } else {
        // Supprimer la permission
        $stmt = $conn->prepare("DELETE FROM user_permissions WHERE user_email = ? AND page = ?");
        $stmt->bind_param("ss", $user, $page);
        $stmt->execute();
        $stmt->close();
    }
    // Réponse AJAX
    echo 'OK';
    exit;
}

// Récupérer les pages autorisées pour l'utilisateur sélectionné
$user_allowed = [];
if ($selected_user) {
    $stmt = $conn->prepare("SELECT page FROM user_permissions WHERE user_email = ?");
    $stmt->bind_param("s", $selected_user);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $user_allowed[] = $row['page'];
    }
    $stmt->close();
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <?php include 'includes/head.php'; ?>
    <style>
        .custom-switch .custom-control-label::before {
            left: -2.25rem;
            width: 2rem;
            height: 1rem;
            pointer-events: all;
            border-radius: 1rem;
        }
        .custom-switch .custom-control-label::after {
            top: .1rem;
            left: -2.1rem;
            width: .8rem;
            height: .8rem;
            border-radius: 50%;
        }
    </style>
</head>
<body id="page-top">
    <div id="wrapper">
        <?php include 'includes/sidebar.php'; ?>
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include 'includes/topbar.php'; ?>
                <div class="container-fluid mt-4">
                    <h2 class="mb-4">Gestion des autorisations utilisateur</h2>
                    <form method="get" class="mb-4">
                        <label for="user">Sélectionner un utilisateur :</label>
                        <select name="user" id="user" class="form-control w-auto d-inline" onchange="this.form.submit()">
                            <option value="" <?php if (empty($selected_user)) echo 'selected'; ?> disabled>-- Choisir un utilisateur --</option>
                            <?php foreach ($users as $user): ?>
                                <option value="<?php echo htmlspecialchars($user['user_email']); ?>" <?php if ($user['user_email'] === $selected_user) echo 'selected'; ?>>
                                    <?php echo htmlspecialchars($user['fullname']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </form>
                    <?php if ($selected_user): ?>
                        <div class="card shadow mb-4">
                            <div class="card-body">
                                <div class="form-inline mb-3">
                                    <label for="pageFilter" class="mr-2 mb-2">Filtrer les pages :</label>
                                    <input type="text" id="pageFilter" class="form-control form-control-sm mb-2" placeholder="Tapez pour filtrer...">
                                </div>
                                <div class="table-responsive">
                                    <table class="table table-bordered bg-white">
                                        <thead>
                                            <tr>
                                                <th>Page</th>
                                                <th>Autorisé</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($pages as $page): ?>
                                            <tr data-title="<?php echo htmlspecialchars(mb_strtolower($page['title'],'UTF-8')); ?>">
                                                <td><?php echo htmlspecialchars($page['title']); ?></td>
                                                <td>
                                                    <div class="custom-control custom-switch">
                                                        <input type="checkbox"
                                                               class="custom-control-input perm-switch"
                                                               id="switch_<?php echo md5($page['link']); ?>"
                                                               data-page="<?php echo htmlspecialchars($page['link']); ?>"
                                                               <?php if (in_array($page['link'], $user_allowed)) echo 'checked'; ?>>
                                                        <label class="custom-control-label" for="switch_<?php echo md5($page['link']); ?>"></label>
                                                    </div>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'includes/footer.php'; ?>
        </div>
    </div>
    <!-- Include required scripts -->
  <script src="vendor/jquery/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
  <script src="vendor/datatables/jquery.dataTables.min.js"></script>
  <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
  <script src="js/ruang-admin.min.js"></script>
    <script>
    $(function() {
        $('.perm-switch').change(function() {
            var allowed = $(this).is(':checked') ? 1 : 0;
            var page = $(this).data('page');
            var user = <?php echo json_encode($selected_user); ?>;
            $.post('manage_permissions.php', {
                user: user,
                page: page,
                allowed: allowed
            });
        });

        $('#pageFilter').on('input', function(){
            var q = $(this).val().toLowerCase().trim();
            $('table tbody tr').each(function(){
                var t = $(this).data('title');
                if(!q || (t && t.indexOf(q)!==-1)){
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        });
    });
    </script>
</body>
</html>