<?php
// POST /api/settings/sync-timezone — keeps user_profiles.timezone (the one
// authoritative timezone every page reads via RenderHelpers.php's
// resolveUserTimezone()/userNow()/greetingWord()) current with wherever the
// trader is actually logged in from right now, not just whichever value was
// last picked in Settings. Called fire-and-forget from sidebar.php on page
// load with the browser's own live IANA zone
// (Intl.DateTimeFormat().resolvedOptions().timeZone — the real signal that
// changes automatically when the device's own timezone does, e.g. after
// travel). Still one single stored field, still the same Settings dropdown
// for a manual override — this only keeps that one field fresh, it never
// introduces a second timezone concept.
header('Content-Type: application/json');

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

$userId = $auth->requireAuth();

$input = json_decode(file_get_contents('php://input'), true) ?: [];
$detectedTimezone = trim((string)($input['timezone'] ?? ''));

// Same allow-list api/settings/update.php's profile section already
// validates against — a client-reported string is never trusted as-is.
if ($detectedTimezone === '' || !in_array($detectedTimezone, timezone_identifiers_list(), true)) {
    echo json_encode(['success' => false, 'error' => 'Invalid timezone']);
    exit;
}

try {
    $profile = $db->selectById('user_profiles', $userId, 'user_id');
    if ($profile && ($profile['timezone'] ?? null) !== $detectedTimezone) {
        $db->update('user_profiles', $userId, ['timezone' => $detectedTimezone], 'user_id');
    }
    echo json_encode(['success' => true, 'timezone' => $detectedTimezone]);
} catch (\Throwable $e) {
    error_log('sync-timezone: failed to update user_profiles.timezone: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Update failed']);
}
