<?php
// ============================================================
// AJAX: update — MUST be before ANY HTML output
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
    header('Content-Type: application/json');
    include '_serveur.php';
    $id       = intval($_POST['user_id']);
    $username = mysqli_real_escape_string($link, trim($_POST['username']));
    $pass     = mysqli_real_escape_string($link, trim($_POST['pass']));
    if ($id > 0 && $username !== '') {
        $ok = mysqli_query($link, "UPDATE users SET username='$username', pass='$pass' WHERE id=$id AND type=2");
        echo json_encode(['ok' => (bool)$ok, 'msg' => $ok ? 'Modifie avec succes.' : mysqli_error($link)]);
    } else {
        echo json_encode(['ok' => false, 'msg' => 'Donnees invalides.']);
    }
    exit;
}

// ============================================================
// AJAX: delete — MUST be before ANY HTML output
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    header('Content-Type: application/json');
    include '_serveur.php';
    $id = intval($_POST['user_id']);
    if ($id > 0) {
        mysqli_query($link, "DELETE FROM devices WHERE userID=$id");
        $ok = mysqli_query($link, "DELETE FROM users WHERE id=$id AND type=2");
        echo json_encode(['ok' => (bool)$ok, 'msg' => $ok ? 'Professeur supprime.' : mysqli_error($link)]);
    } else {
        echo json_encode(['ok' => false, 'msg' => 'ID invalide.']);
    }
    exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="w3.css">
<title>Profs</title>
</head>
<style>
@media print {
  .noprint { display: none; }
  .page-break { display:block; page-break-after:always; }
  @page { size: 210mm 297mm; margin: 7mm 7mm 7mm 7mm; }
}
body { width:90%; }

.badge-inscrit {
  background: #22b573; color: #fff;
  border-radius: 12px; padding: 2px 11px;
  font-size: 0.85em; font-weight: bold;
}
.badge-non {
  background: #e0e0e0; color: #888;
  border-radius: 12px; padding: 2px 11px;
  font-size: 0.85em;
}
.btn-edit {
  background: #2c5f9e; color: #fff;
  border: none; border-radius: 4px;
  padding: 4px 10px; cursor: pointer; font-size: 0.87em;
}
.btn-edit:hover { background: #1a4070; }

.btn-del {
  background: #c0392b; color: #fff;
  border: none; border-radius: 4px;
  padding: 4px 10px; cursor: pointer; font-size: 0.87em; margin-left:4px;
}
.btn-del:hover { background: #96281b; }

/* Modals */
.modal-overlay {
  display: none; position: fixed;
  top:0; left:0; right:0; bottom:0;
  background: rgba(0,0,0,0.45); z-index: 100;
}
.modal-overlay.active { display: flex; align-items: center; justify-content: center; }
.modal-box {
  background: #fff; border-radius: 9px;
  padding: 28px 32px; width: 320px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.18); position: relative;
}
.modal-box h3 { margin: 0 0 18px 0; color: #2c5f9e; font-size: 1.05em; }
.modal-box h3.del { color: #c0392b; }
.modal-box label { display:block; font-size:0.87em; color:#555; margin-top:12px; font-weight:600; }
.modal-box input[type=text] {
  width:100%; padding:7px 9px; border:1px solid #c5d5ee;
  border-radius:4px; font-size:0.94em; box-sizing:border-box; background:#f7faff;
}
.modal-box input:focus { outline:none; border-color:#2c5f9e; }
.modal-actions { margin-top:20px; display:flex; gap:9px; justify-content:flex-end; }
.btn-save    { background:#22b573; color:#fff; border:none; border-radius:4px; padding:7px 20px; cursor:pointer; font-weight:600; }
.btn-save:hover { background:#1a8f5a; }
.btn-confirm { background:#c0392b; color:#fff; border:none; border-radius:4px; padding:7px 20px; cursor:pointer; font-weight:600; }
.btn-confirm:hover { background:#96281b; }
.btn-cancel  { background:#e0e0e0; color:#555; border:none; border-radius:4px; padding:7px 14px; cursor:pointer; }
.close-x { position:absolute; top:10px; right:14px; font-size:1.3em; cursor:pointer; color:#aaa; }
.close-x:hover { color:#333; }
.msg-ok  { background:#e6f9f0; color:#22b573; border:1px solid #b2ecd3; padding:7px 12px; border-radius:4px; margin-top:12px; display:none; }
.msg-err { background:#fff0f0; color:#c0392b; border:1px solid #f5c6c6; padding:7px 12px; border-radius:4px; margin-top:12px; display:none; }
.del-name { font-weight:bold; color:#333; }
</style>
<body>

<div class="w3-card-4">
<?php

echo '<button type="button" class="noprint" onclick="window.print()"><img src="imprimante.png" height="32" width="40" /></button>';

include 'header.php';
include '_serveur.php';

$sql = 'SELECT * FROM users LEFT JOIN devices ON users.id=devices.userID WHERE users.type=2';

if (!(mysqli_query($link, $sql))) {
    echo "ERROR: Could not execute $sql. " . mysqli_error($link);
}

echo '<div class="w3-container">';
$j = 1;
$req = mysqli_query($link, $sql);
echo "Date:  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . date('d/m/Y');

while ($data = mysqli_fetch_array($req)) {
    $id        = $data[0];
    $username  = $data[1];
    $firstName = $data[2];
    $lastName  = $data[3];
    $pass      = $data[4];
    $ipcell    = $data[7];
    $cell      = $data[9];

    $inscrit = ($ipcell != "");

    echo '<div class="w3-container w3-left-align">';

    if ($j == 1) {
        echo '<table width="95%" border=1 cellspacing=0>';
        echo "<tr bgcolor='#BDDCFD'>
                <td width='5%'>Nom Utilisateur</td>
                <td width='5%'>Prenom</td>
                <td width='5%'>Nom</td>
                <td width='5%'>Passe</td>
                <td width='10%'>Statut App</td>
                <td width='5%'>Genre</td>
                <td width='10%' class='noprint'>Actions</td>
              </tr>";
    }

    $badge = $inscrit
        ? '<span class="badge-inscrit">&#10003; Inscrit</span>'
        : '<span class="badge-non">Non inscrit</span>';

    $safeUser  = htmlspecialchars($username,                ENT_QUOTES);
    $safePass  = htmlspecialchars($pass,                    ENT_QUOTES);
    $safeFull  = htmlspecialchars($firstName.' '.$lastName, ENT_QUOTES);

    echo "<tr id='row-$id'>
            <td>$username</td>
            <td>$firstName</td>
            <td>$lastName</td>
            <td>$pass</td>
            <td>$badge</td>
            <td>$cell</td>
            <td class='noprint'>
              <button class='btn-edit'
                onclick=\"openEdit($id, '$safeUser', '$safePass')\">
                &#9998; Modifier
              </button>
              <button class='btn-del'
                onclick=\"openDelete($id, '$safeFull')\">
                &#128465; Effacer
              </button>
            </td>
          </tr>";

    $j++;
}
?>
</table>
</div>
</div>

<!-- Edit Modal -->
<div class="modal-overlay noprint" id="editModal">
  <div class="modal-box">
    <span class="close-x" onclick="closeEdit()">&times;</span>
    <h3>&#9998; Modifier le professeur</h3>
    <input type="hidden" id="edit_id">
    <label>Nom d'utilisateur</label>
    <input type="text" id="edit_username">
    <label>Mot de passe</label>
    <input type="text" id="edit_pass">
    <div class="modal-actions">
      <button class="btn-cancel" onclick="closeEdit()">Annuler</button>
      <button class="btn-save"   onclick="saveChanges()">Enregistrer</button>
    </div>
    <div class="msg-ok"  id="edit-msg-ok"></div>
    <div class="msg-err" id="edit-msg-err"></div>
  </div>
</div>

<!-- Delete Confirm Modal -->
<div class="modal-overlay noprint" id="delModal">
  <div class="modal-box">
    <span class="close-x" onclick="closeDelete()">&times;</span>
    <h3 class="del">&#128465; Confirmer la suppression</h3>
    <p>Supprimer le professeur <span class="del-name" id="del-name"></span> ?<br>
    <small style="color:#c0392b">Cette action supprime aussi son appareil enregistre.</small></p>
    <input type="hidden" id="del_id">
    <div class="modal-actions">
      <button class="btn-cancel"  onclick="closeDelete()">Annuler</button>
      <button class="btn-confirm" onclick="confirmDelete()">Supprimer</button>
    </div>
    <div class="msg-err" id="del-msg-err"></div>
  </div>
</div>

<script>
/* ---- Edit ---- */
function openEdit(id, username, pass) {
  document.getElementById('edit_id').value       = id;
  document.getElementById('edit_username').value = username;
  document.getElementById('edit_pass').value     = pass;
  document.getElementById('edit-msg-ok').style.display  = 'none';
  document.getElementById('edit-msg-err').style.display = 'none';
  document.getElementById('editModal').classList.add('active');
}
function closeEdit() { document.getElementById('editModal').classList.remove('active'); }

function saveChanges() {
  var id       = document.getElementById('edit_id').value;
  var username = document.getElementById('edit_username').value.trim();
  var pass     = document.getElementById('edit_pass').value.trim();
  if (!username) { showMsg('edit','err','Le nom utilisateur est requis.'); return; }
  var fd = new FormData();
  fd.append('action','update'); fd.append('user_id',id);
  fd.append('username',username); fd.append('pass',pass);
  fetch(window.location.pathname, {method:'POST', body:fd})
    .then(function(r){
      if (!r.ok) throw new Error('HTTP ' + r.status);
      return r.json();
    })
    .then(function(d){
      if (d.ok) {
        showMsg('edit','ok', d.msg);
        var row = document.getElementById('row-'+id);
        if (row) { row.cells[0].textContent = username; row.cells[3].textContent = pass; }
        var btn = row ? row.querySelector('.btn-edit') : null;
        if (btn) btn.setAttribute('onclick',"openEdit("+id+",'"+username+"','"+pass+"')");
      } else { showMsg('edit','err', d.msg); }
    })
    .catch(function(e){ showMsg('edit','err','Erreur reseau: ' + e.message); });
}

/* ---- Delete ---- */
function openDelete(id, fullname) {
  document.getElementById('del_id').value              = id;
  document.getElementById('del-name').textContent      = fullname;
  document.getElementById('del-msg-err').style.display = 'none';
  document.getElementById('delModal').classList.add('active');
}
function closeDelete() { document.getElementById('delModal').classList.remove('active'); }

function confirmDelete() {
  var id = document.getElementById('del_id').value;
  var fd = new FormData();
  fd.append('action','delete'); fd.append('user_id',id);
  fetch(window.location.pathname, {method:'POST', body:fd})
    .then(function(r){
      if (!r.ok) throw new Error('HTTP ' + r.status);
      return r.json();
    })
    .then(function(d){
      if (d.ok) {
        closeDelete();
        var row = document.getElementById('row-'+id);
        if (row) row.parentNode.removeChild(row);
      } else { showMsg('del','err', d.msg); }
    })
    .catch(function(e){ showMsg('del','err','Erreur reseau: ' + e.message); });
}

/* ---- Helpers ---- */
function showMsg(modal, type, msg) {
  var ok  = document.getElementById(modal+'-msg-ok');
  var err = document.getElementById(modal+'-msg-err');
  if (ok)  ok.style.display  = 'none';
  if (err) err.style.display = 'none';
  var el = document.getElementById(modal+'-msg-'+type);
  if (el) { el.textContent = msg; el.style.display = 'block'; }
}

document.getElementById('editModal').addEventListener('click', function(e){ if(e.target===this) closeEdit(); });
document.getElementById('delModal').addEventListener('click',  function(e){ if(e.target===this) closeDelete(); });
</script>

</body>
</html>
