<?php
require_once '../config/db.php';

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

$nroi_id = $_GET['nroi_id'] ?? '';

if (empty($nroi_id)) {
    echo json_encode(['valid' => false, 'message' => 'NROI ID required']);
    exit;
}

// Check if numeric and length
if (!is_numeric($nroi_id) || strlen($nroi_id) > 12) {
    echo json_encode(['valid' => false, 'message' => 'NROI ID must be numeric (max 12 digits)']);
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE nroi_id = ?");
    $stmt->execute([$nroi_id]);
    $count = $stmt->fetchColumn();

    if ($count > 0) {
        echo json_encode(['valid' => false, 'is_unique' => false, 'message' => 'NROI ID already registered']);
    } else {
        echo json_encode(['valid' => true, 'is_unique' => true, 'message' => 'NROI ID available']);
    }
} catch (Exception $e) {
    echo json_encode(['valid' => false, 'message' => 'Error checking NROI ID']);
}
?>