<?php
declare(strict_types=1);
require __DIR__ . '/../lib/bootstrap.php';
handle_cors_preflight();
require_method(['POST']);
rate_limit('device-sync', 120, 60);

$input = input_json();
$device = authenticate_device($input);
$action = strtolower(trim((string) ($input['action'] ?? 'get')));
$allowedKeys = ['settings', 'favorites', 'progress', 'locks'];

if ($action === 'get_all') {
    $stmt = db()->prepare('SELECT data_key, payload, updated_at FROM device_data WHERE device_id = ?');
    $stmt->execute([(int) $device['id']]);
    $data = [];
    foreach ($stmt->fetchAll() as $row) {
        $data[$row['data_key']] = ['payload' => json_decode($row['payload'], true), 'updated_at' => $row['updated_at']];
    }
    json_response(['ok' => true, 'data' => $data]);
}

$key = strtolower(trim((string) ($input['key'] ?? '')));
if (!in_array($key, $allowedKeys, true)) {
    json_response(['ok' => false, 'error' => 'Invalid sync key'], 422);
}

if ($action === 'set') {
    $payload = json_encode($input['payload'] ?? null, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if ($payload === false || strlen($payload) > 262144) {
        json_response(['ok' => false, 'error' => 'Sync payload is too large'], 422);
    }
    db()->prepare(
        'INSERT INTO device_data (device_id, data_key, payload) VALUES (?, ?, ?)
         ON DUPLICATE KEY UPDATE payload = VALUES(payload), updated_at = NOW()'
    )->execute([(int) $device['id'], $key, $payload]);
    json_response(['ok' => true, 'updated_at' => gmdate('c')]);
}

$stmt = db()->prepare('SELECT payload, updated_at FROM device_data WHERE device_id = ? AND data_key = ? LIMIT 1');
$stmt->execute([(int) $device['id'], $key]);
$row = $stmt->fetch();
json_response(['ok' => true, 'payload' => $row ? json_decode($row['payload'], true) : null, 'updated_at' => $row['updated_at'] ?? null]);
