<?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;
}

$file = __DIR__ . '/../data/djs.txt';
$imageDir = __DIR__ . '/../assets/djs/';

// Load existing DJs
$entries = file_exists($file) ? explode("---\n", file_get_contents($file)) : [];
$djs = [];
foreach ($entries as $entry) {
  $lines = array_map('trim', explode("\n", trim($entry)));
  if (count($lines) >= 2) {
    $djs[] = $lines;
  }
}

// Handle edits
foreach ($_POST as $key => $value) {
  if (strpos($key, 'save_') === 0) {
    $id = (int)substr($key, 5);
    if (isset($djs[$id])) {
      $name = $_POST["name_$id"];
      $bio = $_POST["bio_$id"];
      $visibility = $_POST["visibility_$id"] ?? 'visible';

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

      $djs[$id] = [$name, $bio, $image, $visibility];
    }
  }
}

// Handle new DJ
if (isset($_POST['add_new'])) {
  $name = trim($_POST['new_name']);
  $bio = trim($_POST['new_bio']);
  $visibility = $_POST['new_visibility'] ?? 'visible';
  $image = '';

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

  $djs[] = [$name, $bio, $image, $visibility];
}

// Save back to file
$output = '';
foreach ($djs as $dj) {
  $output .= implode("\n", $dj) . "\n---\n";
}
file_put_contents($file, trim($output));

ah_redirect_back('/admin/djs.php', ['saved' => 1]);
?>
