<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method_not_allowed']);
    return;
}

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'unauthorized']);
    return;
}

$preference = (string)($_POST['preference'] ?? '');
if (!in_array($preference, ['disabled', 'prompt', 'enabled'], true)) {
    http_response_code(422);
    echo json_encode(['ok' => false, 'error' => 'invalid_preference']);
    return;
}

try {
    $pdo = app()->pdo();
    if (!$pdo) {
        throw new RuntimeException('db_unavailable');
    }

    $settings = new \App\ProfileSettings($pdo);
    $settings->updateLocationTrackingPreference((int)$_SESSION['user_id'], $preference);

    echo json_encode(['ok' => true, 'preference' => $preference]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'save_failed']);
}
