<?php
session_start();
$role = $_SESSION['role'] ?? 'guest';
if (!in_array($role, ['master','admin'])) {
  header('Location: /login/index.php');
  exit;
}

$friends_file = __DIR__ . '/../data/friends.json';
$friends = file_exists($friends_file) ? json_decode(file_get_contents($friends_file), true) : [];

include('../header.php');
include('../menu.php');
?>
<link rel="stylesheet" href="/css/style.css?v=1">

<main class="main-container">
  <section class="admin-card">
    <h2 class="text-warning">🤝 Manage Friends & Partners</h2>

    <form method="POST" enctype="multipart/form-data" action="save_friends.php" class="admin-form">
  <input type="hidden" name="return_to" value="<?= htmlspecialchars($_SERVER['REQUEST_URI'] ?? '/admin/friends.php') ?>">
      <?php foreach ($friends as $i => $friend): ?>
        <div class="admin-friend-card mb-4">
          <h4><?= htmlspecialchars($friend['name']) ?></h4>
          <textarea name="description_<?= $i ?>" class="admin-textarea mb-2"><?= htmlspecialchars($friend['description']) ?></textarea>

          <label class="form-label">Website URL</label>
          <input type="url" name="url_<?= $i ?>" class="admin-input mb-2" value="<?= htmlspecialchars($friend['url']) ?>">

          <label class="form-label">Replace Image</label>
          <input type="file" name="image_<?= $i ?>" class="admin-input mb-2">

          <label class="form-label">Or Image URL</label>
          <input type="url" name="image_url_<?= $i ?>" class="admin-input mb-2" value="<?= htmlspecialchars($friend['image']) ?>">

          <input type="hidden" name="name_<?= $i ?>" value="<?= htmlspecialchars($friend['name']) ?>">

          <button type="submit" name="save_<?= $i ?>" class="btn btn-warning btn-sm">💾 Save</button>
          <a href="delete_friend.php?delete=<?= $i ?>&return_to=<?= urlencode($_SERVER['REQUEST_URI'] ?? '/admin/friends.php') ?>" class="btn btn-danger btn-sm">🗑 Delete</a>
        </div>
      <?php endforeach; ?>

      <h3 class="text-warning mt-4">➕ Add New Friend</h3>
      <input type="text" name="new_name" class="admin-input mb-2" placeholder="Friend name" required>
      <textarea name="new_description" class="admin-textarea mb-2" placeholder="Description" required></textarea>

      <label class="form-label">Website URL</label>
      <input type="url" name="new_url" class="admin-input mb-2" placeholder="https://example.com">

      <label class="form-label">Upload Image</label>
      <input type="file" name="new_image" class="admin-input mb-2">

      <label class="form-label">Or Image URL</label>
      <input type="url" name="new_image_url" class="admin-input mb-2">

      <button type="submit" name="add_new" class="btn btn-dark">➕ Add Friend</button>
    </form>
  </section>
</main>

<?php include('../footer.php'); ?>
