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

$allowedCats = ['dlazba','pvc','koberec'];
$cat = $_POST['cat'] ?? 'dlazba';
if (!in_array($cat, $allowedCats, true)) {
  http_response_code(400);
  echo json_encode(['error' => 'Invalid category']);
  exit;
}

$caption = trim($_POST['caption'] ?? '');
if ($caption === '') {
  // fallback caption
  $caption = ucfirst($cat);
}

if (!isset($_FILES['photo'])) {
  http_response_code(400);
  echo json_encode(['error' => 'No file uploaded']);
  exit;
}

$err = $_FILES['photo']['error'];
if ($err !== UPLOAD_ERR_OK) {
  http_response_code(400);
  echo json_encode(['error' => 'Upload error', 'code' => $err]);
  exit;
}

$tmp = $_FILES['photo']['tmp_name'];
$orig = $_FILES['photo']['name'] ?? 'photo';

$ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
$allowedExt = ['jpg','jpeg','png','webp'];
if (!in_array($ext, $allowedExt, true)) {
  http_response_code(400);
  echo json_encode(['error' => 'Unsupported file type']);
  exit;
}

$uploadsDir = realpath(__DIR__ . '/..') . '/assets/uploads';
if (!is_dir($uploadsDir)) {
  if (!mkdir($uploadsDir, 0755, true)) {
    http_response_code(500);
    echo json_encode(['error' => 'Cannot create uploads dir']);
    exit;
  }
}

$safeBase = preg_replace('/[^a-zA-Z0-9_-]+/', '-', pathinfo($orig, PATHINFO_FILENAME));
$safeBase = trim($safeBase, '-');
if ($safeBase === '') $safeBase = 'foto';

$filename = 'gallery-' . date('Ymd-His') . '-' . $safeBase . '.' . $ext;
$dest = $uploadsDir . '/' . $filename;

if (!move_uploaded_file($tmp, $dest)) {
  http_response_code(500);
  echo json_encode(['error' => 'Cannot save file']);
  exit;
}

$src = 'assets/uploads/' . $filename;

// Update gallery.json
$galleryPath = __DIR__ . '/gallery.json';
$data = ['items' => []];
if (file_exists($galleryPath)) {
  $raw = file_get_contents($galleryPath);
  $decoded = json_decode($raw, true);
  if (is_array($decoded) && isset($decoded['items']) && is_array($decoded['items'])) {
    $data = $decoded;
  }
}
array_unshift($data['items'], ['src' => $src, 'caption' => $caption, 'cat' => $cat]);

$tmpPath = $galleryPath . '.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 gallery temp']);
  exit;
}
if (!rename($tmpPath, $galleryPath)) {
  @unlink($tmpPath);
  http_response_code(500);
  echo json_encode(['error' => 'Cannot replace gallery file']);
  exit;
}

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