<?php
$ouvrages = Ouvrage::getAllOuvrages();
$authorizedRoles = ['admin', 'ca', 'bureau'];

if (isset($_SESSION['user'])) {
    include './vue/navlogin.php';
    $authorizedRoles = ['admin', 'ca', 'bureau'];
    $userRole = Rolle::getRolle($_SESSION['user']->getId_rolle())->getLibelle();
        if (in_array($userRole, $authorizedRoles, true)): ?>
        <div class="mb-3 d-flex justify-content-end">
            <a class="btn btn-secondary"
            href="index.php?uc=export_qr_pdf"
            target="_blank"
            rel="noopener">
            📄 Générer le PDF des QR
            </a>
        </div>
        <?php endif; ?>
    ?>
    <!-- Dynatable (conservé comme demandé) -->
    <link rel="stylesheet" href="https://s3.amazonaws.com/dynatable-docs-assets/css/jquery.dynatable.css" />
    <script src="https://s3.amazonaws.com/dynatable-docs-assets/js/jquery.dynatable.js"></script>

    <div class="container my-4">
      <h4 class="mb-3">Ludothèque — Ouvrages</h4>

      <div class="table-responsive">
        <table id="tabludotheque" class="table table-striped table-bordered align-middle">
          <thead class="table-dark">
            <tr>
              <th>N°</th>
              <th>Titre</th>
              <th>État</th>
              <th>Image</th>
              <th>Type</th>
              <th>Collection</th>
              <th>QR</th>
              <th>Statut</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if (!empty($ouvrages)) : ?>
            <?php foreach ($ouvrages as $o): 
              // Sécurisation + adaptation du type (objet)
              $numero     = htmlspecialchars($o->getNumero() ?? '', ENT_QUOTES, 'UTF-8');
              $titre      = htmlspecialchars($o->getTitre() ?? '', ENT_QUOTES, 'UTF-8');
              $etat       = htmlspecialchars($o->getEtat() ?? '', ENT_QUOTES, 'UTF-8');
              $img        = htmlspecialchars($o->getImg() ?? '', ENT_QUOTES, 'UTF-8');
              $collection = htmlspecialchars($o->getcollection() ?? '', ENT_QUOTES, 'UTF-8');

              // getId_type() renvoie un objet Type (d’après ton getAllOuvrages)
              $typeObj = $o->getId_type();
              $typeLib = '-';
              if ($typeObj instanceof Type) {
                  $typeLib = htmlspecialchars($typeObj->getLibelle() ?? '-', ENT_QUOTES, 'UTF-8');
              } elseif (is_string($typeObj)) {
                  // au cas où tu ne passerais plus un objet mais l’id brut
                  $typeLib = htmlspecialchars($typeObj, ENT_QUOTES, 'UTF-8');
              }
            ?>
              <tr>
                <td><?php echo $numero; ?></td>
                <td><?php echo $titre; ?></td>
                <td><?php echo $etat; ?></td>
                <td>
                  <?php if (!empty($img)) : ?>
                    <img src="<?php echo $img; ?>" alt="visuel"
                         class="img-fluid rounded" style="max-height:60px">
                  <?php else: ?>
                    -
                  <?php endif; ?>
                </td>
                <td><?php echo $typeLib; ?></td>
                <td><?php echo $collection !== '' ? $collection : '-'; ?></td>
                <td class="text-center">
                    <?php
                        // Bouton test (sans scanner)
                        $scanUrl = Ouvrage::scanUrl((int)$o->getId_ouvrage());
                    ?>
                    <a class="btn btn-sm btn-primary" href="<?php echo htmlspecialchars($scanUrl, ENT_QUOTES, 'UTF-8'); ?>"><img src="qr.php?id=<?php echo (int)$o->getId_ouvrage(); ?>"
                        alt="QR" class="img-thumbnail" style="max-height:80px"></a>
                </td>
                <?php
                    $idOuvrage = (int)$o->getId_ouvrage();
                    $dispo = Ouvrage::isDisponible($idOuvrage);
                ?>
                <td class="text-center">
                    <?php if ($dispo): ?>
                        <span class="badge rounded-pill bg-success">Disponible</span>
                    <?php else: ?>
                        <span class="badge rounded-pill bg-danger">Emprunté</span>
                    <?php endif; ?>
                </td>
                <td class="text-center">
                <?php
                  // Récupère le rôle utilisateur (même logique que pour le bouton global)
                  $userRole = null;
                  if (isset($_SESSION['user'])) {
                      if (method_exists($_SESSION['user'], 'getRole')) {
                          $userRole = strtolower((string)$_SESSION['user']->getRole());
                      } elseif (method_exists($_SESSION['user'], 'getId_rolle')) {
                          switch ((int)$_SESSION['user']->getId_rolle()) {
                              case 1: $userRole = 'admin';  break;
                              case 2: $userRole = 'ca';     break;
                              case 3: $userRole = 'bureau'; break;
                              default: $userRole = 'user';
                          }
                      }
                  }
                  $authorized = in_array($userRole, ['admin','ca','bureau'], true);
                ?>

                <?php if ($authorized): ?>
                  <a class="btn btn-sm btn-secondary"
                    href="index.php?uc=export_qr_single&id=<?php echo (int)$o->getId_ouvrage(); ?>"
                    target="_blank" rel="noopener">
                    PDF QR
                  </a>
                <?php else: ?>
                  <span class="text-muted small">—</span>
                <?php endif; ?>
              </td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
              <tr>
                <td colspan="6" class="text-center text-muted">Aucun ouvrage trouvé.</td>
                
              </tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <script>
      // Active Dynatable basique
      (function () {
        if (window.jQuery && jQuery.fn.dynatable) {
          jQuery(function($){
            $('#tabludotheque').dynatable({
              features: {
                paginate: true,
                sort: true,
                pushState: false,
                search: true,
                recordCount: true,
                perPageSelect: true
              },
              table: {
                defaultColumnIdStyle: 'trimDash'
              }
            });
          });
        }
      })();
    </script>

    <script src="./vue/js/tablejs.js"></script>
    <?php
}
