<?php
ob_start();
try { require_once __DIR__ . '/../../includes/auth.php'; } catch(Throwable $e) { ob_end_clean(); header('Content-Type: application/json'); echo json_encode(['success'=>false,'error'=>'Server error']); exit; }
ob_end_clean();
header('Content-Type: application/json');

if (!isLoggedIn()) { echo json_encode(['success'=>false,'error'=>'Not authenticated']); exit; }

$action  = $_GET['action'] ?? '';
$userId  = $_SESSION['user_id'];
$isAdmin = !empty($_SESSION['is_admin']);

switch ($action) {

    // ── Get all aliases for a user ────────────────────────
    case 'get':
        $uid = $isAdmin ? (int)($_GET['user_id'] ?? $userId) : $userId;
        $stmt = db()->prepare("SELECT platform_slug, alias FROM game_aliases WHERE user_id=?");
        $stmt->execute([$uid]);
        $rows = $stmt->fetchAll();
        $map  = [];
        foreach ($rows as $r) $map[$r['platform_slug']] = $r['alias'];
        echo json_encode(['success'=>true, 'aliases'=>$map]);
        break;

    // ── Save a single alias ───────────────────────────────
    case 'save':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false]); exit; }
        $data  = json_decode(file_get_contents('php://input'), true);
        $uid   = $isAdmin && isset($data['user_id']) ? (int)$data['user_id'] : $userId;
        $slug  = preg_replace('/[^a-z0-9_]/', '', strtolower(trim($data['platform_slug'] ?? '')));
        $alias = substr(trim($data['alias'] ?? ''), 0, 100);
        if (!$slug) { echo json_encode(['success'=>false,'error'=>'Platform slug required']); exit; }
        if ($alias === '') {
            // Empty alias = delete it
            db()->prepare("DELETE FROM game_aliases WHERE user_id=? AND platform_slug=?")->execute([$uid,$slug]);
        } else {
            db()->prepare("INSERT INTO game_aliases (user_id,platform_slug,alias) VALUES (?,?,?)
                ON DUPLICATE KEY UPDATE alias=VALUES(alias)")->execute([$uid,$slug,$alias]);
        }
        echo json_encode(['success'=>true]);
        break;

    // ── Save all aliases at once (bulk) ───────────────────
    case 'save_all':
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success'=>false]); exit; }
        $data    = json_decode(file_get_contents('php://input'), true);
        $uid     = $isAdmin && isset($data['user_id']) ? (int)$data['user_id'] : $userId;
        $aliases = $data['aliases'] ?? [];
        $stmt    = db()->prepare("INSERT INTO game_aliases (user_id,platform_slug,alias) VALUES (?,?,?)
            ON DUPLICATE KEY UPDATE alias=VALUES(alias)");
        $del     = db()->prepare("DELETE FROM game_aliases WHERE user_id=? AND platform_slug=?");
        foreach ($aliases as $slug => $alias) {
            $slug  = preg_replace('/[^a-z0-9_]/', '', strtolower(trim($slug)));
            $alias = substr(trim($alias), 0, 100);
            if (!$slug) continue;
            if ($alias === '') $del->execute([$uid, $slug]);
            else $stmt->execute([$uid, $slug, $alias]);
        }
        echo json_encode(['success'=>true]);
        break;

    default:
        echo json_encode(['success'=>false,'error'=>'Unknown action']);
}
