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

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

try {
    // Re-fetch latest state (villager row from token may be slightly stale after prior steps)
    $stmt = $pdo->prepare("SELECT * FROM villager WHERE id = ? AND isdeleted = 0");
    $stmt->execute([$villager['id']]);
    $v = $stmt->fetch();

    if (!$v || $v['fullname'] === '' || empty($v['panchayatid']) || empty($v['address'])) {
        jsonOut(false, 'Please complete all previous steps (name, photo and residency verification) before submitting');
    }
    if ($v['status'] !== 'pending') {
        jsonOut(false, 'This registration has already been submitted and reviewed');
    }

    logActivity($pdo, 'villager', $v['id'], 'submit', 'villager', $v['id'], 'Registration submitted for panchayat review');

    // Notify the panchayat user(s) for this villager's panchayat
    $pustmt = $pdo->prepare("SELECT phone FROM panchayatuser WHERE panchayatid = ? AND isactive = 1 AND isdeleted = 0");
    $pustmt->execute([$v['panchayatid']]);
    foreach ($pustmt->fetchAll() as $pu) {
        sendWhatsapp($pdo, $pu['phone'], "New Divar Ferry Pass registration from {$v['fullname']} ({$v['phone']}) is awaiting your review.", 'newregistration');
    }

    jsonOut(true, 'Registration submitted successfully. You will be notified once the Panchayat reviews it.');
} catch (Exception $e) {
    logDebug('[api_submitregistration] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
