<?php
require_once __DIR__ . '/../includes/redirect_helper.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) : [];

// Handle edits
foreach ($_POST as $key => $value) {
  if (strpos($key, 'save_') === 0) {
    $id = (int)substr($key, 5);
    if (isset($friends[$id])) {
      $name = $_POST["name_$id"];
      $description = $_POST["description_$id"];
      $url = $_POST["url_$id"] ?? $friends[$id]['url'] ?? '';
      $image = $friends[$id]['image'] ?? '';

      // Handle image upload
      if (!empty($_FILES["image_$id"]['name'])) {
        $slug = strtolower(preg_replace('/[^a-z0-9]+/', '_', $name));
        $ext = pathinfo($_FILES["image_$id"]['name'], PATHINFO_EXTENSION);
        $target = __DIR__ . "/../assets/friends/$slug.$ext";
        move_uploaded_file($_FILES["image_$id"]['tmp_name'], $target);
        $image = "/assets/friends/$slug.$ext";
      } elseif (!empty($_POST["image_url_$id"])) {
        $image = $_POST["image_url_$id"];
      }

      $friends[$id] = [
        'name' => $name,
        'description' => $description,
        'url' => $url,
        'image' => $image
      ];
    }
  }
}

// Handle new friend
if (isset($_POST['add_new'])) {
  $name = trim($_POST['new_name']);
  $description = trim($_POST['new_description']);
  $url = $_POST['new_url'] ?? '';
  $image = '';

  if (!empty($_FILES['new_image']['name'])) {
    $slug = strtolower(preg_replace('/[^a-z0-9]+/', '_', $name));
    $ext = pathinfo($_FILES['new_image']['name'], PATHINFO_EXTENSION);
    $target = __DIR__ . "/../assets/friends/$slug.$ext";
    move_uploaded_file($_FILES['new_image']['tmp_name'], $target);
    $image = "/assets/friends/$slug.$ext";
  } elseif (!empty($_POST['new_image_url'])) {
    $image = $_POST['new_image_url'];
  }

  $friends[] = [
    'name' => $name,
    'description' => $description,
    'url' => $url,
    'image' => $image
  ];
}

// Save back to JSON
file_put_contents($friends_file, json_encode(array_values($friends), JSON_PRETTY_PRINT));
ah_redirect_back('/admin/friends.php', ['saved' => 1]);
?>
