<?php
/**
 * check_availability.php
 * AJAX endpoint — checks if username / email / phone is already taken.
 * Returns JSON: { "available": true|false, "message": "..." }
 *
 * Place this file in the same root directory as register.php
 */

require_once 'config/database.php';
require_once 'includes/functions.php';

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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$conn  = getConnection();
$field = trim($_POST['field'] ?? '');
$value = trim($_POST['value'] ?? '');

// Sanitize
$value = htmlspecialchars(strip_tags($value), ENT_QUOTES, 'UTF-8');

if ($field === '' || $value === '') {
    echo json_encode(['available' => null, 'message' => '']);
    exit;
}

switch ($field) {

    case 'username':
        // Local format checks first (no DB hit needed)
        if (strlen($value) < 3) {
            echo json_encode(['available' => false, 'message' => 'Too short (min 3 characters)']);
            exit;
        }
        if (strlen($value) > 30) {
            echo json_encode(['available' => false, 'message' => 'Too long (max 30 characters)']);
            exit;
        }
        if (!preg_match('/^[a-zA-Z0-9_]+$/', $value)) {
            echo json_encode(['available' => false, 'message' => 'Letters, numbers and underscores only']);
            exit;
        }
        if (preg_match('/^(none|admin|root|system|support|moderator|mod|superadmin)$/i', $value)) {
            echo json_encode(['available' => false, 'message' => 'This username is reserved']);
            exit;
        }
        $stmt = $conn->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
        $stmt->bind_param("s", $value);
        $stmt->execute();
        $taken = $stmt->get_result()->num_rows > 0;
        echo json_encode([
            'available' => !$taken,
            'message'   => $taken ? 'Username already taken' : 'Username is available',
        ]);
        break;

    case 'email':
        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
            echo json_encode(['available' => false, 'message' => 'Invalid email format']);
            exit;
        }
        $stmt = $conn->prepare("SELECT id FROM users WHERE email = ? LIMIT 1");
        $stmt->bind_param("s", $value);
        $stmt->execute();
        $taken = $stmt->get_result()->num_rows > 0;
        echo json_encode([
            'available' => !$taken,
            'message'   => $taken ? 'Email already registered' : 'Email is available',
        ]);
        break;

    case 'phone':
        $digits = preg_replace('/\D/', '', $value);
        if (strlen($digits) < 9 || strlen($digits) > 15) {
            echo json_encode(['available' => false, 'message' => 'Invalid phone number']);
            exit;
        }
        $stmt = $conn->prepare("SELECT id FROM users WHERE phone = ? LIMIT 1");
        $stmt->bind_param("s", $value);
        $stmt->execute();
        $taken = $stmt->get_result()->num_rows > 0;
        echo json_encode([
            'available' => !$taken,
            'message'   => $taken ? 'Phone number already registered' : 'Phone number is available',
        ]);
        break;

    default:
        http_response_code(400);
        echo json_encode(['error' => 'Unknown field']);
        break;
}
exit;