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

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

$path = __DIR__ . '/gallery.json';
$raw = file_get_contents($path);
$data = json_decode($raw, true);
if (!is_array($data) || !isset($data['items']) || !is_array($data['items'])) {
  $data = ['items' => []];
}

$new = [];
$deleted = false;
foreach ($data['items'] as $it) {
  if (!$deleted && is_array($it) && (($it['src'] ?? '') === $src)) {
    $deleted = true;
    continue;
  }
  $new[] = $it;
}
$data['items'] = $new;

// If it's in assets/uploads, delete file too
$root = realpath(__DIR__ . '/..');
$full = $root . '/' . $src;
$uploadsDir = realpath($root . '/assets/uploads');
if ($uploadsDir && strpos(realpath(dirname($full)) ?: '', $uploadsDir) === 0) {
  if (file_exists($full)) @unlink($full);
}

$tmpPath = $path . '.tmp';
$jsonOut = json_encode($data, 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, $path)) {
  @unlink($tmpPath);
  http_response_code(500);
  echo json_encode(['error' => 'Cannot replace gallery']);
  exit;
}

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