<?php require_once __DIR__ . '/includes/admin_bootstrap.php';
ugfx_require_permission('djs');
$items = ugfx_read_json($ugfx['storage']['djs'], []);
$message = '';
$editing = null;
$uploadRoot = dirname(__DIR__) . '/storage/uploads';
if (!is_dir($uploadRoot)) { @mkdir($uploadRoot, 0777, true); }
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save';
    if ($action === 'delete') {
        $id = (string)($_POST['id'] ?? '');
        $items = array_values(array_filter($items, fn($item) => (string)($item['id'] ?? '') !== $id));
        ugfx_write_json($ugfx['storage']['djs'], $items);
        $message = 'DJ removed.';
    } else {
        $id = trim((string)($_POST['id'] ?? '')) ?: (string)(time() . random_int(100,999));
        $existing = null;
        foreach ($items as $item) {
            if ((string)($item['id'] ?? '') === $id) { $existing = $item; break; }
        }
        $image = trim((string)($_POST['image_existing'] ?? ($existing['image'] ?? '')));
        if (!empty($_FILES['image_upload']['name'] ?? '') && is_uploaded_file($_FILES['image_upload']['tmp_name'] ?? '')) {
            $ext = strtolower(pathinfo((string)$_FILES['image_upload']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png','webp','gif'], true)) {
                $safeBase = preg_replace('/[^a-zA-Z0-9_-]+/', '-', trim((string)($_POST['name'] ?? 'dj')));
                $safeBase = trim($safeBase, '-') ?: 'dj';
                $filename = 'dj-' . date('YmdHis') . '-' . strtolower($safeBase) . '.' . $ext;
                $target = $uploadRoot . '/' . $filename;
                if (move_uploaded_file($_FILES['image_upload']['tmp_name'], $target)) {
                    $image = 'storage/uploads/' . $filename;
                }
            }
        }
        $entry = [
            'id' => $id,
            'name' => trim((string)($_POST['name'] ?? '')),
            'show' => trim((string)($_POST['show'] ?? '')),
            'image' => $image,
            'bio' => trim((string)($_POST['bio'] ?? '')),
            'sort_order' => (int)($_POST['sort_order'] ?? 0),
            'active' => isset($_POST['active']) ? 1 : 0,
        ];
        $updated = false;
        foreach ($items as &$item) {
            if ((string)($item['id'] ?? '') === $id) { $item = array_merge($item, $entry); $updated = true; break; }
        }
        unset($item);
        if (!$updated) $items[] = $entry;
        usort($items, fn($a,$b) => (($a['sort_order'] ?? 9999) <=> ($b['sort_order'] ?? 9999)) ?: strcmp((string)($a['name'] ?? ''), (string)($b['name'] ?? '')));
        ugfx_write_json($ugfx['storage']['djs'], array_values($items));
        $message = $updated ? 'DJ updated.' : 'DJ created.';
    }
    $items = ugfx_read_json($ugfx['storage']['djs'], []);
}
$items = array_map(function($item, $idx) {
    if (!isset($item['id']) || $item['id'] === '') { $item['id'] = (string)(time() + $idx) . random_int(100,999); }
    if (!isset($item['active'])) { $item['active'] = 1; }
    if (!isset($item['sort_order'])) { $item['sort_order'] = $idx + 1; }
    return $item;
}, $items, array_keys($items));
usort($items, fn($a,$b) => (($a['sort_order'] ?? 9999) <=> ($b['sort_order'] ?? 9999)) ?: strcmp((string)($a['name'] ?? ''), (string)($b['name'] ?? '')));
ugfx_write_json($ugfx['storage']['djs'], array_values($items));
$editId = (string)($_GET['edit'] ?? '');
foreach ($items as $item) { if ((string)($item['id'] ?? '') === $editId) { $editing = $item; break; } }
$adminTitle='DJs'; include __DIR__ . '/includes/admin_header.php'; ?>
<?php if ($message): ?><div class="ugfx-admin-alert"><?= htmlspecialchars($message) ?></div><?php endif; ?>
<div class="ugfx-admin-grid">
  <div class="ugfx-card p-4"><div class="ugfx-micro-label">TEAM EDITOR</div><h3><?= $editing ? 'Edit DJ / presenter' : 'Add DJ / presenter' ?></h3>
    <form method="post" class="ugfx-admin-form row g-3" enctype="multipart/form-data">
      <input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?= htmlspecialchars((string)($editing['id'] ?? '')) ?>">
      <input type="hidden" name="image_existing" value="<?= htmlspecialchars((string)($editing['image'] ?? '')) ?>">
      <div class="col-md-7"><input class="form-control" name="name" placeholder="DJ / presenter name" required value="<?= htmlspecialchars((string)($editing['name'] ?? '')) ?>"></div>
      <div class="col-md-5"><input class="form-control" type="number" name="sort_order" placeholder="Sort order" value="<?= (int)($editing['sort_order'] ?? (count($items)+1)) ?>"></div>
      <div class="col-12"><input class="form-control" name="show" placeholder="Show name" value="<?= htmlspecialchars((string)($editing['show'] ?? '')) ?>"></div>
      <div class="col-12"><input class="form-control" name="image_upload" type="file" accept=".jpg,.jpeg,.png,.webp,.gif"></div>
      <div class="col-12"><input class="form-control" name="image_existing" placeholder="Existing image path" value="<?= htmlspecialchars((string)($editing['image'] ?? '')) ?>"></div>
      <div class="col-12"><textarea class="form-control" name="bio" rows="8" placeholder="Bio"><?= htmlspecialchars((string)($editing['bio'] ?? '')) ?></textarea></div>
      <div class="col-md-6 d-flex align-items-center"><div class="form-check"><input class="form-check-input" type="checkbox" name="active" id="djActive" <?= !isset($editing['active']) || !empty($editing['active']) ? 'checked' : '' ?>><label class="form-check-label" for="djActive">Active on team page</label></div></div>
      <div class="col-12 d-flex gap-2 flex-wrap"><button class="btn ugfx-btn-primary">Save DJ</button><?php if ($editing): ?><a class="btn ugfx-btn-outline" href="djs.php">New DJ</a><?php endif; ?><a class="btn ugfx-btn-outline" href="../team.php" target="_blank" rel="noopener">View team page</a></div>
    </form>
  </div>
  <div class="ugfx-card p-4"><div class="ugfx-admin-toolbar"><div><div class="ugfx-micro-label">FRONT PAGE MATCH</div><h3 class="mb-0">Team / DJs from team.php</h3></div><span class="ugfx-chip"><?= count($items) ?> records</span></div>
    <div class="ugfx-admin-list"><?php foreach ($items as $item): ?><div class="ugfx-admin-item"><div class="d-flex gap-3 align-items-start"><?php if (!empty($item['image'])): ?><img src="../<?= htmlspecialchars(ltrim((string)$item['image'], '/')) ?>" alt="<?= htmlspecialchars((string)($item['name'] ?? 'DJ')) ?>" style="width:72px;height:72px;object-fit:cover;border-radius:18px;"><?php endif; ?><div class="flex-grow-1"><h4><?= htmlspecialchars((string)($item['name'] ?? 'DJ')) ?></h4><div class="ugfx-admin-meta"><span><?= htmlspecialchars((string)($item['show'] ?? '')) ?></span><span>Sort <?= (int)($item['sort_order'] ?? 0) ?></span><span><?= !empty($item['active']) ? 'Active' : 'Hidden' ?></span></div><div class="mt-2 text-secondary"><?= htmlspecialchars(ugfx_excerpt((string)($item['bio'] ?? ''), 180)) ?></div><div class="ugfx-admin-actions"><a class="btn ugfx-btn-outline btn-sm" href="djs.php?edit=<?= urlencode((string)($item['id'] ?? '')) ?>">Edit</a><form method="post" onsubmit="return confirm('Delete this DJ?');"><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></div></div></div><?php endforeach; ?><?php if (!$items): ?><div class="ugfx-admin-empty">No DJs yet.</div><?php endif; ?></div>
  </div>
</div>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
