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


$dataFile = __DIR__ . '/../data/fans.json';
$fans = smurf_read_json($dataFile, []);
if (!is_array($fans)) $fans = [];

$action = $_GET['action'] ?? '';
$i = isset($_GET['i']) ? (int)$_GET['i'] : -1;
$edit = ($action === 'edit' && $i >= 0 && isset($fans[$i])) ? $fans[$i] : ['name'=>'','url'=>'','image'=>'','description'=>'','top_fan'=>0];

if ($action === 'delete' && $i >= 0) {
  if (!$CAN_EDIT) die('<h1>Access Denied</h1><p>You do not have permission to edit Fans.</p>');
  if (isset($fans[$i])) {
    array_splice($fans, $i, 1);
    smurf_write_json($dataFile, array_values($fans));
  }
  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 Fans.</p>');
  $mode = $_POST['mode'] ?? 'create';
  $editIndex = (int)($_POST['edit_index'] ?? -1);
  $name  = trim($_POST['name'] ?? '');
  $url   = trim($_POST['url'] ?? '');
  $image = trim($_POST['image'] ?? '');
  $desc  = trim($_POST['description'] ?? '');
  $topFan = isset($_POST['top_fan']) ? 1 : 0;
  if ($image === '') {
    $uploaded = smurf_handle_upload('image_file', __DIR__ . '/../img/friends');
    if ($uploaded !== '') $image = $uploaded;
  }
  if ($name !== '') {
    $row = ['name'=>$name,'url'=>$url,'link'=>$url,'image'=>$image,'description'=>$desc,'top_fan'=>$topFan];
    if ($mode === 'update' && isset($fans[$editIndex])) $fans[$editIndex] = $row;
    else $fans[] = $row;
    smurf_write_json($dataFile, array_values($fans));
    smurf_redirect_self(['saved'=>1], ['action','i']);
  }
}
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">⭐ Fans</h1>
  <p style="opacity:.8;">Front-end reads: <code>/data/fans.json</code> • Add a description and mark special supporters as Top Fans.</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 Fan' : 'Add Fan' ?></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>Website URL (optional)</label>
        <input class="input-field" name="url" placeholder="https://example.com" value="<?= smurf_h($edit['url'] ?? ($edit['link'] ?? '')) ?>" <?= $CAN_EDIT ? '' : 'disabled' ?>>

        <label>Description</label>
        <textarea class="input-field" name="description" rows="4" placeholder="Who they are, why they support the station, etc" <?= $CAN_EDIT ? '' : 'disabled' ?>><?= smurf_h($edit['description'] ?? '') ?></textarea>

        <label>Image Link (optional)</label>
        <input class="input-field" name="image" placeholder="https://example.com/photo.png" 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/fans/</code></small>
            </div>
          </div>
        </div>

        <label style="display:flex;gap:10px;align-items:center;margin-top:10px;">
          <input type="checkbox" name="top_fan" value="1" <?= !empty($edit['top_fan']) ? 'checked' : '' ?> <?= $CAN_EDIT ? '' : 'disabled' ?>>
          <span>Mark as Top Fan ⭐</span>
        </label>

        <?php if ($CAN_EDIT): ?>
          <button class="admin-btn primary" type="submit" style="margin-top:12px;"><?= ($action === 'edit') ? 'Save Fan' : 'Add Fan' ?></button>
          <?php if ($action === 'edit'): ?><a class="admin-btn" href="/admin/fans.php" style="margin-left:8px;">Cancel</a><?php endif; ?>
        <?php else: ?>
          <p style="opacity:.7;margin-top:10px;">View-only mode — editing disabled.</p>
        <?php endif; ?>
      </form>
    </section>

    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Current Fans</h3>
      <?php if (empty($fans)): ?>
        <p>No fans yet.</p>
      <?php else: foreach ($fans as $idx => $fr): ?>
        <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><?= !empty($fr['top_fan']) ? '⭐ ' : '' ?><?= smurf_h($fr['name'] ?? '') ?></strong>
            <div style="display:flex;gap:8px;">
              <a class="admin-btn" href="/admin/fans.php?action=edit&i=<?= $idx ?>">Edit</a>
              <?php if ($CAN_EDIT): ?><a class="admin-btn" href="/admin/fans.php?action=delete&i=<?= $idx ?>" onclick="return confirm('Delete this fan?');">Delete</a><?php endif; ?>
            </div>
          </div>
          <?php if (!empty($fr['description'])): ?><p style="margin:8px 0 0;opacity:.9;"><?= nl2br(smurf_h($fr['description'])) ?></p><?php endif; ?>
          <?php if (!empty($fr['url']) || !empty($fr['link'])): ?><p style="margin:8px 0 0;opacity:.9;"><strong>URL:</strong> <?= smurf_h($fr['url'] ?? ($fr['link'] ?? '')) ?></p><?php endif; ?>
          <?php if (!empty($fr['image'])): ?><p style="margin:4px 0 0;opacity:.9;"><strong>Image:</strong> <?= smurf_h($fr['image']) ?></p><?php endif; ?>
        </div>
      <?php endforeach; endif; ?>
    </section>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>