#!/usr/bin/env php
<?php
$json = json_decode(file_get_contents('php://stdin'));
foreach ($json as $book) {
    $book->isbn = formatIsbn($book->isbn);

    $tags = array_flip($book->tags);
    unset($tags['Bücherregal (echt)']);
    unset($tags['ebook - gekauft']);
    $book->tagstr = implode(', ', array_keys($tags));

    if (!isset($book->series)) {
        $book->series = '';
    }
    $book->pubyear = '';
    $pubyear = date('Y', strtotime($book->pubdate));
    if ($pubyear != 101) {
        $book->pubyear = $pubyear;
    }
}

function formatIsbn($isbn)
{
    if ($isbn == '') {
        return '';
    }
    return substr($isbn, 0, 3) . '-' . substr($isbn, 3);
}
?>
<h1>Bibliothek</h1>
<p>
 Bücher im Bücherregal.
 Falls ihr in der Nähe seid und eins leihen möchtet, einfach Bescheid sagen.
</p>

<label style="display: block; text-align: right">
 Filter:
 <input type="search" class="light-table-filter" data-table="order-table" />
</label>
<table border="1" class="order-table">
 <caption>Bibliothek</caption>
 <thead>
  <tr>
   <th>Titel</th>
   <th>Autor</th>
   <th>Serie</th>
   <th>ISBN</th>
   <th>Tags</th>
   <th>Jahr</th>
  </tr>
 </thead>
 <tbody>
  <?php foreach ($json as $book) { ?>
  <tr class="h-cite">
   <td class="p-name"><?= htmlspecialchars($book->title) ?></td>
   <td class="p-author"><?= htmlspecialchars($book->authors) ?></td>
   <td><?= htmlspecialchars($book->series) ?></td>
   <td class="u-uid"><?= htmlspecialchars($book->isbn) ?></td>
   <td><?= htmlspecialchars($book->tagstr) ?></td>
   <td class="dt-published"><?= $book->pubyear ?></td>
  </tr>
  <?php } ?>
 </tbody>
</table>

<p>
 Last update: <?= date('Y-m-d') ?>
</p>

<script type="text/javascript" src="light-table-filter.min.js"></script>
<script type="text/javascript">LightTableFilter.init();</script>
