<?php
require_once __DIR__ . '/../includes/auth.php';
requireLoginApi();
header('Content-Type: application/json');

$pdo = getPDO();

function normText(string $s): string {
    return preg_replace('/\s+/', ' ', strtoupper(trim($s)));
}
function normDigits(string $s): string {
    return preg_replace('/\D/', '', $s);
}
function nameDobKey(string $name, string $father, string $mother, string $dob): string {
    return normText($name) . '|' . normText($father) . '|' . normText($mother) . '|' . trim($dob);
}

$aadhaar = $_POST['aadhaar'] ?? '';
$name = $_POST['cwsn_name'] ?? '';
$father = $_POST['cwsn_f_name'] ?? '';
$mother = $_POST['cwsn_m_name'] ?? '';
$dob = $_POST['dob'] ?? '';

$aadhaarNorm = normDigits($aadhaar);
if ($aadhaarNorm !== '') {
    $stmt = $pdo->prepare('SELECT * FROM udise_enrollment WHERE aadhaar_norm = ? LIMIT 1');
    $stmt->execute([$aadhaarNorm]);
    $row = $stmt->fetch();
    if ($row) {
        echo json_encode(['matched' => true, 'matchType' => 'AADHAAR', 'udise' => $row]);
        exit;
    }
}

if ($name !== '' && $father !== '' && $mother !== '' && $dob !== '') {
    $key = nameDobKey($name, $father, $mother, $dob);
    $stmt = $pdo->prepare('SELECT * FROM udise_enrollment WHERE name_dob_key = ? LIMIT 1');
    $stmt->execute([$key]);
    $row = $stmt->fetch();
    if ($row) {
        echo json_encode(['matched' => true, 'matchType' => 'NAME_DOB', 'udise' => $row]);
        exit;
    }
}

echo json_encode(['matched' => false]);
