<?php use App\Core\View; ?>
<header class="page-head row">
  <div>
    <h1><?= View::e($module['label']) ?></h1>
    <p><?= count($rows) ?> item<?= count($rows) === 1 ? '' : 's' ?></p>
  </div>
  <?php if (($module['canCreate'] ?? true) !== false): ?>
  <a class="btn" href="<?= View::url("/admin/$moduleKey/create") ?>">+ Add new</a>
  <?php endif; ?>
</header>

<div class="panel">
  <table class="table">
    <thead>
      <tr>
        <?php foreach ($module['columns'] as $col): ?>
        <th><?= View::e(ucwords(str_replace('_', ' ', $col))) ?></th>
        <?php endforeach; ?>
        <th class="actions">Actions</th>
      </tr>
    </thead>
    <tbody>
      <?php if (!$rows): ?>
      <tr><td colspan="<?= count($module['columns']) + 1 ?>" class="empty">Nothing here yet.</td></tr>
      <?php endif; ?>
      <?php foreach ($rows as $row): ?>
      <tr>
        <?php foreach ($module['columns'] as $col): $v = $row[$col] ?? ''; ?>
        <td>
          <?php if (in_array($col, ['src', 'image', 'photo'], true) && $v): ?>
            <img class="thumb" src="<?= View::e($v) ?>" alt="">
          <?php elseif (in_array($col, ['featured', 'status', 'active', 'approved', 'handled'], true)): ?>
            <?php if ($v === 0 || $v === 1 || $v === '0' || $v === '1' || $v === ''): ?>
              <span class="badge <?= $v ? 'ok' : '' ?>"><?= $v ? 'Yes' : 'No' ?></span>
            <?php else: // text status, e.g. bookings paid/pending, blog draft/published ?>
              <span class="badge <?= in_array($v, ['paid', 'published'], true) ? 'ok' : '' ?>"><?= View::e(ucfirst((string) $v)) ?></span>
            <?php endif; ?>
          <?php else: ?>
            <?= View::e(mb_substr((string) $v, 0, 60)) ?>
          <?php endif; ?>
        </td>
        <?php endforeach; ?>
        <td class="actions">
          <a class="btn sm" href="<?= View::url("/admin/$moduleKey/" . (int) $row['id'] . '/edit') ?>">Edit</a>
          <?php if (($module['canDelete'] ?? true) !== false): ?>
          <form method="post" action="<?= View::url("/admin/$moduleKey/" . (int) $row['id'] . '/delete') ?>"
                onsubmit="return confirm('Delete this item? This cannot be undone.')">
            <input type="hidden" name="_csrf" value="<?= $csrf ?>">
            <button class="btn sm danger" type="submit">Delete</button>
          </form>
          <?php endif; ?>
        </td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
