<?php
session_start();
include '../../function/connect.php';

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

if (!isset($_POST['username'])) {
  echo json_encode(['available' => false]);
  exit;
}

$username = strtolower(trim($_POST['username']));

// validasi dasar
if (strlen($username) < 4) {
  echo json_encode(['available' => false]);
  exit;
}

$stmt = mysqli_prepare($koneksi, "SELECT id FROM tb_user WHERE username = ? LIMIT 1");
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);

$exists = mysqli_stmt_num_rows($stmt) > 0;
mysqli_stmt_close($stmt);

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