<?php
$downloadsFile = __DIR__ . '/../devworks-admin/data/downloads.json';
$downloads = file_exists($downloadsFile) ? json_decode(file_get_contents($downloadsFile), true) : [];
if (!is_array($downloads)) $downloads = [];
usort($downloads, fn($a,$b) => ($a['sort'] ?? 100) <=> ($b['sort'] ?? 100));
$groups = [];
foreach ($downloads as $download) {
    if (empty($download['active'])) continue;
    $group = $download['group'] ?? 'General Resources';
    $groups[$group][] = $download;
}
?>
<section class="mdw-downloads">
  <h2>Public Downloads</h2>
  <p>Manuals, quick-start guides, setup notes, and public resources for Murdock DevWorks products.</p>
  <?php if (!$groups): ?>
    <div class="mdw-download-group"><p>No public downloads are currently listed.</p></div>
  <?php endif; ?>
  <?php foreach ($groups as $groupName => $items): ?>
    <div class="mdw-download-group">
      <h3><?php echo htmlspecialchars($groupName, ENT_QUOTES, 'UTF-8'); ?></h3>
      <?php foreach ($items as $item):
        $file = $item['file'] ?? '';
        $href = 'public-downloads/' . rawurlencode($file);
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        $target = $ext === 'pdf' ? ' target="_blank" rel="noopener"' : ' download';
      ?>
        <div class="mdw-download-row">
          <div><strong><?php echo htmlspecialchars($item['title'] ?? '', ENT_QUOTES, 'UTF-8'); ?></strong><span><?php echo htmlspecialchars($item['description'] ?? '', ENT_QUOTES, 'UTF-8'); ?></span></div>
          <a class="mdw-button" href="<?php echo htmlspecialchars($href, ENT_QUOTES, 'UTF-8'); ?>"<?php echo $target; ?>><?php echo htmlspecialchars($item['button'] ?? 'Open File', ENT_QUOTES, 'UTF-8'); ?></a>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endforeach; ?>
</section>
