<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
header('Content-Type: application/json');

$uid = gp_current_user_id();
if ($uid <= 0) {
    echo json_encode(['ok' => false, 'error' => 'Not logged in']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$theme = $input['theme'] ?? 'system';

if (!in_array($theme, ['light', 'dark', 'system'], true)) {
    $theme = 'system';
}

try {
    $stmt = crm_pdo()->prepare("UPDATE users SET theme_preference = :theme WHERE id = :id");
    $stmt->execute([':theme' => $theme, ':id' => $uid]);
    $_SESSION['gp_theme_override'] = $theme;
    echo json_encode(['ok' => true]);
} catch (Throwable $e) {
    echo json_encode(['ok' => false, 'error' => 'DB error']);
}
