<?php
require_once __DIR__ . '/lib.php';
arrow_require_login();

$file    = arrow_data_path('gallery.json');
$gallery = arrow_read_json($file, []);
$notice  = '';

$action = $_POST['_action'] ?? '';
if ($action && $action !== 'login') {
    arrow_csrf_check();
}

if ($action === 'upload') {
    $img = arrow_handle_image_upload('image');
    if ($img === null) {
        $notice = 'Upload rejected — must be a JPG, PNG, WEBP or GIF under 8MB.';
    } else {
        $img['id']      = 'g-' . uniqid();
        $img['caption'] = trim($_POST['caption'] ?? '');
        $gallery[] = $img;
        $notice = arrow_write_json($file, $gallery) ? 'Image added.' : 'Write failed (check data/ permissions).';
    }
} elseif ($action === 'delete') {
    $id = $_POST['id'] ?? '';
    foreach ($gallery as $g) {
        if (($g['id'] ?? '') === $id && !empty($g['src'])) {
            $p = __DIR__ . '/' . $g['src'];
            // only remove files we manage, inside assets/img/
            if (strpos(realpath($p) ?: '', realpath(arrow_img_dir())) === 0) { @unlink($p); }
        }
    }
    $gallery = array_values(array_filter($gallery, function ($g) use ($id) { return ($g['id'] ?? '') !== $id; }));
    $notice = arrow_write_json($file, $gallery) ? 'Deleted.' : 'Write failed.';
} elseif ($action === 'reorder') {
    $order = $_POST['order'] ?? [];
    if (is_array($order) && $order) {
        $byId = [];
        foreach ($gallery as $g) { $byId[$g['id'] ?? ''] = $g; }
        $new = [];
        foreach ($order as $id) { if (isset($byId[$id])) { $new[] = $byId[$id]; unset($byId[$id]); } }
        foreach ($byId as $g) { $new[] = $g; } // any stragglers
        $gallery = $new;
        $notice = arrow_write_json($file, $gallery) ? 'Order saved.' : 'Write failed.';
    }
} elseif ($action === 'caption') {
    $id = $_POST['id'] ?? '';
    foreach ($gallery as $i => $g) {
        if (($g['id'] ?? '') === $id) { $gallery[$i]['caption'] = trim($_POST['caption'] ?? ''); }
    }
    $notice = arrow_write_json($file, $gallery) ? 'Caption saved.' : 'Write failed.';
}

$csrf = arrow_csrf_token();
function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Manage Gallery — Arrow Admin</title>
<style>
 :root{--teal:#0F4C5C;--amber:#D68910;--ink:#1C2326;--bg:#F7F4EE;--border:#E2DED5}
 *{box-sizing:border-box}body{font-family:system-ui,sans-serif;margin:0;background:var(--bg);color:var(--ink)}
 header{background:var(--teal);color:#fff;padding:16px 24px;display:flex;justify-content:space-between;align-items:center}
 header a{color:#fff}main{max-width:900px;margin:0 auto;padding:24px}
 .notice{background:#e7f5e9;border:1px solid #b6e0bf;padding:10px 14px;border-radius:6px;margin-bottom:16px}
 form.card{background:#fff;border:1px solid var(--border);border-radius:8px;padding:20px;margin-bottom:28px}
 label{display:block;font-weight:600;margin:12px 0 4px;font-size:.9rem}
 input,textarea{width:100%;padding:10px;border:1px solid #ccc;border-radius:6px;font:inherit}
 button{padding:9px 16px;border:0;border-radius:6px;font-weight:700;cursor:pointer}
 .btn{background:var(--amber);color:var(--ink)}.btn-del{background:#c0392b;color:#fff}
 .btn-sm{padding:5px 10px;font-size:.82rem}
 .tiles{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:16px}
 .tile{background:#fff;border:1px solid var(--border);border-radius:8px;overflow:hidden;display:flex;flex-direction:column}
 .tile img{width:100%;aspect-ratio:4/3;object-fit:cover;background:#ddd}
 .tile .body{padding:10px;display:flex;flex-direction:column;gap:8px}
 .tile.dragover{outline:3px dashed var(--amber)}
 .move{cursor:grab;color:#888;font-size:.8rem;user-select:none}
 .cap{font-size:.85rem;padding:6px;border:1px solid #ddd;border-radius:5px;width:100%}
</style></head><body>
<header>
  <strong>Arrow · Manage Gallery</strong>
  <span><a href="index.html">View site</a> &nbsp;·&nbsp; <a href="?logout=1">Sign out</a></span>
</header>
<main>
  <?php if ($notice): ?><div class="notice"><?= h($notice) ?></div><?php endif; ?>

  <form class="card" method="post" enctype="multipart/form-data">
    <h2 style="margin:0 0 4px">Add a photo</h2>
    <input type="hidden" name="_csrf" value="<?= h($csrf) ?>">
    <input type="hidden" name="_action" value="upload">
    <label>Image file (JPG, PNG, WEBP, GIF — max 8MB)</label>
    <input type="file" name="image" accept="image/*" required>
    <label>Caption (optional)</label>
    <input name="caption" placeholder="Deck restoration, May 2026">
    <p style="margin-top:16px"><button class="btn" type="submit">Upload</button></p>
  </form>

  <h2>Photos (<?= count($gallery) ?>) — drag the ☰ handle to reorder</h2>
  <form method="post" id="reorderForm">
    <input type="hidden" name="_csrf" value="<?= h($csrf) ?>">
    <input type="hidden" name="_action" value="reorder">
    <div class="tiles" id="tiles">
      <?php foreach ($gallery as $g): ?>
        <div class="tile" draggable="true" data-id="<?= h($g['id'] ?? '') ?>">
          <img src="<?= h($g['src'] ?? '') ?>" alt="<?= h($g['caption'] ?? '') ?>">
          <div class="body">
            <span class="move">☰ drag to reorder</span>
            <form method="post" style="display:flex;gap:6px">
              <input type="hidden" name="_csrf" value="<?= h($csrf) ?>">
              <input type="hidden" name="_action" value="caption">
              <input type="hidden" name="id" value="<?= h($g['id'] ?? '') ?>">
              <input class="cap" name="caption" value="<?= h($g['caption'] ?? '') ?>" placeholder="Caption">
              <button class="btn btn-sm" type="submit">Save</button>
            </form>
            <form method="post" onsubmit="return confirm('Delete this photo?')">
              <input type="hidden" name="_csrf" value="<?= h($csrf) ?>">
              <input type="hidden" name="_action" value="delete">
              <input type="hidden" name="id" value="<?= h($g['id'] ?? '') ?>">
              <button class="btn-del btn-sm" type="submit">Delete</button>
            </form>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
    <p style="margin-top:16px"><button class="btn" type="submit" id="saveOrder" disabled>Save new order</button></p>
  </form>

<script>
(function(){
  var tiles=document.getElementById('tiles'), form=document.getElementById('reorderForm'),
      saveBtn=document.getElementById('saveOrder'), dragged=null;
  if(!tiles)return;
  tiles.querySelectorAll('.tile').forEach(function(t){
    t.addEventListener('dragstart',function(){dragged=t;});
    t.addEventListener('dragover',function(e){e.preventDefault();t.classList.add('dragover');});
    t.addEventListener('dragleave',function(){t.classList.remove('dragover');});
    t.addEventListener('drop',function(e){
      e.preventDefault();t.classList.remove('dragover');
      if(dragged&&dragged!==t){tiles.insertBefore(dragged,t);saveBtn.disabled=false;}
    });
  });
  form.addEventListener('submit',function(){
    tiles.querySelectorAll('.tile').forEach(function(t){
      var i=document.createElement('input');i.type='hidden';i.name='order[]';i.value=t.dataset.id;form.appendChild(i);
    });
  });
})();
</script>
</main></body></html>
