<?php
if (!defined('HOBBES')) { http_response_code(403); exit; }
$q = trim($_GET['q'] ?? '');
$per_page = 25;
$page_num = max(1, (int)($_GET['page'] ?? 1));
$results = $q ? search_query($q) : [];
$paged = paginate($results, $per_page, $page_num);
$page_title = 'Search' . ($q ? ': ' . h($q) : '');
$_page = 'search';
$cats = categories_load();
include ROOT_DIR . '/templates/header.php';
?>
<div class="panel">
<div class="panel-title">Search the Archive</div>
<div class="panel-body">
<form method="get" action="/search" class="std">
<table style="width:100%">
<tr>
<td><input type="text" name="q" value="<?php echo h($q); ?>" style="width:100%;font-size:13px;" placeholder="Enter keywords..."></td>
<td style="width:80px;padding-left:6px;"><button type="submit" class="btn btn-primary" style="width:100%">Search</button></td>
</tr>
</table>
</form>
<?php if ($q): ?>
<p class="muted" style="margin-top:8px;">
Found <strong><?php echo $paged['total']; ?></strong> result(s) for “<?php echo h($q); ?>”
<?php if ($paged['pages'] > 1): ?>
— Page <?php echo $paged['page']; ?> of <?php echo $paged['pages']; ?>
<?php endif; ?>
</p>
<table class="listing">
<thead>
<tr>
<th>Type</th>
<th>Filename</th>
<th>Title</th>
<th>Category</th>
<th class="size">Size</th>
<th style="width:46px;text-align:right;" title="Download count">DLs</th>
<th class="date">Date</th>
</tr>
</thead>
<tbody>
<?php if (empty($paged['items'])): ?>
<tr><td colspan="7" class="muted">No results found. Try different keywords.</td></tr>
<?php else: ?>
<?php foreach ($paged['items'] as $f):
$ext = get_extension($f['original_name']);
$cat = category_by_id($f['category'] ?? '');
?>
<tr>
<td class="icon"><?php echo file_icon($ext); ?></td>
<td><a href="<?php echo h(file_url($f)); ?>"><?php echo h($f['original_name']); ?></a></td>
<td>
<?php echo h($f['title'] ?? ''); ?>
<?php if (!empty($f['author'])): ?><br><span class="muted">by <?php echo h($f['author']); ?></span><?php endif; ?>
</td>
<td><?php echo $cat ? '<a href="/browse/' . h($cat['slug']) . '">' . h($cat['name']) . '</a>' : '—'; ?></td>
<td class="size"><?php echo format_size($f['size'] ?? 0); ?></td>
<td style="text-align:right;"><?php echo number_format((int)($f['downloads'] ?? 0)); ?></td>
<td class="date"><?php echo fmt_date($f['uploaded']); ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
<?php echo pagination_links($paged['page'], $paged['pages'], '/search?q=' . urlencode($q) . '&'); ?>
<?php endif; ?>
</div>
</div>
<?php include ROOT_DIR . '/templates/footer.php'; ?>