<?php
session_start();
require_once __DIR__ . '/../db/connect.php';

// Access control: solo admin
if (!isset($_SESSION['role_name']) || $_SESSION['role_name'] !== 'admin') {
    header('Location: ../../index.php');
    exit;
}

// Query utenti con persona e ultimo ruolo assegnato
$sql = "SELECT u.user_id, u.descrizione AS username, u.data AS registrato_il,
               p.nome, p.cognome, p.cod_fiscale, p.telefono,
               COALESCE(r.name, 'utente') AS role_name
        FROM `user` u
        JOIN `person` p ON p.id_persona = u.person_id
        LEFT JOIN `permission` pm ON pm.user_id = u.user_id
            AND pm.data = (SELECT MAX(pm2.data) FROM `permission` pm2 WHERE pm2.user_id = u.user_id)
        LEFT JOIN `role` r ON r.id = pm.role
        ORDER BY u.user_id ASC";

$result = mysqli_query($conn, $sql);
if (!$result) {
    $error = mysqli_error($conn);
}
?>
<!DOCTYPE html>
<html lang="it">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Amministrazione | Utenti</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-[#f8fafc] text-[#1f2937]">
  <nav class="w-full bg-[#545454] text-white shadow">
    <div class="max-w-7xl mx-auto px-4">
      <div class="flex justify-between items-center h-16">
        <a href="../../index.php" class="font-semibold text-lg">Biblioteca Online</a>
        <div class="flex items-center gap-3">
          <span class="hidden md:inline text-sm">Admin: <?php echo htmlspecialchars($_SESSION['username'] ?? ''); ?></span>
          <a href="../auth/logout.php" class="px-4 py-2 bg-[#84dd63] text-[#1f2937] rounded hover:bg-[#cbff4d]">Logout</a>
        </div>
      </div>
    </div>
  </nav>

  <main class="max-w-7xl mx-auto px-4 py-8">
    <div class="flex items-center justify-between mb-6">
      <h1 class="text-2xl font-semibold">Utenti Registrati</h1>
      <a href="../../index.php" class="text-sm text-[#1f2937] hover:text-[#84dd63]">← Torna alla Home</a>
    </div>

    <?php if (!empty($error)): ?>
      <div class="p-4 bg-red-50 text-red-700 rounded mb-4">Errore DB: <?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <div class="overflow-x-auto bg-white shadow rounded">
      <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
          <tr>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Username</th>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Ruolo</th>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Registrato il</th>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nome</th>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Cognome</th>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Cod. Fiscale</th>
            <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Telefono</th>
          </tr>
        </thead>
        <tbody class="bg-white divide-y divide-gray-200">
          <?php if ($result && mysqli_num_rows($result) > 0): ?>
            <?php while ($row = mysqli_fetch_assoc($result)): ?>
              <tr class="hover:bg-gray-50">
                <td class="px-4 py-2 text-sm text-gray-700"><?php echo (int)$row['user_id']; ?></td>
                <td class="px-4 py-2 text-sm text-gray-700"><?php echo htmlspecialchars($row['username']); ?></td>
                <td class="px-4 py-2 text-sm">
                  <span class="px-2 py-1 rounded bg-[#84dd63] text-[#1f2937] text-xs font-medium"><?php echo htmlspecialchars($row['role_name']); ?></span>
                </td>
                <td class="px-4 py-2 text-sm text-gray-700"><?php echo htmlspecialchars($row['registrato_il'] ?? ''); ?></td>
                <td class="px-4 py-2 text-sm text-gray-700"><?php echo htmlspecialchars($row['nome']); ?></td>
                <td class="px-4 py-2 text-sm text-gray-700"><?php echo htmlspecialchars($row['cognome']); ?></td>
                <td class="px-4 py-2 text-sm text-gray-700 font-mono"><?php echo htmlspecialchars($row['cod_fiscale']); ?></td>
                <td class="px-4 py-2 text-sm text-gray-700"><?php echo htmlspecialchars($row['telefono']); ?></td>
              </tr>
            <?php endwhile; ?>
          <?php else: ?>
            <tr>
              <td colspan="8" class="px-4 py-6 text-center text-sm text-gray-500">Nessun utente trovato</td>
            </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </main>
</body>
</html>