<?php require_once __DIR__ . '/includes/admin_bootstrap.php';
ugfx_require_permission('requests');
$items = ugfx_read_json($ugfx['storage']['requests'], []);
$message = '';
$statusFilter = trim((string)($_GET['status'] ?? 'all'));
$search = trim((string)($_GET['q'] ?? ''));

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'delete') {
        $id = (string)($_POST['id'] ?? '');
        $items = array_values(array_filter($items, fn($item) => (string)($item['id'] ?? '') !== $id));
        ugfx_write_json($ugfx['storage']['requests'], $items);
        $message = 'Request deleted.';
    } elseif ($action === 'mark_status') {
        $id = (string)($_POST['id'] ?? '');
        $status = trim((string)($_POST['status'] ?? 'new')) ?: 'new';
        foreach ($items as &$item) {
            if ((string)($item['id'] ?? '') === $id) {
                $item['status'] = $status;
                break;
            }
        }
        unset($item);
        ugfx_write_json($ugfx['storage']['requests'], $items);
        $message = 'Request updated.';
    } elseif ($action === 'clear_done') {
        $items = array_values(array_filter($items, fn($item) => strtolower((string)($item['status'] ?? 'new')) !== 'done'));
        ugfx_write_json($ugfx['storage']['requests'], $items);
        $message = 'Done requests cleared.';
    }
    $items = ugfx_read_json($ugfx['storage']['requests'], []);
}

$allItems = array_values(array_map(function($item) {
    if (!isset($item['id']) || trim((string)$item['id']) === '') {
        $item['id'] = md5(json_encode($item));
    }
    if (!isset($item['status']) || trim((string)$item['status']) === '') {
        $item['status'] = 'new';
    }
    return $item;
}, $items));
$counts = ['all' => count($allItems), 'new' => 0, 'done' => 0];
foreach ($allItems as $item) {
    $st = strtolower((string)($item['status'] ?? 'new'));
    if (!isset($counts[$st])) $counts[$st] = 0;
    $counts[$st]++;
}
$items = $allItems;
if ($statusFilter !== 'all') {
    $items = array_values(array_filter($items, fn($item) => strtolower((string)($item['status'] ?? 'new')) === strtolower($statusFilter)));
}
if ($search !== '') {
    $needle = strtolower($search);
    $items = array_values(array_filter($items, function($item) use ($needle) {
        $hay = strtolower(trim((string)($item['name'] ?? '') . ' ' . (string)($item['artist'] ?? '') . ' ' . (string)($item['song'] ?? '') . ' ' . (string)($item['message'] ?? '')));
        return str_contains($hay, $needle);
    }));
}
$adminTitle='Requests'; include __DIR__ . '/includes/admin_header.php'; ?>
<?php if ($message): ?><div class="ugfx-admin-alert"><?= htmlspecialchars($message) ?></div><?php endif; ?>
<div class="ugfx-card p-4">
  <div class="ugfx-admin-toolbar mb-3">
    <div><div class="ugfx-micro-label">REQUEST QUEUE</div><h3 class="mb-0">Song requests from the public side</h3></div>
    <div class="d-flex gap-2 flex-wrap">
      <span class="ugfx-chip">All <?= (int)$counts['all'] ?></span>
      <span class="ugfx-chip ugfx-chip-blue">New <?= (int)$counts['new'] ?></span>
      <span class="ugfx-chip">Done <?= (int)$counts['done'] ?></span>
    </div>
  </div>
  <form method="get" class="row g-2 mb-3">
    <div class="col-md-3">
      <select class="form-select" name="status">
        <option value="all" <?= $statusFilter === 'all' ? 'selected' : '' ?>>All statuses</option>
        <option value="new" <?= $statusFilter === 'new' ? 'selected' : '' ?>>New</option>
        <option value="done" <?= $statusFilter === 'done' ? 'selected' : '' ?>>Done</option>
      </select>
    </div>
    <div class="col-md-6"><input class="form-control" type="search" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="Search requester, artist, song..."></div>
    <div class="col-md-3 d-flex gap-2">
      <button class="btn ugfx-btn-outline flex-fill">Filter</button>
      <a class="btn ugfx-btn-outline flex-fill" href="requests.php">Reset</a>
    </div>
  </form>
  <div class="d-flex justify-content-end mb-3">
    <form method="post" onsubmit="return confirm('Clear all done requests?');">
      <input type="hidden" name="action" value="clear_done">
      <button class="btn ugfx-btn-outline btn-sm">Clear done</button>
    </form>
  </div>
  <div class="table-responsive"><table class="table ugfx-table"><thead><tr><th>Name</th><th>Artist</th><th>Song</th><th>Status</th><th>Time</th><th>Actions</th></tr></thead><tbody>
  <?php foreach (array_reverse($items) as $item): $status = strtolower((string)($item['status'] ?? 'new')); ?>
    <tr>
      <td><?= htmlspecialchars((string)($item['name'] ?? '')) ?></td>
      <td><?= htmlspecialchars((string)($item['artist'] ?? '')) ?></td>
      <td><?= htmlspecialchars((string)($item['song'] ?? '')) ?></td>
      <td><span class="ugfx-chip <?= $status === 'new' ? 'ugfx-chip-blue' : '' ?>"><?= htmlspecialchars(ucfirst($status)) ?></span></td>
      <td><?= htmlspecialchars((string)($item['created_at'] ?? '')) ?></td>
      <td><div class="d-flex gap-2 flex-wrap"><form method="post"><input type="hidden" name="action" value="mark_status"><input type="hidden" name="id" value="<?= htmlspecialchars((string)$item['id']) ?>"><input type="hidden" name="status" value="new"><button class="btn ugfx-btn-outline btn-sm">Mark new</button></form><form method="post"><input type="hidden" name="action" value="mark_status"><input type="hidden" name="id" value="<?= htmlspecialchars((string)$item['id']) ?>"><input type="hidden" name="status" value="done"><button class="btn ugfx-btn-outline btn-sm">Mark done</button></form><form method="post" onsubmit="return confirm('Delete this request?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= htmlspecialchars((string)$item['id']) ?>"><button class="btn btn-outline-danger btn-sm">Delete</button></form></div></td>
    </tr>
  <?php endforeach; ?>
  <?php if (!$items): ?><tr><td colspan="6" class="text-center py-4"><div class="ugfx-admin-empty-state">No requests in the queue for this filter.</div></td></tr><?php endif; ?>
  </tbody></table></div>
</div>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>