<?php
// Fichier: admin_users.php
require 'includes/db.php';
require 'includes/auth.php';
require_login();
if ($_SESSION['user_role'] !== 'SUPER_ADMIN') die("Accès interdit.");

$msg = "";

// AJOUT / RESET (Code logique identique, seul le design change)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] == 'add_user') {
        try {
            $email = trim($_POST['email']);
            $pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
            $nom = trim($_POST['nom']);
            $prenom = trim($_POST['prenom']);
            $entreprise_id = $_POST['entreprise_id'];
            
            $sql = "INSERT INTO utilisateurs (entreprise_id, email, mot_de_passe_hash, role, nom, prenom) VALUES (?, ?, ?, 'CSE_MANAGER', ?, ?)";
            $pdo->prepare($sql)->execute([$entreprise_id, $email, $pass, $nom, $prenom]);
            $msg = "<div class='alert alert-success'>✅ Compte créé pour $email !</div>";
        } catch (PDOException $e) {
            $msg = "<div class='alert alert-danger'>❌ Erreur : " . $e->getMessage() . "</div>";
        }
    }
    if (isset($_POST['action']) && $_POST['action'] == 'reset_pass') {
        $uid = $_POST['user_id'];
        $new_pass = password_hash($_POST['new_pass'], PASSWORD_DEFAULT);
        $pdo->prepare("UPDATE utilisateurs SET mot_de_passe_hash = ? WHERE id = ?")->execute([$new_pass, $uid]);
        $msg = "<div class='alert alert-success'>✅ Mot de passe modifié.</div>";
    }
}

$entreprises = $pdo->query("SELECT * FROM entreprises ORDER BY nom ASC")->fetchAll();
$users = $pdo->query("SELECT u.*, e.nom as cse_nom FROM utilisateurs u LEFT JOIN entreprises e ON u.entreprise_id = e.id ORDER BY u.id DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion Accès - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>

    <nav class="navbar navbar-dark bg-danger mb-4 px-4">
        <span class="navbar-brand"><i class="material-icons align-middle">manage_accounts</i> Gestion des Accès</span>
        <a href="dashboard.php" class="btn btn-outline-light btn-sm">Retour</a>
    </nav>

    <div class="container">
        <?= $msg ?>
        
        <div class="row">
            <div class="col-md-4">
                <div class="card shadow-sm border-0 mb-4" style="border-top: 4px solid #c5a059 !important;">
                    <div class="card-header bg-white fw-bold text-uppercase">Nouveau Compte CSE</div>
                    <div class="card-body bg-light">
                        <form method="POST">
                            <input type="hidden" name="action" value="add_user">
                            <div class="mb-3">
                                <label class="form-label small text-muted">CSE concerné</label>
                                <select name="entreprise_id" class="form-select" required>
                                    <?php foreach ($entreprises as $e): ?>
                                        <option value="<?= $e['id'] ?>"><?= htmlspecialchars($e['nom']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="row g-2 mb-3">
                                <div class="col"><input type="text" name="nom" class="form-control" placeholder="Nom" required></div>
                                <div class="col"><input type="text" name="prenom" class="form-control" placeholder="Prénom" required></div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label small text-muted">Email (Identifiant)</label>
                                <input type="email" name="email" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label small text-muted">Mot de passe</label>
                                <input type="text" name="password" class="form-control" placeholder="Mot de passe initial" required>
                            </div>
                            <button type="submit" class="btn btn-gold w-100 text-uppercase" style="font-size:0.9rem;">Créer l'accès</button>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-8">
                <div class="card shadow-sm border-0">
                    <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
                        <span>Liste des utilisateurs</span>
                        <span class="badge bg-gold text-dark"><?= count($users) ?> comptes</span>
                    </div>
                    <div class="card-body p-0">
                        <table class="table table-hover mb-0 align-middle">
                            <thead class="table-light"><tr><th>CSE / Rôle</th><th>Identité</th><th>Login</th><th>Sécurité</th></tr></thead>
                            <tbody>
                                <?php foreach ($users as $u): ?>
                                <tr>
                                    <td>
                                        <?php if($u['role'] === 'SUPER_ADMIN'): ?>
                                            <span class="badge bg-danger">ADMINISTRATEUR</span>
                                        <?php else: ?>
                                            <span class="fw-bold" style="color:var(--primary-dark)"><?= $u['cse_nom'] ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= htmlspecialchars($u['nom'] . ' ' . $u['prenom']) ?></td>
                                    <td class="small text-muted"><?= htmlspecialchars($u['email']) ?></td>
                                    <td>
                                        <form method="POST" class="d-flex" onsubmit="return confirm('Réinitialiser le mot de passe pour <?= $u['nom'] ?> ?');">
                                            <input type="hidden" name="action" value="reset_pass">
                                            <input type="hidden" name="user_id" value="<?= $u['id'] ?>">
                                            <input type="text" name="new_pass" class="form-control form-control-sm me-1" placeholder="Nouveau Pass" style="width:120px;" required>
                                            <button type="submit" class="btn btn-sm btn-outline-dark" title="Enregistrer"><i class="material-icons" style="font-size:16px">save</i></button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>