<?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;
}

$msg = null; $err = null;

// Azioni POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $azione = $_POST['azione'] ?? '';
    if ($azione === 'crea_bibliotecario') {
        // Creazione nuovo account bibliotecario manuale
        $nome = trim($_POST['nome'] ?? '');
        $cognome = trim($_POST['cognome'] ?? '');
        $data_nascita = trim($_POST['data_nascita'] ?? '');
        $luogo_nascita = trim($_POST['luogo_nascita'] ?? '');
        $cod_fiscale = strtoupper(trim($_POST['cod_fiscale'] ?? ''));
        $telefono = preg_replace('/\D+/', '', $_POST['telefono'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $password = trim($_POST['password'] ?? '');

        $errors = [];
        if ($nome === '' || $cognome === '' || $luogo_nascita === '') $errors[] = 'Campi anagrafici obbligatori';
        if ($data_nascita === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $data_nascita)) $errors[] = 'Data nascita non valida';
        if ($cod_fiscale === '' || strlen($cod_fiscale) !== 16) $errors[] = 'Codice Fiscale non valido';
        if ($telefono === '' || !preg_match('/^\d{6,10}$/', $telefono)) $errors[] = 'Telefono non valido';
        if ($username === '' || strlen($username) < 3) $errors[] = 'Username troppo corto';
        if ($password === '' || preg_match('/\s/', $password) || strlen($password) < 8 || !preg_match('/[a-z]/', $password) || !preg_match('/[A-Z]/', $password) || !preg_match('/[^a-zA-Z0-9]/', $password)) {
            $errors[] = 'Password non conforme ai requisiti';
        }

        // Unicità username
        $username_e = mysqli_real_escape_string($conn, $username);
        $check = mysqli_query($conn, "SELECT user_id FROM `user` WHERE descrizione = '$username_e' LIMIT 1");
        if ($check && mysqli_num_rows($check) > 0) $errors[] = 'Username già esistente';

        if (!empty($errors)) {
            $err = implode(' | ', $errors);
        } else {
            $nome_e = mysqli_real_escape_string($conn, $nome);
            $cognome_e = mysqli_real_escape_string($conn, $cognome);
            $data_nascita_e = mysqli_real_escape_string($conn, $data_nascita);
            $luogo_nascita_e = mysqli_real_escape_string($conn, $luogo_nascita);
            $cod_fiscale_e = mysqli_real_escape_string($conn, $cod_fiscale);
            $telefono_e = mysqli_real_escape_string($conn, $telefono);
            $password_e = mysqli_real_escape_string($conn, $password);
            $oggi = date('Y-m-d');

            $sql_person = "INSERT INTO `person` (nome, cognome, data_nascita, luogo_nascita, cod_fiscale, telefono) VALUES ('$nome_e', '$cognome_e', '$data_nascita_e', '$luogo_nascita_e', '$cod_fiscale_e', '$telefono_e')";
            if (!mysqli_query($conn, $sql_person)) { $err = 'Errore inserimento persona'; }
            else {
                $person_id = mysqli_insert_id($conn);
                $sql_user = "INSERT INTO `user` (descrizione, data, person_id, password) VALUES ('$username_e', '$oggi', $person_id, '$password_e')";
                if (!mysqli_query($conn, $sql_user)) { $err = 'Errore inserimento utente'; }
                else {
                    $user_id = mysqli_insert_id($conn);
                    $sql_perm = "INSERT INTO `permission` (user_id, role, data) VALUES ($user_id, 2, '$oggi')"; // bibliotecario
                    if (!mysqli_query($conn, $sql_perm)) { $err = 'Errore assegnazione ruolo'; }
                    else { $msg = 'Bibliotecario creato correttamente'; }
                }
            }
        }
    }
}

// Query elenco bibliotecari correnti, basata sul ruolo più recente
$sql_b = "SELECT u.user_id, u.descrizione AS username, p.nome, p.cognome, p.cod_fiscale, p.telefono
          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)
              AND pm.role = (
                  SELECT MIN(pm3.role)
                  FROM `permission` pm3
                  WHERE pm3.user_id = u.user_id AND pm3.data = pm.data
              )
          WHERE pm.role = 2
          ORDER BY u.user_id ASC";
$biblios = mysqli_query($conn, $sql_b);

 
?>
<!DOCTYPE html>
<html lang="it">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Amministrazione | Bibliotecari</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">Gestione Bibliotecari</h1>
      <a href="../../index.php" class="text-sm text-[#1f2937] hover:text-[#84dd63]">← Torna alla Home</a>
    </div>

    <?php if ($msg): ?><div class="p-3 bg-green-50 text-green-700 rounded mb-4"><?php echo htmlspecialchars($msg); ?></div><?php endif; ?>
    <?php if ($err): ?><div class="p-3 bg-red-50 text-red-700 rounded mb-4"><?php echo htmlspecialchars($err); ?></div><?php endif; ?>

    <div class="grid md:grid-cols-2 gap-8">
      <section class="bg-white shadow rounded p-4 border border-[#e5e7eb]">
        <h2 class="text-lg font-semibold mb-3">Elenco Bibliotecari</h2>
        <div class="overflow-x-auto">
          <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">Cognome/Nome</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 ($biblios && mysqli_num_rows($biblios) > 0): ?>
                <?php while ($b = mysqli_fetch_assoc($biblios)): ?>
                  <tr class="hover:bg-gray-50">
                    <td class="px-4 py-2 text-sm text-gray-700"><?php echo (int)$b['user_id']; ?></td>
                    <td class="px-4 py-2 text-sm text-gray-700"><?php echo htmlspecialchars($b['username']); ?></td>
                    <td class="px-4 py-2 text-sm text-gray-700"><?php echo htmlspecialchars($b['cognome'] . ' ' . $b['nome']); ?></td>
                    <td class="px-4 py-2 text-sm text-gray-700"><?php echo htmlspecialchars($b['telefono']); ?></td>
                  </tr>
                <?php endwhile; ?>
              <?php else: ?>
                <tr><td colspan="4" class="px-4 py-6 text-center text-sm text-gray-500">Nessun bibliotecario</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </section>

      <section class="bg-white shadow rounded p-4 border border-[#e5e7eb]">
        <h2 class="text-lg font-semibold mb-3">Crea Bibliotecario</h2>
        <form method="post" class="grid grid-cols-1 md:grid-cols-2 gap-3">
          <input type="hidden" name="azione" value="crea_bibliotecario" />
          <div>
            <label class="block text-sm text-[#69747c]">Nome</label>
            <input type="text" name="nome" required class="mt-1 w-full border rounded px-3 py-2">
          </div>
          <div>
            <label class="block text-sm text-[#69747c]">Cognome</label>
            <input type="text" name="cognome" required class="mt-1 w-full border rounded px-3 py-2">
          </div>
          <div>
            <label class="block text-sm text-[#69747c]">Data di nascita</label>
            <input type="date" name="data_nascita" required class="mt-1 w-full border rounded px-3 py-2">
          </div>
          <div>
            <label class="block text-sm text-[#69747c]">Luogo di nascita</label>
            <input type="text" name="luogo_nascita" required class="mt-1 w-full border rounded px-3 py-2">
          </div>
          <div>
            <label class="block text-sm text-[#69747c]">Codice Fiscale</label>
            <input type="text" name="cod_fiscale" maxlength="16" required class="mt-1 w-full border rounded px-3 py-2 uppercase">
          </div>
          <div>
            <label class="block text-sm text-[#69747c]">Telefono</label>
            <input type="tel" name="telefono" maxlength="10" required class="mt-1 w-full border rounded px-3 py-2">
          </div>
          <div class="md:col-span-2 border-t pt-3">
            <h3 class="text-md font-semibold text-[#545454]">Credenziali</h3>
          </div>
          <div>
            <label class="block text-sm text-[#69747c]">Username</label>
            <input type="text" name="username" required class="mt-1 w-full border rounded px-3 py-2">
          </div>
          <div>
            <label class="block text-sm text-[#69747c]">Password</label>
            <input type="password" name="password" required class="mt-1 w-full border rounded px-3 py-2">
          </div>
          <div class="md:col-span-2 mt-2">
            <button class="px-4 py-2 bg-[#6baa75] text-white rounded hover:bg-[#84dd63]">Crea Bibliotecario</button>
          </div>
        </form>
      </section>
    </div>

    
  </main>
</body>
</html>

