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

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

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

if (!in_array($lang, ['el','en'], true)) {
    echo json_encode(['ok'=>false,'error'=>'Invalid language']); exit;
}

$user = auth_user();
if (!$user || ($user['id'] ?? 0) <= 0) {
    echo json_encode(['ok'=>false,'error'=>'Not authenticated']); exit;
}

try {
    $pdo->prepare("UPDATE users SET lang_preference = ? WHERE id = ?")
        ->execute([$lang, (int)$user['id']]);
    if (session_status() !== PHP_SESSION_ACTIVE) session_start();
    $_SESSION['gp_lang'] = $lang;
    echo json_encode(['ok'=>true]);
} catch (Throwable $e) {
    echo json_encode(['ok'=>false,'error'=>'DB error']);
}
