<?php
header('Content-Type: application/json; charset=utf-8');
require __DIR__ . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  echo json_encode(['error' => 'Method not allowed']);
  exit;
}

$token = $_POST['token'] ?? '';
if (!hash_equals(ADMIN_TOKEN, $token)) {
  http_response_code(403);
  echo json_encode(['error' => 'Forbidden']);
  exit;
}

$itemsRaw = $_POST['items'] ?? '';
if ($itemsRaw === '') {
  http_response_code(400);
  echo json_encode(['error' => 'Missing items']);
  exit;
}

$decoded = json_decode($itemsRaw, true);
if (!is_array($decoded)) {
  http_response_code(400);
  echo json_encode(['error' => 'Invalid JSON']);
  exit;
}

$clean = [];
$allowedCats = ['dlazba','pvc','koberec'];
foreach ($decoded as $it) {
  if (!is_array($it)) continue;
  $src = trim((string)($it['src'] ?? ''));
  $caption = trim((string)($it['caption'] ?? ''));
  $cat = trim((string)($it['cat'] ?? 'dlazba'));
  if ($src === '') continue;
  if (!in_array($cat, $allowedCats, true)) $cat = 'dlazba';
  if ($caption === '') $caption = ucfirst($cat);
  $clean[] = ['src' => $src, 'caption' => $caption, 'cat' => $cat];
}

$tmpPath = __DIR__ . '/gallery.json.tmp';
$outPath = __DIR__ . '/gallery.json';
$jsonOut = json_encode(['items' => $clean], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

if (file_put_contents($tmpPath, $jsonOut) === false) {
  http_response_code(500);
  echo json_encode(['error' => 'Cannot write temp']);
  exit;
}
if (!rename($tmpPath, $outPath)) {
  @unlink($tmpPath);
  http_response_code(500);
  echo json_encode(['error' => 'Cannot replace gallery']);
  exit;
}

echo json_encode(['ok' => true, 'count' => count($clean)]);
?>