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


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

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

if ($action === 'delete' && $i >= 0) {
  if (!$CAN_EDIT) die('<h1>Access Denied</h1><p>You do not have permission to edit Friends.</p>');
  if (isset($friends[$i])) {
    array_splice($friends, $i, 1);
    smurf_write_json($dataFile, array_values($friends));
  }
  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 Friends.</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'] ?? '');
  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];
    if ($mode === 'update' && isset($friends[$editIndex])) $friends[$editIndex] = $row;
    else $friends[] = $row;
    smurf_write_json($dataFile, array_values($friends));
    smurf_redirect_self(['saved'=>1], ['action','i']);
  }
}
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <h1 class="admin-title">🤝 Friends</h1>
  <p style="opacity:.8;">Front-end reads: <code>/data/friends.json</code> • Use an image link OR upload a file.</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 Friend' : 'Add Friend' ?></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</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" <?= $CAN_EDIT ? '' : 'disabled' ?>><?= smurf_h($edit['description'] ?? '') ?></textarea>

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

        <?php if ($CAN_EDIT): ?>
          <button class="admin-btn primary" type="submit" style="margin-top:12px;"><?= ($action === 'edit') ? 'Save Friend' : 'Add Friend' ?></button>
          <?php if ($action === 'edit'): ?><a class="admin-btn" href="friends.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 Friends</h3>
      <?php if (empty($friends)): ?>
        <p>No friends yet.</p>
      <?php else: ?>
        <div class="friends-grid">
          <?php foreach ($friends as $idx => $fr): ?>
            <?php $imgSrc = smurf_image_src((string)($fr['image'] ?? ''), 'img/friends'); ?>
            <div class="content-card friend-card" 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">
                  <h3 class="friend-name"><?= 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="friends.php?action=edit&i=<?= $idx ?>">Edit</a>
                <?php if ($CAN_EDIT): ?><a class="admin-btn" href="friends.php?action=delete&i=<?= $idx ?>" onclick="return confirm('Delete this friend?');">Delete</a><?php endif; ?>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </section>
  </div>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>