<?php
session_start();
require __DIR__ . '/includes/admin_lib.php';


$dataFile = __DIR__ . '/../data/djs.json';
$legacyFile = __DIR__ . '/../data/djs.txt';
$djs = smurf_read_json($dataFile, []);
if (!is_array($djs)) $djs = [];
if (empty($djs) && file_exists($legacyFile)) {
  foreach (explode("---", (string)file_get_contents($legacyFile)) as $entry) {
    $lines = array_values(array_filter(array_map('trim', explode("\n", trim($entry))), fn($v) => $v !== ''));
    if (count($lines) < 2) continue;
    $djs[] = ['name'=>$lines[0], 'show'=>'', 'image'=>'', 'bio'=>trim(implode("\n", array_slice($lines, 1)))];
  }
  if (!empty($djs)) smurf_write_json($dataFile, array_values($djs));
}

$action = $_GET['action'] ?? '';
$i = isset($_GET['i']) ? (int)$_GET['i'] : -1;
$edit = ($action === 'edit' && $i >= 0 && isset($djs[$i])) ? $djs[$i] : ['name'=>'','show'=>'','image'=>'','bio'=>''];

if ($action === 'delete' && $i >= 0) {
  if (!$CAN_EDIT) die('<h1>Access Denied</h1><p>You do not have permission to edit DJs.</p>');
  if (isset($djs[$i])) {
    array_splice($djs, $i, 1);
    smurf_write_json($dataFile, array_values($djs));
  }
  smurf_redirect_self([], ['action','i']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) die('<h1>Access Denied</h1><p>You do not have permission to edit DJs.</p>');
  $mode = $_POST['mode'] ?? 'create';
  $editIndex = (int)($_POST['edit_index'] ?? -1);
  $name  = trim($_POST['name'] ?? '');
  $show  = trim($_POST['show'] ?? '');
  $image = trim($_POST['image'] ?? '');
  $bio   = trim($_POST['bio'] ?? '');
  if ($image === '') {
    $uploaded = smurf_handle_upload('image_file', __DIR__ . '/../img/djs');
    if ($uploaded !== '') $image = $uploaded;
  }
  if ($name !== '') {
    $row = ['name'=>$name,'show'=>$show,'image'=>$image,'bio'=>$bio];
    if ($mode === 'update' && isset($djs[$editIndex])) $djs[$editIndex] = $row;
    else $djs[] = $row;
    smurf_write_json($dataFile, array_values($djs));
    smurf_redirect_self(['saved'=>1], ['action','i']);
  }
}
$defaultImage = '/img/nav-icons/ourdjs.png';
$imageMap = [
  'smoke' => '/assets/djs/_gniting_the_irwaves_.jpg',
  'walfman' => '/assets/djs/_he_one_the_alfman_ack.jpg',
  'wolfman' => '/assets/djs/_he_one_the_alfman_ack.jpg',
  'jennah' => '/assets/djs/_murfette_usic_s_y_orever_.png',
];
$resolvePreview = function(array $dj) use ($defaultImage, $imageMap): string {
  $img = trim((string)($dj['image'] ?? ''));
  if ($img !== '') return preg_match('~^https?://~i', $img) ? $img : '/img/djs/' . ltrim($img, '/');
  $name = strtolower((string)($dj['name'] ?? ''));
  foreach ($imageMap as $needle => $path) if (strpos($name, $needle) !== false) return $path;
  return $defaultImage;
};
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">🎙️ DJs</h1>
  <p style="opacity:.8;">Front-end reads: <code>/data/djs.json</code> • Use an external image URL or upload to <code>/img/djs/</code>.</p>
  <?php if (!empty($_GET['saved'])): ?><div class="msg success">Saved.</div><?php endif; ?>

  <div class="admin-wrap stack" style="margin-top:10px;">
    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;"><?= ($action === 'edit') ? 'Edit DJ' : 'Add DJ' ?></h3>
      <form method="POST" enctype="multipart/form-data" class="form">
        <input type="hidden" name="mode" value="<?= ($action === 'edit') ? 'update' : 'create' ?>">
        <input type="hidden" name="edit_index" value="<?= (int)$i ?>">

        <label>Name</label>
        <input class="input-field" name="name" required value="<?= smurf_h($edit['name'] ?? '') ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>>

        <label>Show</label>
        <input class="input-field" name="show" value="<?= smurf_h($edit['show'] ?? '') ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>>

        <label>Image Link (optional)</label>
        <input class="input-field" name="image" placeholder="https://example.com/dj.jpg" value="<?= smurf_h($edit['image'] ?? '') ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>>

        <label>Or Upload Image File</label>
        <div class="request-wrapper admin-upload-wrap">
          <div class="request-box admin-upload-box">
            <div class="request-field">
              <label>Select image from your device</label>
              <input type="file" class="request-input admin-file-input" name="image_file" accept="image/*" <?= $CAN_EDIT ? '' : 'disabled' ?>>
              <small class="upload-help">Use the image link above OR choose a file here. If both are filled, the image link is used. Uploaded files save into <code>/img/djs/</code></small>
            </div>
          </div>
        </div>

        <label>Bio</label>
        <textarea class="input-field" name="bio" rows="6" <?= $CAN_EDIT ? '' : 'disabled' ?>><?= smurf_h($edit['bio'] ?? '') ?></textarea>

        <?php if ($CAN_EDIT): ?>
          <button class="admin-btn primary" type="submit" style="margin-top:12px;"><?= ($action === 'edit') ? 'Save DJ' : 'Add DJ' ?></button>
          <?php if ($action === 'edit'): ?><a class="admin-btn" href="/admin/djs.php" style="margin-left:8px;">Cancel</a><?php endif; ?>
        <?php endif; ?>
      </form>
    </section>

    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Current DJs</h3>
      <?php if (empty($djs)): ?><p>No DJs yet.</p><?php else: foreach ($djs as $idx => $dj): ?>
        <div class="content-card" style="text-align:left;">
          <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap;">
            <strong><?= smurf_h($dj['name'] ?? '') ?></strong>
            <div style="display:flex;gap:8px;">
              <a class="admin-btn" href="/admin/djs.php?action=edit&i=<?= $idx ?>">Edit</a>
              <?php if ($CAN_EDIT): ?><a class="admin-btn" href="/admin/djs.php?action=delete&i=<?= $idx ?>" onclick="return confirm('Delete this DJ?');">Delete</a><?php endif; ?>
            </div>
          </div>
          <?php if (!empty($dj['show'])): ?><p style="margin:8px 0 0;opacity:.9;"><strong>Show:</strong> <?= smurf_h($dj['show']) ?></p><?php endif; ?>
          <?php $previewImage = $resolvePreview($dj); ?>
          <div class="admin-entry-media" style="margin-top:10px;">
            <img src="<?= smurf_h($previewImage) ?>" alt="<?= smurf_h($dj['name'] ?? 'DJ') ?>" class="admin-entry-thumb">
          </div>
          <?php if (!empty($dj['image'])): ?><p style="margin:4px 0 0;opacity:.9;"><strong>Image:</strong> <?= smurf_h($dj['image']) ?></p><?php endif; ?>
          <?php if (!empty($dj['bio'])): ?><p style="margin:8px 0 0;white-space:pre-wrap;"><?= smurf_h($dj['bio']) ?></p><?php endif; ?>
        </div>
      <?php endforeach; endif; ?>
    </section>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>