<?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;
    $firstname = trim($_POST['firstname']);
    $lastname = trim($_POST['lastname']);
    $email = trim($_POST['email']);
    $tel = trim($_POST['tel']);
    $role = $_POST['role'];
    $country = trim($_POST['country']);
    $villes = trim($_POST['villes']);
    $adresse = trim($_POST['adresse']);
    $statut = isset($_POST['statut']) ? 1 : 0;
    $solde = floatval($_POST['solde']);
    $password = !empty($_POST['password']) ? password_hash($_POST['password'], PASSWORD_BCRYPT) : null;

    if (empty($id)) {
        // Insert
        $sql = "INSERT INTO mondialisa_users (firstname,lastname,email,tel,role,country,villes,adresse,solde,statut,pass,dateajt)
                VALUES (?,?,?,?,?,?,?,?,?,?,NOW())";
        $stmt = $dbh->prepare($sql);
        $stmt->execute([$firstname,$lastname,$email,$tel,$role,$country,$villes,$adresse,$solde,$statut]);
        showMsg('success', "Utilisateur ajouté avec succès.");
    } else {
        // Update
        $sql = "UPDATE mondialisa_users SET firstname=?, lastname=?, email=?, tel=?, role=?, country=?, villes=?, adresse=?, solde=?, statut=?";
        $params = [$firstname,$lastname,$email,$tel,$role,$country,$villes,$adresse,$solde,$statut];
        if ($password) {
            $sql .= ", pass=?";
            $params[] = $password;
        }
        $sql .= " WHERE id=?";
        $params[] = $id;
        $stmt = $dbh->prepare($sql);
        $stmt->execute($params);
        showMsg('success', "Utilisateur mis à jour.");
    }
    header("Location: users.php");
    exit;
}

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

// --- LISTE ---
$stmt = $dbh->query("SELECT * FROM mondialisa_users ORDER BY dateajt DESC");
$users = $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>👥 Users </h2>
  </div>

  <?php displayMsgs(); ?>

  <table class="table table-bordered table-hover align-middle">
    <thead class="table-dark">
      <tr>
        <th>#</th>
        <th>Full name</th>
        <th>Email</th>
        <th>Tel</th>
        <th>Country</th>
        <th>City</th>
        <th>Role</th>
        <th>Statut</th>
        <th>Balance</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach($users as $u): ?>
        <tr>
          <td><?= $u['id'] ?></td>
          <td><?= htmlspecialchars($u['firstname'] . ' ' . $u['lastname']) ?></td>
          <td><?= htmlspecialchars($u['email']) ?></td>
          <td><?= htmlspecialchars($u['tel']) ?></td>
          <td><?= htmlspecialchars($u['country']) ?></td>
          <td><?= htmlspecialchars($u['villes']) ?></td>
          <td><span class="badge bg-secondary"><?= htmlspecialchars($u['role']) ?></span></td>
          <td><?= $u['statut'] ? '✅' : '❌' ?></td>
          <td><?= htmlspecialchars($u['solde']) ?></td>
          <td>
            <button class="btn btn-sm btn-outline-info" 
              onclick='viewUser(<?= json_encode($u, JSON_HEX_APOS|JSON_HEX_QUOT) ?>)'>👁</button>
            <button class="btn btn-sm btn-outline-primary" 
              onclick='editUser(<?= json_encode($u, JSON_HEX_APOS|JSON_HEX_QUOT) ?>)'>✏️</button>
            <a href="?delete=<?= $u['id'] ?>" class="btn btn-sm btn-outline-danger"
               onclick="return confirm('Supprimer cet utilisateur ?')">🗑️</a>
          </td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</main>

<!-- 👁 Modal Détails -->
<div class="modal fade" id="userViewModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header bg-info text-white">
        <h5 class="modal-title">Details</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <table class="table table-bordered">
          <tr><th>Full name</th><td id="v_nom"></td></tr>
          <tr><th>Email</th><td id="v_email"></td></tr>
          <tr><th>Tel</th><td id="v_tel"></td></tr>
          <tr><th>Role</th><td id="v_role"></td></tr>
          <tr><th>Country</th><td id="v_country"></td></tr>
          <tr><th>City</th><td id="v_villes"></td></tr>
          <tr><th>Adress</th><td id="v_adresse"></td></tr>
          <tr><th>Balance</th><td id="v_solde"></td></tr>
          <tr><th>Date</th><td id="v_dateajt"></td></tr>
        </table>
      </div>
      <div class="modal-footer">
        <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- ✏️ Modal Edition -->
<div class="modal fade" id="userEditModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <form class="modal-content" method="post">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">Edit user</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="id" id="e_id">

        <div class="row">
          <div class="col-md-6 mb-3">
            <label>First name</label>
            <input type="text" name="firstname" id="e_firstname" class="form-control" required>
          </div>
          <div class="col-md-6 mb-3">
            <label>Last name</label>
            <input type="text" name="lastname" id="e_lastname" class="form-control" required>
          </div>
          <div class="col-md-6 mb-3">
            <label>Email</label>
            <input type="email" name="email" id="e_email" class="form-control" required>
          </div>
          <div class="col-md-6 mb-3">
            <label>Tel</label>
            <input type="text" name="tel" id="e_tel" class="form-control">
          </div>
          <div class="col-md-6 mb-3">
            <label>Password</label>
            <input type="password" name="password" id="e_password" class="form-control">
            <small class="text-muted">Laisser vide pour ne pas changer</small>
          </div>
          <div class="col-md-6 mb-3">
            <label>Role</label>
            <select name="role" id="e_role" class="form-select">
              <option value="user">User</option>
              <option value="ambassador">Ambassador</option>
              <option value="manager">Country manager</option>
              <option value="admin">Admin</option>
            </select>
          </div>
          <div class="col-md-6 mb-3">
            <label>Country</label>
            <input type="text" name="country" id="e_country" class="form-control">
          </div>
          <div class="col-md-6 mb-3">
            <label>City</label>
            <input type="text" name="villes" id="e_villes" class="form-control">
          </div>
          <div class="col-md-12 mb-3">
            <label>Adress</label>
            <input type="text" name="adresse" id="e_adresse" class="form-control">
          </div>
          <div class="col-md-4 mb-3">
            <label>Balance</label>
            <input type="number" step="0.01" name="solde" id="e_solde" class="form-control">
          </div>
          <div class="col-md-4 mb-3">
            <label><input type="checkbox" name="statut" id="e_statut" value="1"> Enabled</label>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="submit" class="btn btn-primary">Save</button>
      </div>
    </form>
  </div>
</div>

<script>
function viewUser(u) {
  document.getElementById('v_nom').textContent = u.firstname + " " + u.lastname;
  document.getElementById('v_email').textContent = u.email;
  document.getElementById('v_tel').textContent = u.tel;
  document.getElementById('v_role').textContent = u.role;
  document.getElementById('v_country').textContent = u.country;
  document.getElementById('v_villes').textContent = u.villes;
  document.getElementById('v_adresse').textContent = u.adresse;
  document.getElementById('v_solde').textContent = u.solde;
  document.getElementById('v_dateajt').textContent = u.dateajt;
  new bootstrap.Modal(document.getElementById('userViewModal')).show();
}

function editUser(u) {
  document.getElementById('e_id').value = u.id;
  document.getElementById('e_firstname').value = u.firstname;
  document.getElementById('e_lastname').value = u.lastname;
  document.getElementById('e_email').value = u.email;
  document.getElementById('e_tel').value = u.tel;
  document.getElementById('e_country').value = u.country;
  document.getElementById('e_villes').value = u.villes;
  document.getElementById('e_adresse').value = u.adresse;
  document.getElementById('e_solde').value = u.solde;
  document.getElementById('e_role').value = u.role;
  document.getElementById('e_statut').checked = u.statut == 1;
  document.getElementById('e_password').value = '';
  new bootstrap.Modal(document.getElementById('userEditModal')).show();
}
</script>

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