<?php
require_once '../includes/auth.php';

if (!checkPermission('admin')) {
    header('Location: ../dashboard.php');
    exit;
}

require_once '../config/database.php';
require_once '../includes/functions.php';

$pdo = getPDO();
$error = '';
$success = '';

$is_superadmin = ($_SESSION['user_role'] === 'superadmin');

// Ajout d'utilisateur
if (isset($_POST['ajouter'])) {
    $username = trim($_POST['username'] ?? '');
    $nom = trim($_POST['nom'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $role = $_POST['role'] ?? 'personnel';
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($nom) || empty($email) || empty($password)) {
        $error = "Tous les champs sont requis.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Email invalide.";
    } elseif (strlen($password) < 6) {
        $error = "Mot de passe trop court (minimum 6 caractères).";
    } else {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
        $stmt->execute([$username, $email]);
        if ($stmt->fetch()) {
            $error = "Ce nom d'utilisateur ou email est déjà utilisé.";
        } else {
            $hash = password_hash($password, PASSWORD_BCRYPT);
            $stmt = $pdo->prepare("INSERT INTO users (username, nom, email, password_hash, role) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$username, $nom, $email, $hash, $role]);
            savePasswordHistory($pdo, $pdo->lastInsertId(), $hash);
            logAction($pdo, $_SESSION['user_id'], 'creation_utilisateur', "Utilisateur $username créé");
            $success = "Utilisateur ajouté avec succès.";
        }
    }
}

// Suppression d'utilisateur (superadmin uniquement)
if (isset($_GET['delete']) && $is_superadmin) {
    $id = filter_input(INPUT_GET, 'delete', FILTER_VALIDATE_INT);
    if ($id && $id != $_SESSION['user_id']) {
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$id]);
        logAction($pdo, $_SESSION['user_id'], 'suppression_utilisateur', "User ID $id");
        $success = "Utilisateur supprimé définitivement.";
    }
}

// Récupérer la liste des utilisateurs
$stmt = $pdo->query("SELECT id, username, nom, email, role, signature_path, created_at FROM users ORDER BY role DESC, nom");
$users = $stmt->fetchAll();

require_once '../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <a href="index.php" class="btn btn-outline-secondary me-2">
            <i class="fas fa-arrow-left me-1"></i> Retour au tableau de bord admin
        </a>
    </div>
    <div>
        <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="fas fa-user-plus me-2"></i>Nouvel utilisateur
        </button>
    </div>
</div>

<h1><i class="fas fa-users-cog me-2"></i>Gestion des utilisateurs</h1>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= $error ?></div>
<?php endif; ?>
<?php if ($success): ?>
    <div class="alert alert-success"><?= $success ?></div>
<?php endif; ?>

<?php if (empty($users)): ?>
    <div class="alert alert-info">Aucun utilisateur enregistré.</div>
<?php else: ?>
    <div class="card shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th>ID</th>
                            <th>Username</th>
                            <th>Nom</th>
                            <th>Email</th>
                            <th>Rôle</th>
                            <th>Signature</th>
                            <th>Créé le</th>
                            <th class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $u): ?>
                            <tr>
                                <td><?= $u['id'] ?></td>
                                <td><?= htmlspecialchars($u['username']) ?></td>
                                <td><?= htmlspecialchars($u['nom']) ?></td>
                                <td><?= htmlspecialchars($u['email']) ?></td>
                                <td>
                                    <?php
                                    $badge = match($u['role']) {
                                        'superadmin' => 'bg-dark',
                                        'admin' => 'bg-danger',
                                        'personnel' => 'bg-secondary',
                                        default => 'bg-light'
                                    };
                                    ?>
                                    <span class="badge <?= $badge ?>"><?= $u['role'] ?></span>
                                </td>
                                <td>
                                    <?= $u['signature_path'] ? '<i class="fas fa-check-circle text-success" title="Signature enregistrée"></i>' : '<i class="fas fa-times-circle text-muted" title="Aucune signature"></i>' ?>
                                </td>
                                <td><?= date('d/m/Y', strtotime($u['created_at'])) ?></td>
                                <td class="text-center">
                                    <div class="btn-group btn-group-sm" role="group">
                                        <?php if ($is_superadmin && $u['role'] !== 'superadmin'): ?>
                                            <a href="?delete=<?= $u['id'] ?>" class="btn btn-danger" onclick="return confirm('Supprimer définitivement cet utilisateur ?')" title="Supprimer">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        <?php endif; ?>
                                        <?php if ($is_superadmin): ?>
                                            <a href="historique_password.php?user_id=<?= $u['id'] ?>" class="btn btn-info" title="Historique des mots de passe / Réinitialiser">
                                                <i class="fas fa-key"></i>
                                            </a>
                                        <?php endif; ?>
                                        <?php if ($u['id'] == $_SESSION['user_id']): ?>
                                            <a href="../profile.php" class="btn btn-warning" title="Modifier mon profil">
                                                <i class="fas fa-user-edit"></i>
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- Modal d'ajout d'utilisateur -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header bg-success text-white">
                    <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 for="username" class="form-label">Nom d'utilisateur *</label>
                        <input type="text" class="form-control" id="username" name="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="nom" class="form-label">Nom complet *</label>
                        <input type="text" class="form-control" id="nom" name="nom" required>
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">Email *</label>
                        <input type="email" class="form-control" id="email" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label for="role" class="form-label">Rôle</label>
                        <select class="form-select" id="role" name="role">
                            <option value="personnel">Personnel</option>
                            <?php if ($is_superadmin): ?>
                                <option value="admin">Admin</option>
                                <option value="superadmin">Superadmin</option>
                            <?php else: ?>
                                <option value="admin" disabled>Admin (réservé)</option>
                            <?php endif; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">Mot de passe *</label>
                        <input type="password" class="form-control" id="password" name="password" required minlength="6">
                        <div class="form-text">Minimum 6 caractères</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                    <button type="submit" name="ajouter" class="btn btn-success">Créer</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>