<?php
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/db_tools.php';

require_login();

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

$pdo = db();
ensure_user_profile_columns($pdo);

$uid = (int)($_SESSION['user_id'] ?? 0);
$cid = (int)($_SESSION['company_id'] ?? 0);

$stmt = $pdo->prepare("SELECT theme_mode FROM users WHERE id=? AND company_id=? LIMIT 1");
$stmt->execute([$uid, $cid]);
$current = (string)($stmt->fetchColumn() ?: 'light');
$newMode = $current === 'dark' ? 'light' : 'dark';

$update = $pdo->prepare("UPDATE users SET theme_mode=? WHERE id=? AND company_id=?");
$update->execute([$newMode, $uid, $cid]);

$_SESSION['theme_mode'] = $newMode;

echo json_encode(['ok' => true, 'mode' => $newMode], JSON_UNESCAPED_UNICODE);
