<?php
declare(strict_types=1);
require_once __DIR__ . '/api/_util.php';

/**
 * edit.php — file-based editor for:
 * - Quest lists (quests/*.json arrays)
 * - Inventory items (inventory/*.json object containing items[])
 * - Champions (champions/*.json single object)
 * - world.json (single object)
 *
 * IMPORTANT: Protect this page later with .htaccess Basic Auth.
 */

date_default_timezone_set('Pacific/Auckland');

$targets = [
  // Quest arrays
  "quests:dailies" => ["label" => "Quests - Dailies", "path" => "quests/dailies.json", "type" => "array"],
  "quests:goals" => ["label" => "Quests - Goals/Bounties", "path" => "quests/goals.json", "type" => "array"],
  "quests:random_pool" => ["label" => "Quests - Random Pool", "path" => "quests/random_pool.json", "type" => "array"],

  // Inventory object w/ items[]
  "inv:supplements" => ["label" => "Inventory - Supplements", "path" => "inventory/supplements.json", "type" => "inventory"],
"inv:stash" => ["label" => "Inventory - Stash", "path" => "inventory/stash.json", "type" => "inventory"],
  "inv:wishlist" => ["label" => "Inventory - Wishlist", "path" => "inventory/wishlist.json", "type" => "inventory"],

  // Single objects
  "world" => ["label" => "World (world.json)", "path" => "world.json", "type" => "single"],

  "champ:mon" => ["label" => "Champion - Monday (mon.json)", "path" => "champions/mon.json", "type" => "single"],
  "champ:tue" => ["label" => "Champion - Tuesday (tue.json)", "path" => "champions/tue.json", "type" => "single"],
  "champ:wed" => ["label" => "Champion - Wednesday (wed.json)", "path" => "champions/wed.json", "type" => "single"],
  "champ:thu" => ["label" => "Champion - Thursday (thu.json)", "path" => "champions/thu.json", "type" => "single"],
  "champ:fri" => ["label" => "Champion - Friday (fri.json)", "path" => "champions/fri.json", "type" => "single"],
  "champ:sat" => ["label" => "Champion - Saturday (sat.json)", "path" => "champions/sat.json", "type" => "single"],
  "champ:sun" => ["label" => "Champion - Sunday (sun.json)", "path" => "champions/sun.json", "type" => "single"]
];

$targetKey = safe_string($_GET['target'] ?? 'quests:dailies');
if (!isset($targets[$targetKey])) $targetKey = "quests:dailies";

$target = $targets[$targetKey];
$path = data_path($target['path']);
$type = $target['type'];

$message = null;
$error = null;

$selectedId = safe_string($_GET['id'] ?? '');     // For array/inventory editing
$mode = safe_string($_GET['mode'] ?? 'edit');    // edit | new

function load_target_data(string $type, string $path) {
  $data = read_json($path);
  if ($data === null) {
    // Create default structures if missing
    if ($type === 'array') return [];
    if ($type === 'inventory') return ["category" => "", "grid" => ["cols"=>12,"rows"=>5], "items" => []];
    if ($type === 'single') return [];
  }
  return $data;
}

$data = load_target_data($type, $path);

function get_items_list(string $type, $data): array {
  if ($type === 'array') return is_array($data) ? $data : [];
  if ($type === 'inventory') {
    if (is_array($data) && isset($data['items']) && is_array($data['items'])) return $data['items'];
    return [];
  }
  return [];
}

function set_items_list(string $type, &$data, array $items): void {
  if ($type === 'array') {
    $data = $items;
    return;
  }
  if ($type === 'inventory') {
    if (!is_array($data)) $data = [];
    if (!isset($data['grid'])) $data['grid'] = ["cols"=>12,"rows"=>5];
    if (!isset($data['category'])) $data['category'] = "";
    $data['items'] = $items;
    return;
  }
}

function index_items_by_id(array $items): array {
  $out = [];
  foreach ($items as $i => $it) {
    $id = is_array($it) ? (string)($it['id'] ?? '') : '';
    if ($id !== '') $out[$id] = $i;
  }
  ksort($out);
  return $out;
}

// Handle POST (save/delete)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $postTarget = safe_string($_POST['target'] ?? '');
  if (!isset($targets[$postTarget])) {
    $error = "Invalid target selected.";
  } else {
    $targetKey = $postTarget;
    $target = $targets[$targetKey];
    $path = data_path($target['path']);
    $type = $target['type'];
    $data = load_target_data($type, $path);

    $action = safe_string($_POST['action'] ?? 'save');
    $jsonText = trim((string)($_POST['json'] ?? ''));

    $selectedId = safe_string($_POST['id'] ?? '');
    $mode = safe_string($_POST['mode'] ?? 'edit');

    if ($action === 'delete' && ($type === 'array' || $type === 'inventory')) {
      $items = get_items_list($type, $data);
      $map = index_items_by_id($items);

      if ($selectedId === '' || !isset($map[$selectedId])) {
        $error = "Select a valid ID to delete.";
      } else {
        $idx = $map[$selectedId];
        array_splice($items, $idx, 1);
        set_items_list($type, $data, $items);
        write_json_atomic($path, $data);
        $message = "Deleted item: {$selectedId}";
        $selectedId = '';
        $mode = 'edit';
      }
    }
    else if ($action === 'save') {
      $parsed = json_decode($jsonText, true);
      if ($parsed === null && json_last_error() !== JSON_ERROR_NONE) {
        $error = "Invalid JSON: " . json_last_error_msg();
      } else {
        // Save depending on target type
        if ($type === 'single') {
          // Save entire file as provided
          write_json_atomic($path, $parsed);
          $message = "Saved {$target['label']}";
        } else {
          // array/inventory: save by id (replace or add new)
          if (!is_array($parsed)) {
            $error = "For this target, JSON must be an object with an 'id' field.";
          } else {
            $id = (string)($parsed['id'] ?? '');
            if ($id === '') {
              $error = "Missing required field: id";
            } else {
              $items = get_items_list($type, $data);
              $map = index_items_by_id($items);

              if ($mode === 'new' || !isset($map[$id])) {
                // Add new (append)
                $items[] = $parsed;
                set_items_list($type, $data, $items);
                write_json_atomic($path, $data);
                $message = "Added new item: {$id}";
                $selectedId = $id;
                $mode = 'edit';
              } else {
                // Replace existing
                $idx = $map[$id];
                $items[$idx] = $parsed;
                set_items_list($type, $data, $items);
                write_json_atomic($path, $data);
                $message = "Updated item: {$id}";
                $selectedId = $id;
                $mode = 'edit';
              }
            }
          }
        }

        // Reload after save
        $data = load_target_data($type, $path);
      }
    }
  }
}

// Build UI content
$items = get_items_list($type, $data);
$idIndex = index_items_by_id($items);

// Determine textarea content
$textareaJson = "";
if ($type === 'single') {
  $textareaJson = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) ?: "{}";
} else {
  if ($mode === 'new') {
    // starter template for new item
    $template = ["id" => "new_id_here", "title" => "New Item", "xp" => 10, "gold" => 3];
    if ($type === 'inventory') {
      $template = ["id"=>"new_item_id","name"=>"New Item","qty"=>1,"unit"=>"each","icon"=>"/assets/inventory/new.png","w"=>1,"h"=>1];
    }
    $textareaJson = json_encode($template, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) ?: "{}";
  } else if ($selectedId !== '' && isset($idIndex[$selectedId])) {
    $idx = $idIndex[$selectedId];
    $textareaJson = json_encode($items[$idx], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) ?: "{}";
  } else {
    $textareaJson = "{\n  \"id\": \"\",\n  \"title\": \"\",\n  \"xp\": 0,\n  \"gold\": 0\n}\n";
    if ($type === 'inventory') {
      $textareaJson = "{\n  \"id\": \"\",\n  \"name\": \"\",\n  \"qty\": 1,\n  \"unit\": \"\",\n  \"icon\": \"\",\n  \"w\": 1,\n  \"h\": 1\n}\n";
    }
  }
}

?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Edit</title>
  /styles.css
  /themes.css
  <style>
    .editorGrid { display:grid; grid-template-columns: 320px 1fr; gap:14px; align-items:start; }
    .field { display:grid; gap:6px; margin-bottom:10px; }
    select, textarea, input { width:100%; padding:10px; border-radius:10px; border:1px solid #333; background:#0f0f0f; color:#eee; }
    textarea { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; min-height: 520px; }
    .row { display:flex; gap:10px; flex-wrap:wrap; }
    .btnDanger { border-color: #5a1a1a; background:#2a1010; }
    .muted { opacity:.8; }
    .pill { display:inline-block; padding:3px 8px; border:1px solid #333; border-radius:999px; margin-left:8px; font-size:12px; opacity:.9; }
  </style>
</head>
<body class="theme-default">
  <header class="top">
    /index.html← Back</a>
    <div class="logo">Editor <span class="pill"><?= h($targets[$targetKey]['label']) ?></span></div>
  </header>

  <main class="wrap">
    <section class="panel">
      <?php if ($message): ?><div class="muted">✅ <?= h($message) ?></div><?php endif; ?>
      <?php if ($error): ?><div class="muted" style="color:#ff7b7b;">❌ <?= h($error) ?></div><?php endif; ?>
    </section>

    <section class="panel editorGrid">
      <!-- Left: target + ID list -->
      <div>
        <form method="get" class="field">
          <label class="muted">Target</label>
          <select name="target" onchange="this.form.submit()">
            <?php foreach ($targets as $k => $t): ?>
              <option value="<?= h($k) ?>" <?= $k === $targetKey ? 'selected' : '' ?>>
                <?= h($t['label']) ?>
              </option>
            <?php endforeach; ?>
          </select>

          <?php if ($type !== 'single'): ?>
            <label class="muted">Item ID</label>
            <select name="id" onchange="this.form.submit()">
              <option value="">— Select —</option>
              <?php foreach ($idIndex as $id => $idx): ?>
                <option value="<?= h($id) ?>" <?= $id === $selectedId ? 'selected' : '' ?>>
                  <?= h($id) ?>
                </option>
              <?php endforeach; ?>
            </select>

            <input type="hidden" name="mode" value="edit">
            <div class="row" style="margin-top:10px;">
              <button class="btn" type="submit" name="mode" value="new">+ New</button>
              <button class="btn" type="submit" name="mode" value="edit">Edit</button>
            </div>
          <?php endif; ?>
        </form>

        <div class="muted" style="margin-top:12px;">
          <strong>Tip:</strong> For quests & inventory items, the JSON <code>id</code> is the key.
          If you change the <code>id</code> while editing, it’ll be treated as a new item.
        </div>
      </div>

      <!-- Right: JSON editor -->
      <div>
        <form method="post" class="field">
          <input type="hidden" name="target" value="<?= h($targetKey) ?>">
          <input type="hidden" name="id" value="<?= h($selectedId) ?>">
          <input type="hidden" name="mode" value="<?= h($mode) ?>">

          <label class="muted">JSON</label>
          <textarea name="json"><?= h($textareaJson) ?></textarea>

          <div class="row">
            <button class="btn" type="submit" name="action" value="save">Save</button>

            <?php if ($type !== 'single' && $selectedId !== '' && $mode !== 'new'): ?>
              <button class="btn btnDanger" type="submit" name="action" value="delete"
                      onclick="return confirm('Delete <?= h($selectedId) ?>?');">
                Delete
              </button>
            <?php endif; ?>
          </div>

          <div class="muted" style="margin-top:10px;">
            <strong>Milestones note:</strong> we’ll award milestone medals server-side (in <code>complete.php</code>) so it stays reliable.
          </div>
        </form>
      </div>
    </section>
  </main>
</body>
</html>