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

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

$panchayatid = (int)($_POST['panchayatid'] ?? 0);
$houseno = cleanInput($_POST['houseno'] ?? '');
$address = cleanInput($_POST['address'] ?? '');
$dob = cleanInput($_POST['dob'] ?? '');

if ($panchayatid <= 0 || $houseno === '' || $dob === '') {
    jsonOut(false, 'Panchayat, house number and date of birth are required');
}
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $dob) || strtotime($dob) === false) {
    jsonOut(false, 'Invalid date of birth format');
}

try {
    $pstmt = $pdo->prepare("SELECT id, name FROM panchayat WHERE id = ? AND isdeleted = 0");
    $pstmt->execute([$panchayatid]);
    $panchayat = $pstmt->fetch();
    if (!$panchayat) {
        jsonOut(false, 'Invalid panchayat selected');
    }

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

    $finaladdress = $address !== '' ? $address : ($panchayat['name'] . ', Divar');

    $stmt = $pdo->prepare("UPDATE villager SET hasaadhaar = 0, aadhaarnumber = NULL, aadhaarphoto = NULL,
        verifymethod = 'house', address = ?, houseno = ?, panchayatid = ?, dob = ?, age = ? WHERE id = ?");
    $stmt->execute([$finaladdress, $houseno, $panchayatid, $dob, $age, $villager['id']]);

    logActivity($pdo, 'villager', $villager['id'], 'verifyresidency', 'villager', $villager['id'], 'Verified via house number');

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