<?php
require '../db.php';
require '../functions.php';

header('Content-Type: application/json');
$villager = requireVillagerToken($pdo);

// IMPORTANT: this call must be multipart/form-data because 'aadhaarphoto' is an actual
// file field, not a filename string - there is no separate "upload first" step needed.
//
// Aadhaar QR parsing (extracting the signed XML payload's name/dob/vtc fields) happens
// client-side in the app using a QR-decoding library. This endpoint receives the
// already-parsed fields plus the Aadhaar card image, and:
//   1) looks up which panchayat the Aadhaar's village (the 'vtc' field) belongs to via
//      the villagepanchayat table - this is the authoritative source of the villager's
//      panchayat, not a manual dropdown (matching is case-insensitive)
//   2) uses the Aadhaar's name field as the villager's official name (overwrites Step 1)
//   3) enforces the minimum age setting

$aadhaarnumber = cleanInput($_POST['aadhaarnumber'] ?? '');
$name = cleanInput($_POST['name'] ?? ''); // name field as read from the Aadhaar QR
$address = cleanInput($_POST['address'] ?? '');
$dob = cleanInput($_POST['dob'] ?? ''); // YYYY-MM-DD (app converts from Aadhaar's DD/MM/YYYY)
$village = cleanInput($_POST['village'] ?? ''); // vtc field from the Aadhaar QR

if ($aadhaarnumber === '' || $name === '' || $address === '' || $dob === '' || $village === '') {
    jsonOut(false, 'Aadhaar number, name, address, date of birth and village are required');
}
if (!preg_match('/^[0-9]{12}$/', $aadhaarnumber)) {
    jsonOut(false, 'Aadhaar number must be 12 digits');
}
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $dob) || strtotime($dob) === false) {
    jsonOut(false, 'Invalid date of birth format');
}

try {
    $panchayatid = getPanchayatIdByVillage($pdo, $village);
    if (!$panchayatid) {
        jsonOut(false, "The village \"{$village}\" on this Aadhaar is not recognized as part of Divar (Golti-Navelim or Malar/Sao Mathias). Please use the house number method instead, or contact your panchayat.");
    }

    $age = calcAge($dob);
    $minage = (int)getSetting($pdo, 'minage', '18');
    if ($age < $minage) {
        jsonOut(false, "You must be at least {$minage} years old to register");
    }

    $aadhaarphoto = null;
    $hasnewphoto = !empty($_FILES['aadhaarphoto']['name']);
    if ($hasnewphoto) {
        $result = uploadFile($_FILES['aadhaarphoto'], APPROOT . '/uploads/aadhaar', ['jpg', 'jpeg', 'png']);
        if (!$result['success']) {
            jsonOut(false, 'Aadhaar photo: ' . $result['message']);
        }
        $aadhaarphoto = $result['filename'];
    }

    if ($hasnewphoto) {
        $stmt = $pdo->prepare("UPDATE villager SET fullname = ?, hasaadhaar = 1, aadhaarnumber = ?, aadhaarphoto = ?,
            verifymethod = 'aadhaar', address = ?, houseno = NULL, village = ?, panchayatid = ?, dob = ?, age = ? WHERE id = ?");
        $stmt->execute([$name, $aadhaarnumber, $aadhaarphoto, $address, $village, $panchayatid, $dob, $age, $villager['id']]);
    } else {
        // Retried without re-sending the file - keep whatever aadhaarphoto is already on record.
        $stmt = $pdo->prepare("UPDATE villager SET fullname = ?, hasaadhaar = 1, aadhaarnumber = ?,
            verifymethod = 'aadhaar', address = ?, houseno = NULL, village = ?, panchayatid = ?, dob = ?, age = ? WHERE id = ?");
        $stmt->execute([$name, $aadhaarnumber, $address, $village, $panchayatid, $dob, $age, $villager['id']]);
    }

    logActivity($pdo, 'villager', $villager['id'], 'verifyresidency', 'villager', $villager['id'], 'Verified via Aadhaar, village ' . $village);

    jsonOut(true, 'Residency verified successfully', ['panchayatid' => $panchayatid]);
} catch (Exception $e) {
    logDebug('[api_aadhaarverify] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
