<?php
// Allow only your WordPress domain (recommended)
header('Access-Control-Allow-Origin: https://mygoldsdnbhd.com');
header('Vary: Origin');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// Always return JSON
header('Content-Type: application/json; charset=utf-8');
ini_set('display_errors', 0);
error_reporting(0);

function json_out($arr) {
    echo json_encode($arr);
    exit;
}

// 1) Buffer everything to prevent Connection.php echo from breaking JSON
ob_start();
require_once("../Header/Connection.php"); // adjust if needed
ob_end_clean(); // discard any echoed output like "<!--Connect start here-->"

// 2) Get input (support GET for browser testing + POST for AJAX)
$field = $_POST['field'] ?? ($_GET['field'] ?? '');
$value = $_POST['value'] ?? ($_GET['value'] ?? '');
$field = trim($field);
$value = trim($value);

if ($field === '' || $value === '') {
    json_out(['ok' => false, 'message' => 'Missing field/value']);
}

$allowed = ['email', 'nick_name'];
if (!in_array($field, $allowed, true)) {
    json_out(['ok' => false, 'message' => 'Invalid field']);
}

if ($field === 'email') {
    $value = strtolower($value);
}

// 3) Validate $mysqli exists
if (!isset($mysqli) || !($mysqli instanceof mysqli)) {
    json_out(['ok' => false, 'message' => 'DB connection not initialized']);
}

// 4) Query (prepared statement)
$sql = "SELECT 1 
        FROM user 
        WHERE $field = ? 
        AND Status = '1' 
        LIMIT 1";
$stmt = $mysqli->prepare($sql);
if (!$stmt) {
    json_out(['ok' => false, 'message' => 'Prepare failed']);
}

$stmt->bind_param("s", $value);
$stmt->execute();
$stmt->store_result();
$exists = ($stmt->num_rows > 0);
$stmt->close();

json_out([
    'ok' => true,
    'field' => $field,
    'exists' => $exists
]);