<?php
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
require __DIR__ . '/config.php';

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

// Token check (ochrana proti náhodnému přepsání)
$token = $_POST['token'] ?? '';
if (!hash_equals(ADMIN_TOKEN, $token)) {
  http_response_code(403);
  echo json_encode(['error' => 'Forbidden']);
  exit;
}

$status = $_POST['status'] ?? '';
$text   = $_POST['text'] ?? '';

$allowed = ['available','limited','unavailable'];
if (!in_array($status, $allowed, true)) {
  http_response_code(400);
  echo json_encode(['error' => 'Invalid status']);
  exit;
}

$text = trim($text);
if ($text === '') {
  $text = 'Aktuálně přijímáme nové zakázky';
}

// Write JSON atomically
$data = json_encode(['status' => $status, 'text' => $text], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
$tmp = STATUS_FILE . '.tmp';

if (file_put_contents($tmp, $data) === false) {
  http_response_code(500);
  echo json_encode(['error' => 'Cannot write temp file']);
  exit;
}

if (!rename($tmp, STATUS_FILE)) {
  @unlink($tmp);
  http_response_code(500);
  echo json_encode(['error' => 'Cannot replace status file']);
  exit;
}

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