<?php
/**
 * check-subdomain.php — AJAX endpoint the signup form calls as the
 * customer types, so they find out a name is taken BEFORE submitting the
 * whole form, not after.
 */
require_once __DIR__ . '/../lib/StoreProvisioner.php';
require_once __DIR__ . '/../config/master-db.php'; // must return a connected PDO as $masterDb

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

$subdomain = trim($_GET['subdomain'] ?? '');
if ($subdomain === '') {
    echo json_encode(['available' => false, 'reason' => 'Enter a store address']);
    exit;
}

$clean = strtolower(preg_replace('/[^a-z0-9\-]/', '', $subdomain));
if (strlen($clean) < 3) {
    echo json_encode(['available' => false, 'reason' => 'Too short']);
    exit;
}

$reserved = $masterDb->prepare('SELECT 1 FROM reserved_subdomains WHERE subdomain = ?');
$reserved->execute([$clean]);
if ($reserved->fetchColumn()) {
    echo json_encode(['available' => false, 'reason' => 'That name is reserved']);
    exit;
}

$taken = $masterDb->prepare("SELECT 1 FROM stores WHERE subdomain = ? AND status != 'deleted'");
$taken->execute([$clean]);
if ($taken->fetchColumn()) {
    echo json_encode(['available' => false, 'reason' => 'Already taken']);
    exit;
}

echo json_encode(['available' => true]);
