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

$isLogged = isset($_SESSION['user_id']);
$roleName = $_SESSION['role_name'] ?? null;

// Filtri
$q = trim($_GET['q'] ?? '');
$tipo = trim($_GET['tipo'] ?? ''); // '', 'libro', 'film', 'documentario'

// Costruzione query
$where = ["stato = 'attivo'"];
if ($q !== '') {
  $q_e = mysqli_real_escape_string($conn, $q);
  $where[] = "(titolo LIKE '%$q_e%' OR autore_regista LIKE '%$q_e%' OR descrizione LIKE '%$q_e%')";
}
if ($tipo !== '' && in_array($tipo, ['libro','film','documentario'])) {
  $tipo_e = mysqli_real_escape_string($conn, $tipo);
  $where[] = "tipo = '$tipo_e'";
}
$whereSql = implode(' AND ', $where);

$sql = "SELECT id_item, codice, tipo, titolo, autore_regista, descrizione, costo_noleggio, argomento, data_inserimento, copertina_url
         FROM item WHERE $whereSql ORDER BY data_inserimento DESC, id_item DESC";
$result = mysqli_query($conn, $sql);
$error = $result ? null : 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>Catalogo | Biblioteca</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-[#f8fafc] text-[#545454]">
  <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">
        <div class="flex items-center gap-6">
          <a href="../index.php" class="font-semibold text-lg">Biblioteca Online</a>
          <div class="hidden md:flex items-center gap-4">
            <a href="./catalogo.php" class="hover:text-[#cbff4d]">Catalogo</a>
            <a href="#" class="hover:text-[#cbff4d]">Recensioni</a>
          </div>
        </div>
        <div class="hidden md:flex items-center gap-4">
          <?php if ($isLogged && $roleName === 'admin'): ?>
            <a href="./admin/users.php" class="hover:text-[#cbff4d]">Gestione Utenti</a>
            <a href="./admin/bibliotecari.php" class="hover:text-[#cbff4d]">Gestione Bibliotecari</a>
          <?php elseif ($isLogged && $roleName === 'bibliotecario'): ?>
            <a href="#" class="hover:text-[#cbff4d]">Elenco Libri</a>
            <a href="#" class="hover:text-[#cbff4d]">Elenco Film</a>
          <?php elseif ($isLogged && $roleName === 'utente'): ?>
            <a href="#" class="hover:text-[#cbff4d]">Prenota</a>
            <a href="#" class="hover:text-[#cbff4d]">Le mie Prenotazioni</a>
          <?php endif; ?>
        </div>
        <div class="flex items-center gap-3">
          <?php if ($isLogged): ?>
            <span class="hidden md:inline text-sm">Ciao, <?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>
          <?php else: ?>
            <a href="../index.php" class="px-4 py-2 bg-[#84dd63] text-[#1f2937] rounded hover:bg-[#cbff4d]">Accedi</a>
          <?php endif; ?>
        </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">Catalogo</h1>
      <form method="get" class="flex items-center gap-2">
        <select name="tipo" class="border rounded px-3 py-2">
          <option value="">Tutti</option>
          <option value="libro" <?php echo $tipo==='libro'?'selected':''; ?>>Libri</option>
          <option value="film" <?php echo $tipo==='film'?'selected':''; ?>>Film</option>
          <option value="documentario" <?php echo $tipo==='documentario'?'selected':''; ?>>Documentari</option>
        </select>
        <input type="text" name="q" value="<?php echo htmlspecialchars($q); ?>" placeholder="Cerca titolo/autore..." class="border rounded px-3 py-2 w-64" />
        <button class="px-4 py-2 bg-[#6baa75] text-white rounded hover:bg-[#84dd63]">Cerca</button>
      </form>
    </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="grid grid-cols-1 md:grid-cols-3 gap-6">
      <?php if ($result && mysqli_num_rows($result) > 0): ?>
        <?php while ($row = mysqli_fetch_assoc($result)): ?>
          <div class="bg-white rounded shadow border border-[#e5e7eb] overflow-hidden">
            <img src="<?php echo htmlspecialchars($row['copertina_url'] ?: 'https://placehold.co/600x400?text=Copertina'); ?>" alt="Copertina" class="w-full h-40 object-cover" onerror="this.src='https://placehold.co/600x400?text=Copertina'" />
            <div class="p-4">
              <div class="flex items-center justify-between">
                <h3 class="text-lg font-semibold text-[#545454]"><?php echo htmlspecialchars($row['titolo']); ?></h3>
                <span class="px-2 py-1 text-xs rounded bg-[#84dd63] text-[#1f2937]"><?php echo htmlspecialchars(ucfirst($row['tipo'])); ?></span>
              </div>
              <p class="text-sm text-[#69747c] mt-1">di <?php echo htmlspecialchars($row['autore_regista']); ?></p>
              <p class="text-sm text-[#69747c] mt-2 line-clamp-3"><?php echo htmlspecialchars($row['descrizione']); ?></p>
              <div class="mt-3 flex items-center justify-between">
                <span class="text-sm text-[#1f2937] font-medium">Costo: € <?php echo number_format((float)$row['costo_noleggio'],2,',','.'); ?></span>
                <a href="#" class="text-sm text-[#6baa75] hover:text-[#84dd63]">Dettagli</a>
              </div>
            </div>
          </div>
        <?php endwhile; ?>
      <?php else: ?>
        <div class="md:col-span-3 p-6 bg-white rounded shadow text-center text-sm text-[#69747c]">Nessuna entità trovata</div>
      <?php endif; ?>
    </div>
  </main>
</body>
</html>

