<?php

declare(strict_types=1);

header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store');

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_register.php';

if (fate_public_registration_disabled()) {
    echo json_encode(['ok' => false, 'message' => '站方已暫停開放註冊。'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (!fate_admin_member_auth_ready()) {
    echo json_encode(['ok' => false, 'message' => '會員功能尚未設定完成。'], JSON_UNESCAPED_UNICODE);
    exit;
}

$field = isset($_REQUEST['field']) && is_string($_REQUEST['field']) ? $_REQUEST['field'] : '';
$value = isset($_REQUEST['value']) && is_string($_REQUEST['value']) ? $_REQUEST['value'] : '';

if (strlen($value) > 512) {
    echo json_encode(['ok' => false, 'message' => '輸入過長。'], JSON_UNESCAPED_UNICODE);
    exit;
}

$pdo = null;
try {
    require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'pdo.php';
    if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
        $pdo = $GLOBALS['pdo'];
    }
} catch (Throwable) {
    echo json_encode(['ok' => false, 'message' => '無法連線資料庫。'], JSON_UNESCAPED_UNICODE);
    exit;
}

if (!$pdo instanceof PDO) {
    echo json_encode(['ok' => false, 'message' => '無法連線資料庫。'], JSON_UNESCAPED_UNICODE);
    exit;
}

$GLOBALS['fate_member_table_columns_reload'] = true;
$result = fate_register_check_field_availability($pdo, $field, $value);
echo json_encode($result, JSON_UNESCAPED_UNICODE);
