<?php
//admins.php
require_once "inc/config.php";
require_once "inc/functions.php";
checkLogin();

if ($_SESSION['admin']['role'] !== 'superadmin') {
    header("Location: index.php");
    exit;
}

// --- AJOUT / MODIFICATION ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;
    $nom = trim($_POST['nom']);
    $email = trim($_POST['email']);
    $password = !empty($_POST['password']) ? password_hash($_POST['password'], PASSWORD_BCRYPT) : null;
    if ($_SESSION['admin']['role'] !== 'superadmin') {
    unset($_POST['role']);
    }

    $role = $_POST['role'];
    $countries = trim($_POST['countries']);
    $cities = trim($_POST['cities']);
    $actif = isset($_POST['actif']) ? 1 : 0;

    if (empty($id)) {
        // Insert
        $sql = "INSERT INTO mondialisa_admins (nom,email,password,role,countries,cities,actif)
                VALUES (?,?,?,?,?,?,?)";
        $stmt = $dbh->prepare($sql);
        $stmt->execute([$nom,$email,$password,$role,$countries,$cities,$actif]);
        showMsg('success', "Administrateur ajouté avec succès.");
    } else {
        // Update
        $sql = "UPDATE mondialisa_admins SET nom=?, email=?, role=?, countries=?, cities=?, actif=?";
        $params = [$nom,$email,$role,$countries,$cities,$actif];
        if ($password) {
            $sql .= ", password=?";
            $params[] = $password;
        }
        $sql .= " WHERE id=?";
        $params[] = $id;
        $stmt = $dbh->prepare($sql);
        $stmt->execute($params);
        showMsg('success', "Administrateur mis à jour.");
    }
    header("Location: admins.php");
    exit;
}

// --- SUPPRESSION ---
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $stmt = $dbh->prepare("DELETE FROM mondialisa_admins WHERE id = ?");
    $stmt->execute([$id]);
    showMsg('success', "Administrateur supprimé.");
    header("Location: admins.php");
    exit;
}

// --- LISTE DES ADMINS ---
$stmt = $dbh->query("SELECT * FROM mondialisa_admins ORDER BY created_at DESC");
$admins = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php include "inc/header.php"; ?>
<?php include "inc/sidebar.php"; ?>
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
  <?php include "inc/topbar.php"; ?>
  <div class="pt-3 pb-2 mb-3 border-bottom d-flex justify-content-between align-items-center">
    <h2>👥 Gestion des administrateurs</h2>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#adminModal">➕ Nouvel Admin</button>
  </div>

  <?php displayMsgs(); ?>

  <table class="table table-bordered table-hover align-middle">
    <thead class="table-dark">
      <tr>
        <th>#</th>
        <th>Nom</th>
        <th>Email</th>
        <th>Rôle</th>
        <th>Pays</th>
        <th>Villes</th>
        <th>Actif</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach($admins as $a): ?>
        <tr>
          <td><?= $a['id'] ?></td>
          <td><?= htmlspecialchars($a['nom']) ?></td>
          <td><?= htmlspecialchars($a['email']) ?></td>
          <td><span class="badge bg-<?= $a['role']=='superadmin'?'danger':'secondary' ?>"><?= $a['role'] ?></span></td>
          <td><?= htmlspecialchars($a['countries']) ?></td>
          <td><?= htmlspecialchars($a['cities']) ?></td>
          <td><?= $a['actif'] ? '✅' : '❌' ?></td>
          <td>
            <button class="btn btn-sm btn-outline-primary" 
              onclick='editAdmin(<?= json_encode($a, JSON_HEX_APOS|JSON_HEX_QUOT) ?>)'>
              ✏️
            </button>
            <a href="?delete=<?= $a['id'] ?>" 
               class="btn btn-sm btn-outline-danger"
               onclick="return confirm('Supprimer cet administrateur ?')">🗑️</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</main>

<!-- 🧩 Modal Ajout / Edition -->
<div class="modal fade" id="adminModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <form class="modal-content" method="post">
      <div class="modal-header">
        <h5 class="modal-title">Nouvel administrateur</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="admin_id">

        <div class="row">
          <div class="col-md-6 mb-3">
            <label>Nom</label>
            <input type="text" name="nom" id="admin_nom" class="form-control" required>
          </div>
          <div class="col-md-6 mb-3">
            <label>Email</label>
            <input type="email" name="email" id="admin_email" class="form-control" required>
          </div>
          <div class="col-md-6 mb-3">
            <label>Mot de passe</label>
            <input type="password" name="password" id="admin_password" class="form-control">
            <small class="text-muted">Laisser vide pour ne pas changer</small>
          </div>
          <div class="col-md-6 mb-3">
            <label>Rôle</label>
            <select name="role" id="admin_role" class="form-select">
              <option value="admin">Admin</option>
              <option value="superadmin">Super Admin</option>
            </select>
          </div>
          <div class="col-md-6 mb-3">
            <label>Pays (codes séparés par virgule)</label>
            <input type="text" name="countries" id="admin_countries" class="form-control" placeholder="MA,FR,ES">
          </div>
          <div class="col-md-6 mb-3">
            <label>Villes (séparées par virgule)</label>
            <input type="text" name="cities" id="admin_cities" class="form-control" placeholder="Casablanca,Marrakech">
          </div>
          <div class="col-md-12 mb-3">
            <label><input type="checkbox" name="actif" id="admin_actif" value="1"> Compte actif</label>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
        <button type="submit" class="btn btn-primary">Enregistrer</button>
      </div>
    </form>
  </div>
</div>

<script>
function editAdmin(admin) {
  document.getElementById('admin_id').value = admin.id;
  document.getElementById('admin_nom').value = admin.nom;
  document.getElementById('admin_email').value = admin.email;
  document.getElementById('admin_role').value = admin.role;
  document.getElementById('admin_countries').value = admin.countries ?? '';
  document.getElementById('admin_cities').value = admin.cities ?? '';
  document.getElementById('admin_actif').checked = admin.actif == 1;
  document.getElementById('admin_password').value = '';
  document.querySelector('#adminModal .modal-title').textContent = "Modifier administrateur";
  new bootstrap.Modal(document.getElementById('adminModal')).show();
}
</script>

<?php include "inc/footer.php"; ?>
