<?php
$categories = is_array($this->categories ?? null) ? $this->categories : [];
$inputName = trim((string)($this->inputName ?? 'categories[]'));
$selectedRaw = is_array($this->selectedIds ?? null) ? $this->selectedIds : [];
$selected = [];
foreach ($selectedRaw as $value) {
  $id = (int)$value;
  if ($id > 0) {
    $selected[$id] = true;
  }
}
?>
<?php if (!empty($categories)): ?>
  <ol class="coupon-categories-tree">
    <?php foreach ($categories as $category): ?>
      <?php
      $categoryId = (int)($category['id'] ?? 0);
      if ($categoryId <= 0) {
        continue;
      }

      $title = trim((string)($category['title'] ?? ''));
      if ($title === '') {
        $title = 'Kategoria #' . $categoryId;
      }

      $isActive = (int)($category['status'] ?? 0) === 1;
      $children = is_array($category['subcategories'] ?? null) ? $category['subcategories'] : [];
      $hasChildren = !empty($children);
      ?>
      <li class="coupon-category-item<?= $hasChildren ? ' has-children is-collapsed' : ''; ?>">
        <div class="coupon-category-row">
          <?php if ($hasChildren): ?>
            <button type="button" class="coupon-tree-toggle" aria-expanded="false" title="Rozwin / zwin">
              <i class="fa fa-caret-right"></i>
            </button>
          <?php else: ?>
            <span class="coupon-tree-spacer"></span>
          <?php endif; ?>

          <?php if (!$isActive): ?>
            <i class="fa fa-ban text-danger" title="Kategoria nieaktywna"></i>
          <?php endif; ?>

          <label class="coupon-category-label">
            <input
              type="checkbox"
              class="g-checkbox"
              name="<?= htmlspecialchars($inputName, ENT_QUOTES, 'UTF-8'); ?>"
              value="<?= $categoryId; ?>"
              <?= isset($selected[$categoryId]) ? 'checked="checked"' : ''; ?>
            />
            <span><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8'); ?></span>
          </label>
        </div>

        <?php if ($hasChildren): ?>
          <?= \Shared\Tpl\Tpl::view('shop-coupon/coupon-categories-tree', [
            'categories' => $children,
            'selectedIds' => array_keys($selected),
            'inputName' => $inputName,
          ]); ?>
        <?php endif; ?>
      </li>
    <?php endforeach; ?>
  </ol>
<?php endif; ?>

