<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$file         = __DIR__ . '/dispo_state.json';
$logFile      = __DIR__ . '/dispo_log.jsonl';
$snapshotFile = __DIR__ . '/dispo_state_snapshots.jsonl';
$backupFile   = __DIR__ . '/dispo_state_pre_edit.json';
$backupMeta   = __DIR__ . '/dispo_state_pre_edit_meta.json';

// ── Pre-Edit-Backup speichern ─────────────────────────────────────────────
if (isset($_GET['save_pre_edit'])) {
    if (file_exists($file)) {
        copy($file, $backupFile);
        $meta = ['ts' => date('c'), 'author' => $_GET['author'] ?? ''];
        file_put_contents($backupMeta, json_encode($meta, JSON_UNESCAPED_UNICODE));
        echo json_encode(['ok' => true, 'ts' => date('c')]);
    } else {
        echo json_encode(['ok' => false, 'error' => 'no state']);
    }
    exit;
}

// ── Pre-Edit-Backup info ───────────────────────────────────────────────────
if (isset($_GET['pre_edit_info'])) {
    if (file_exists($backupMeta)) {
        echo file_get_contents($backupMeta);
    } else {
        echo json_encode(['ts' => null]);
    }
    exit;
}

// ── Pre-Edit-Backup wiederherstellen ─────────────────────────────────────
if (isset($_GET['restore_pre_edit'])) {
    if (file_exists($backupFile)) {
        $state = file_get_contents($backupFile);
        file_put_contents($file, $state, LOCK_EX);
        $decoded = json_decode($state, true);
        $logEntry = json_encode([
            'ts' => date('c'), 'ts_ms' => null,
            'author' => $_GET['author'] ?? 'System',
            'action' => 'Wiederhergestellt: Eiserner Stand',
            'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
        ], JSON_UNESCAPED_UNICODE);
        file_put_contents($logFile, $logEntry . "\n", FILE_APPEND | LOCK_EX);
        $snapEntry = json_encode([
            'ts' => date('c'),
            'author' => $_GET['author'] ?? 'System',
            'action' => 'Wiederhergestellt: Eiserner Stand',
            'state' => $decoded,
        ], JSON_UNESCAPED_UNICODE);
        file_put_contents($snapshotFile, $snapEntry . "\n", FILE_APPEND | LOCK_EX);
        echo json_encode(['ok' => true, 'state' => $decoded]);
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'kein Backup vorhanden']);
    }
    exit;
}

// ── Log lesen ──────────────────────────────────────────────────────────────
if (isset($_GET['log'])) {
    $entries = [];
    if (file_exists($logFile)) {
        $lines = array_filter(explode("\n", trim(file_get_contents($logFile))));
        $lines = array_slice(array_values($lines), -30);
        foreach (array_reverse($lines) as $l) {
            $e = json_decode($l, true);
            if ($e) $entries[] = $e;
        }
    }
    echo json_encode($entries, JSON_UNESCAPED_UNICODE);
    exit;
}

// ── Speichern ──────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data    = file_get_contents('php://input');
    $decoded = json_decode($data, true);
    if ($decoded !== null) {
        file_put_contents($file, $data);
        $logEntry = json_encode([
            'ts'     => date('c'),
            'ts_ms'  => isset($decoded['ts']) ? $decoded['ts'] : null,
            'author' => isset($decoded['author']) ? $decoded['author'] : '',
            'action' => isset($decoded['action']) ? $decoded['action'] : '',
            'ip'     => $_SERVER['REMOTE_ADDR'] ?? '',
        ], JSON_UNESCAPED_UNICODE);
        file_put_contents($logFile, $logEntry . "\n", FILE_APPEND | LOCK_EX);
        // Vollständiger State-Snapshot für manuelles Restore
        $snapEntry = json_encode([
            'ts'     => date('c'),
            'author' => isset($decoded['author']) ? $decoded['author'] : '',
            'action' => isset($decoded['action']) ? $decoded['action'] : '',
            'state'  => $decoded,
        ], JSON_UNESCAPED_UNICODE);
        file_put_contents($snapshotFile, $snapEntry . "\n", FILE_APPEND | LOCK_EX);
        echo json_encode(['ok' => true, 'ts' => time()]);
    } else {
        http_response_code(400);
        echo json_encode(['error' => 'invalid JSON']);
    }
    exit;
}

// ── Laden ──────────────────────────────────────────────────────────────────
if (file_exists($file)) {
    echo file_get_contents($file);
} else {
    echo json_encode(['slots' => []]);
}
