<?php
session_start();
require_once 'config.php';
require_once 'function.php';

if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] != 'super_admin') {
    header('Location: login.php');
    exit();
}

$current_user = getCurrentUserInfo($pdo);
$message = '';

// Traitement AJOUT admin
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    if ($_POST['action'] == 'ajouter_admin') {
        try {
            $check = $pdo->prepare("SELECT id_user FROM utilisateur WHERE login = ?");
            $check->execute([$_POST['login']]);
            if ($check->rowCount() > 0) {
                $message = '<div class="alert-error">Ce login existe déjà !</div>';
            } else {
                $sql = "INSERT INTO utilisateur (nom, prenom, email, login, mot_de_passe, role, etat_compte) 
                        VALUES (:nom, :prenom, :email, :login, :mot_de_passe, :role, 'actif')";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([
                    ':nom' => $_POST['nom'],
                    ':prenom' => $_POST['prenom'],
                    ':email' => $_POST['email'],
                    ':login' => $_POST['login'],
                    ':mot_de_passe' => $_POST['mot_de_passe'],
                    ':role' => $_POST['role']
                ]);
                $message = '<div class="alert-success">Administrateur ajouté avec succès!</div>';
            }
        } catch(PDOException $e) {
            $message = '<div class="alert-error">Erreur : ' . $e->getMessage() . '</div>';
        }
    }
    
    if ($_POST['action'] == 'supprimer_admin' && isset($_POST['id_user'])) {
        try {
            // Ne pas supprimer son propre compte
            if ($_POST['id_user'] == $_SESSION['id_user']) {
                $message = '<div class="alert-error">Vous ne pouvez pas supprimer votre propre compte!</div>';
            } else {
                $pdo->prepare("DELETE FROM utilisateur WHERE id_user = ?")->execute([$_POST['id_user']]);
                $message = '<div class="alert-success">Administrateur supprimé!</div>';
            }
        } catch(PDOException $e) {
            $message = '<div class="alert-error">Erreur : ' . $e->getMessage() . '</div>';
        }
    }
}

// Récupérer la liste des admins
$admins = [];
try {
    $stmt = $pdo->query("SELECT * FROM utilisateur WHERE role IN ('admin', 'super_admin') ORDER BY id_user DESC");
    $admins = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>Gestion Admins | CPN</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; }
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap');
        
        body { background: #eff0f1; }
        header {
            background: linear-gradient(135deg, #e3e5ee 0%, #2f6d8c 50%, #095175 100%);
            padding: 15px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo { width: 150px; }
        .back-btn { background: #0a3144; color: white; padding: 8px 20px; text-decoration: none; border-radius: 8px; }
        .container { padding: 30px; }
        .card { background: white; padding: 25px; border-radius: 16px; margin-bottom: 30px; }
        .header-actions { display: flex; justify-content: space-between; margin-bottom: 20px; flex-wrap: wrap; gap: 15px; }
        .btn-ajouter { background: #1e6f9f; color: white; border: none; padding: 12px 22px; border-radius: 10px; cursor: pointer; }
        .btn-success { background: #28a745; }
        .btn-danger { background: #dc3545; }
        .btn-action { padding: 5px 10px; margin: 0 2px; border: none; border-radius: 5px; cursor: pointer; }
        
        table { width: 100%; border-collapse: collapse; background: white; border-radius: 16px; overflow: hidden; }
        table th { background: #0a3144; color: white; padding: 12px; }
        table td { padding: 10px; text-align: center; border-bottom: 1px solid #eee; }
        
        .form-container { background: white; padding: 25px; border-radius: 16px; margin-bottom: 25px; display: none; border: 2px solid #6ab0e6; }
        .form-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; }
        .form-grid input, .form-grid select { padding: 10px; border: 2px solid #e9ecef; border-radius: 8px; width: 100%; }
        .full-width { grid-column: span 2; }
        .form-buttons { display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px; }
        
        .alert-success { background: #d4edda; color: #155724; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 5px solid #28a745; }
        .alert-error { background: #f8d7da; color: #721c24; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 5px solid #dc3545; }
        
        .badge-admin { background: #1e6f9f; color: white; padding: 5px 10px; border-radius: 20px; font-size: 12px; }
        .badge-super { background: #ffc107; color: #000; padding: 5px 10px; border-radius: 20px; font-size: 12px; }
        
        @media(max-width: 768px) { .form-grid { grid-template-columns: 1fr; } .full-width { grid-column: span 1; } }
    </style>
</head>
<body>
    <header>
        <img src="logo.png" alt="Logo" class="logo" onerror="this.style.display='none'">
        <h1>👥 Gestion des Administrateurs</h1>
        <a href="admin.php" class="back-btn">← Retour</a>
    </header>
    
    <div class="container">
        <?php echo $message; ?>
        
        <div class="card">
            <div class="header-actions">
                <h2>Liste des administrateurs</h2>
                <button class="btn-ajouter" onclick="toggleFormulaire()">+ Ajouter Admin</button>
            </div>
            
            <!-- Formulaire d'ajout -->
            <div id="formulaireAdmin" class="form-container">
                <h3>Nouvel Administrateur</h3>
                <form method="POST">
                    <input type="hidden" name="action" value="ajouter_admin">
                    <div class="form-grid">
                        <input type="text" name="nom" placeholder="Nom" required>
                        <input type="text" name="prenom" placeholder="Prénom" required>
                        <input type="email" name="email" placeholder="Email" required>
                        <input type="text" name="login" placeholder="Login" required>
                        <input type="password" name="mot_de_passe" placeholder="Mot de passe" required>
                        <select name="role" required>
                            <option value="admin">Admin</option>
                            <option value="super_admin">Super Admin</option>
                        </select>
                    </div>
                    <div class="form-buttons">
                        <button type="submit" class="btn-ajouter btn-success">Créer</button>
                        <button type="button" class="btn-ajouter btn-danger" onclick="toggleFormulaire()">Annuler</button>
                    </div>
                </form>
            </div>
            
            <table>
                <thead>
                    <tr><th>ID</th><th>Nom complet</th><th>Email</th><th>Login</th><th>Rôle</th><th>Actions</th></tr>
                </thead>
                <tbody>
                    <?php foreach ($admins as $admin): ?>
                    <tr>
                        <td><?php echo $admin['id_user']; ?></td>
                        <td><?php echo htmlspecialchars($admin['nom'] . ' ' . $admin['prenom']); ?></td>
                        <td><?php echo htmlspecialchars($admin['email']); ?></td>
                        <td><?php echo htmlspecialchars($admin['login']); ?></td>
                        <td><span class="<?php echo $admin['role'] == 'super_admin' ? 'badge-super' : 'badge-admin'; ?>">
                            <?php echo $admin['role'] == 'super_admin' ? '👑 Super Admin' : '👤 Admin'; ?>
                        </span></td>
                        <td>
                            <?php if ($admin['id_user'] != $_SESSION['id_user']): ?>
                            <form method="POST" style="display:inline;">
                                <input type="hidden" name="action" value="supprimer_admin">
                                <input type="hidden" name="id_user" value="<?php echo $admin['id_user']; ?>">
                                <button type="submit" class="btn-action btn-danger" onclick="return confirm('Supprimer cet administrateur ?')">🗑️</button>
                            </form>
                            <?php else: ?>
                            <span style="color:gray;">(Compte actuel)</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <script>
        function toggleFormulaire() {
            let form = document.getElementById('formulaireAdmin');
            form.style.display = form.style.display === 'none' ? 'block' : 'none';
        }
    </script>
</body>
</html>