<?php
// prefs.php — shared cross-device viewer preferences for the Odeon pages.
//
//   GET  -> returns the stored prefs JSON, or {} if nothing saved yet
//   POST -> overwrites the stored prefs with the posted JSON body
//
// Single-user store: there is no login, so every device shares one prefs file.
// Last write wins, which is the right behaviour for one person on a phone and a
// desktop. Written to data/prefs.json (that dir is www-data writable).
//
// Created: 20:25 - 16 Aug 2026 -- so slot selections follow Steve between devices,
//   and so /odeon/bills/ can read the SAME live selection the main page is showing
//   (it previously read a localStorage key the main page stopped writing on 30 Jul).

header('Content-Type: application/json');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

$path = __DIR__ . '/data/prefs.json';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (!file_exists($path)) {
        echo '{}';
        exit;
    }
    $raw = file_get_contents($path);
    echo ($raw === false || $raw === '') ? '{}' : $raw;
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $raw = file_get_contents('php://input');
    if (!$raw) {
        echo json_encode(['ok' => false, 'error' => 'Empty body']);
        exit;
    }

    // Size cap. Without it this is an anonymous write primitive against the
    // disk — repeated large POSTs would fill the partition and take down every
    // site on the VPS, not just this one. Real payloads are ~2KB.
    if (strlen($raw) > 65536) {
        echo json_encode(['ok' => false, 'error' => 'Too large']);
        exit;
    }

    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        echo json_encode(['ok' => false, 'error' => 'Invalid JSON']);
        exit;
    }

    // Shape check — anything without 'slots' is not a prefs payload.
    if (!isset($decoded['slots'])) {
        echo json_encode(['ok' => false, 'error' => 'Bad shape']);
        exit;
    }

    // Server-stamped so clients can tell how fresh the stored state is.
    $decoded['saved'] = date('Y-m-d H:i:s');

    // Write via a temp file + rename so a half-written file can never be read.
    $tmp = $path . '.tmp';
    if (file_put_contents($tmp, json_encode($decoded)) === false || !rename($tmp, $path)) {
        echo json_encode(['ok' => false, 'error' => 'Could not write file — check permissions']);
        exit;
    }

    echo json_encode(['ok' => true, 'saved' => $decoded['saved']]);
    exit;
}

echo json_encode(['ok' => false, 'error' => 'GET or POST only']);
