<?php
// check_username.php
require 'conn.php';

$q = $_GET['q'] ?? '';
$q = trim($q);
header('Content-Type: application/json');

if ($q === '') {
    echo json_encode(['available' => false, 'error' => 'empty']);
    exit;
}

// basic sanitize
$qclean = substr(preg_replace('/[^a-zA-Z0-9_\-]/', '', $q), 0, 32);

$stmt = mysqli_prepare($con, "SELECT id FROM ahli WHERE username = ? LIMIT 1");
mysqli_stmt_bind_param($stmt, "s", $qclean);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);
$exists = (bool) mysqli_fetch_assoc($res);
mysqli_stmt_close($stmt);

echo json_encode(['available' => !$exists]);
exit;
