<?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/friends/</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="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: ?>
        <div class="friends-grid">
          <?php foreach ($fans as $idx => $fr): ?>
            <?php $imgSrc = smurf_image_src((string)($fr['image'] ?? ''), 'img/friends'); ?>
            <div class="content-card friend-card fan-card stacked-profile-card <?= !empty($fr['top_fan']) ? 'top-fan' : '' ?>" style="text-align:left;">
              <div class="friend-top">
                <div class="friend-image">
                  <?php if ($imgSrc !== ''): ?>
                    <img src="<?= smurf_h($imgSrc) ?>" alt="<?= smurf_h($fr['name'] ?? '') ?>">
                  <?php else: ?>
                    <div class="friend-image-fallback">⭐</div>
                  <?php endif; ?>
                </div>
                <div class="friend-meta">
                  <?php if (!empty($fr['top_fan'])): ?><div class="top-fan-badge">⭐ Top Fan</div><?php endif; ?>
                  <h3 class="friend-name"><?= !empty($fr['top_fan']) ? '⭐ ' : '' ?><?= smurf_h($fr['name'] ?? '') ?></h3>
                  <?php if (!empty($fr['description'])): ?><p class="friend-desc"><?= nl2br(smurf_h($fr['description'])) ?></p><?php endif; ?>
                  <?php if (!empty($fr['url']) || !empty($fr['link'])): ?><p style="margin:10px 0 0;opacity:.9;"><strong>URL:</strong> <?= smurf_h($fr['url'] ?? ($fr['link'] ?? '')) ?></p><?php endif; ?>
                </div>
              </div>
              <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:12px;">
                <a class="admin-btn" href="fans.php?action=edit&i=<?= $idx ?>">Edit</a>
                <?php if ($CAN_EDIT): ?><a class="admin-btn" href="fans.php?action=delete&i=<?= $idx ?>" onclick="return confirm('Delete this fan?');">Delete</a><?php endif; ?>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </section>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>