<?php
require_once __DIR__ . '/../auth_middleware.php'; // JWT kontrolü
require_once '/home/akgbilis/fi_sf/config.php';

header('Content-Type: application/json');

$userId = $decoded->sub;
$data = json_decode(file_get_contents("php://input"), true);
$newNickname = trim($data['new_nickname'] ?? '');

// 🔒 Boş kontrolü
if (!$newNickname) {
    echo json_encode([
        "success" => false,
        "message" => "Nickname is required."
    ]);
    exit;
}

// 🔒 Aynı nickname başka biri tarafından alınmış mı?
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE nickname = ? AND id != ?");
$stmt->execute([$newNickname, $userId]);
$exists = $stmt->fetchColumn();

if ($exists > 0) {
    echo json_encode([
        "success" => false,
        "message" => "This nickname is already taken."
    ]);
    exit;
}

// 🔧 Güncelle
$stmt = $pdo->prepare("UPDATE users SET nickname = ? WHERE id = ?");
$success = $stmt->execute([$newNickname, $userId]);

echo json_encode([
    "success" => $success,
    "message" => $success ? "Nickname updated successfully." : "Update failed."
]);