<?php
session_start();
include('includes/header.php');
require_once "includes/dbconn.php";

// Vérifie si utilisateur connecté
if (!isset($_SESSION['user'])) {
    header("Location: login.php");
    exit();
}

$user_role = $_SESSION['user']['role'];

$message = '';
$error = '';

// ** Ne permettre les actions que si admin **
if ($user_role === 'admin') {

    // Ajout utilisateur
    if (isset($_POST['add_user'])) {
        $login = trim($_POST['login']);
        $password = $_POST['password'];
        $role = $_POST['role'];

        if ($login === '' || $password === '' || $role === '') {
            $error = "Tous les champs sont obligatoires pour l'ajout.";
        } else {
            $stmt = $conn->prepare("SELECT id FROM users WHERE login = ?");
            $stmt->bind_param("s", $login);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
                $error = "Ce login existe déjà.";
            } else {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $conn->prepare("INSERT INTO users (login, password, role) VALUES (?, ?, ?)");
                $stmt->bind_param("sss", $login, $hash, $role);
                $stmt->execute();
                $message = "Utilisateur ajouté avec succès.";
            }
        }
    }

    // Modification utilisateur
    if (isset($_POST['edit_user'])) {
        $id = (int)$_POST['user_id'];
        $login = trim($_POST['login']);
        $role = $_POST['role'];
        $password = $_POST['password'];

        if ($login === '' || $role === '') {
            $error = "Login et rôle obligatoires.";
        } else {
            if ($password !== '') {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $conn->prepare("UPDATE users SET login = ?, role = ?, password = ? WHERE id = ?");
                $stmt->bind_param("sssi", $login, $role, $hash, $id);
            } else {
                $stmt = $conn->prepare("UPDATE users SET login = ?, role = ? WHERE id = ?");
                $stmt->bind_param("ssi", $login, $role, $id);
            }
            $stmt->execute();
            $message = "Utilisateur modifié avec succès.";
        }
    }

    // Suppression utilisateur
    if (isset($_GET['delete'])) {
        $id = (int)$_GET['delete'];
        if ($id === $_SESSION['user']['id']) {
            $error = "Vous ne pouvez pas vous supprimer vous-même.";
        } else {
            $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $message = "Utilisateur supprimé.";
        }
    }
}

// Récupère tous les utilisateurs (tous les rôles peuvent voir la liste)
$result = $conn->query("SELECT id, login, role FROM users ORDER BY login ASC");
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8" />
    <title>Gestion des utilisateurs</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
    <style>
        :root {
            --primary-color: #1a5276; /* Bleu foncé */
            --secondary-color: #27ae60; /* Vert */
            --accent-color: #e74c3c;
            --light-bg: #f8f9fa;
            --dark-text: #2c3e50;
        }
        
        body {
            background-color: var(--light-bg);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: var(--dark-text);
        }
        
        .card {
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            border: none;
            margin-bottom: 25px;
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            font-weight: 600;
            border-radius: 10px 10px 0 0 !important;
            padding: 15px 20px;
        }
        
        .table-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            padding: 20px;
            margin-top: 20px;
        }
        
        .table {
            margin-bottom: 0;
        }
        
        .table thead th {
            background-color: var(--primary-color);
            color: white;
            border-bottom: none;
            vertical-align: middle;
        }
        
        .table tbody tr:hover {
            background-color: rgba(26, 82, 118, 0.05);
        }
        
        .btn-action {
            padding: 5px 10px;
            font-size: 14px;
            border-radius: 5px;
            margin-right: 5px;
        }
        
        .btn-edit {
            background-color: var(--primary-color);
            color: white;
            border: none;
        }
        
        .btn-delete {
            background-color: var(--accent-color);
            color: white;
            border: none;
        }
        
        .btn-add {
            background: linear-gradient(135deg, var(--secondary-color), #2ecc71);
            color: white;
            border: none;
            padding: 8px 15px;
            font-weight: 500;
        }
        
        .alert {
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .form-control, .form-select {
            border-radius: 5px;
            padding: 8px 12px;
            border: 1px solid #ddd;
            transition: all 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(26, 82, 118, 0.25);
        }
        
        .modal-header {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
        }
        
        .modal-title {
            font-weight: 600;
        }
        
        .role-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 500;
        }
        
        .role-admin {
            background-color: #d4edf9;
            color: var(--primary-color);
        }
        
        .role-caissier {
            background-color: #d5f5e3;
            color: var(--secondary-color);
        }
        
        .role-utilisateur {
            background-color: #e8daef;
            color: #7d3c98;
        }
    </style>
</head>
<body>

<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0"><i class="fas fa-users-cog me-2"></i>Gestion des utilisateurs</h2>
        <?php if ($user_role === 'admin'): ?>
            <button class="btn btn-add" data-bs-toggle="modal" data-bs-target="#addUserModal">
                <i class="fas fa-plus-circle me-2"></i>Ajouter un utilisateur
            </button>
        <?php endif; ?>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="fas fa-check-circle me-2"></i><?= htmlspecialchars($message) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    
    <?php if ($error): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="fas fa-exclamation-circle me-2"></i><?= htmlspecialchars($error) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if ($user_role !== 'admin'): ?>
        <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle me-2"></i>
            Vous n'avez pas les droits pour ajouter, modifier ou supprimer des utilisateurs.
        </div>
    <?php endif; ?>

    <!-- Liste des utilisateurs -->
    <div class="table-container">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th><i class="fas fa-user me-2"></i>Login</th>
                        <th><i class="fas fa-user-tag me-2"></i>Rôle</th>
                        <?php if ($user_role === 'admin'): ?>
                            <th><i class="fas fa-cogs me-2"></i>Actions</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($user = $result->fetch_assoc()): ?>
                    <tr>
                        <td><?= htmlspecialchars($user['login']) ?></td>
                        <td>
                            <span class="role-badge role-<?= htmlspecialchars($user['role']) ?>">
                                <?= htmlspecialchars($user['role']) ?>
                            </span>
                        </td>
                        <?php if ($user_role === 'admin'): ?>
                        <td>
                            <button class="btn btn-action btn-edit" data-bs-toggle="modal" data-bs-target="#editModal<?= $user['id'] ?>">
                                <i class="fas fa-edit me-1"></i>Modifier
                            </button>
                            <a href="?delete=<?= $user['id'] ?>" onclick="return confirm('Êtes-vous sûr de vouloir supprimer cet utilisateur ?');" class="btn btn-action btn-delete">
                                <i class="fas fa-trash-alt me-1"></i>Supprimer
                            </a>

                            <!-- Modal modification -->
                            <div class="modal fade" id="editModal<?= $user['id'] ?>" tabindex="-1" aria-labelledby="editModalLabel<?= $user['id'] ?>" aria-hidden="true">
                              <div class="modal-dialog">
                                <form method="POST" class="modal-content">
                                  <div class="modal-header">
                                    <h5 class="modal-title" id="editModalLabel<?= $user['id'] ?>">
                                        <i class="fas fa-user-edit me-2"></i>Modifier utilisateur
                                    </h5>
                                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
                                  </div>
                                  <div class="modal-body">
                                      <input type="hidden" name="user_id" value="<?= $user['id'] ?>" />
                                      <div class="mb-3">
                                          <label class="form-label">Login</label>
                                          <input type="text" name="login" class="form-control" value="<?= htmlspecialchars($user['login']) ?>" required />
                                      </div>
                                      <div class="mb-3">
                                          <label class="form-label">Mot de passe (laisser vide pour ne pas changer)</label>
                                          <input type="password" name="password" class="form-control" />
                                      </div>
                                      <div class="mb-3">
                                          <label class="form-label">Rôle</label>
                                          <select name="role" class="form-select" required>
                                              <option value="admin" <?= $user['role'] === 'admin' ? 'selected' : '' ?>>Admin</option>
                                              <option value="caissier" <?= $user['role'] === 'caissier' ? 'selected' : '' ?>>Caissier</option>
                                              <option value="utilisateur" <?= $user['role'] === 'utilisateur' ? 'selected' : '' ?>>Utilisateur</option>
                                          </select>
                                      </div>
                                  </div>
                                  <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                        <i class="fas fa-times me-1"></i>Annuler
                                    </button>
                                    <button type="submit" name="edit_user" class="btn btn-primary">
                                        <i class="fas fa-save me-1"></i>Enregistrer
                                    </button>
                                  </div>
                                </form>
                              </div>
                            </div>
                        </td>
                        <?php endif; ?>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal ajout utilisateur -->
<?php if ($user_role === 'admin'): ?>
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form method="POST" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addUserModalLabel"><i class="fas fa-user-plus me-2"></i>Ajouter un utilisateur</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Fermer"></button>
      </div>
      <div class="modal-body">
          <div class="mb-3">
              <label class="form-label">Login</label>
              <input type="text" name="login" class="form-control" required />
          </div>
          <div class="mb-3">
              <label class="form-label">Mot de passe</label>
              <input type="password" name="password" class="form-control" required />
          </div>
          <div class="mb-3">
              <label class="form-label">Rôle</label>
              <select name="role" class="form-select" required>
                  <option value="">-- Choisir un rôle --</option>
                  <option value="admin">Admin</option>
                  <option value="caissier">Caissier</option>
                  <option value="utilisateur">Utilisateur</option>
              </select>
          </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
            <i class="fas fa-times me-1"></i>Annuler
        </button>
        <button type="submit" name="add_user" class="btn btn-primary">
            <i class="fas fa-plus-circle me-1"></i>Ajouter
        </button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Confirmation avant suppression
    document.querySelectorAll('.btn-delete').forEach(button => {
        button.addEventListener('click', function(e) {
            if (!confirm('Êtes-vous sûr de vouloir supprimer cet utilisateur ?')) {
                e.preventDefault();
            }
        });
    });
</script>
</body>
</html>