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

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

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

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

if (strlen($ppsa_id) > 12) {
    echo json_encode(['valid' => false, 'message' => 'PPSA ID must be max 12 characters']);
    exit;
}

try {
    // Check users table for ppsa_id uniqueness
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE ppsa_id = ?");
    $stmt->execute([$ppsa_id]);
    $count = $stmt->fetchColumn();

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