<?php
require 'db.php';
require 'functions.php';
requireRole(['panchayatuser']);

$panchayatid = currentPanchayatId();

$fullname = cleanInput($_POST['fullname'] ?? '');
$phone = cleanInput($_POST['phone'] ?? '');
$dob = cleanInput($_POST['dob'] ?? '');
$verifymethod = cleanInput($_POST['verifymethod'] ?? '');
$paymentmethodinput = cleanInput($_POST['paymentmethod'] ?? 'unpaid');
$vehicles = $_POST['vehicles'] ?? [];

if ($fullname === '' || $phone === '' || $dob === '' || $verifymethod === '') {
    jsonOut(false, 'Name, phone, date of birth and verification method are required');
}
if (!preg_match('/^[0-9]{10}$/', $phone)) {
    jsonOut(false, 'Phone number must be 10 digits');
}
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $dob) || strtotime($dob) === false) {
    jsonOut(false, 'Invalid date of birth');
}
if (!in_array($verifymethod, ['aadhaar', 'house'], true)) {
    jsonOut(false, 'Invalid verification method');
}

try {
    $dupstmt = $pdo->prepare("SELECT id FROM villager WHERE phone = ? AND isdeleted = 0");
    $dupstmt->execute([$phone]);
    if ($dupstmt->fetch()) {
        jsonOut(false, 'A villager is already registered with this phone number');
    }

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

    // Photo (required)
    $photoresult = uploadFile($_FILES['photo'] ?? [], APPROOT . '/uploads/photos', ['jpg', 'jpeg', 'png']);
    if (!$photoresult['success']) {
        jsonOut(false, 'Photo: ' . $photoresult['message']);
    }
    $photo = $photoresult['filename'];

    $hasaadhaar = 0;
    $aadhaarnumber = null;
    $aadhaarphoto = null;
    $village = null;
    $houseno = null;
    $address = '';

    if ($verifymethod === 'aadhaar') {
        $aadhaarnumber = cleanInput($_POST['aadhaarnumber'] ?? '');
        $village = cleanInput($_POST['village'] ?? '');
        $address = cleanInput($_POST['addressaadhaar'] ?? '');

        if (!preg_match('/^[0-9]{12}$/', $aadhaarnumber)) {
            jsonOut(false, 'Aadhaar number must be 12 digits');
        }
        if ($village === '') {
            jsonOut(false, 'Village (vtc field from the Aadhaar card) is required');
        }
        if ($address === '') {
            jsonOut(false, 'Address is required');
        }

        $detectedpanchayatid = getPanchayatIdByVillage($pdo, $village);
        if (!$detectedpanchayatid) {
            jsonOut(false, "The village \"{$village}\" is not recognized as part of Divar");
        }
        if ($detectedpanchayatid != $panchayatid) {
            jsonOut(false, 'This Aadhaar\'s village belongs to a different panchayat. Please verify the address before proceeding.');
        }

        if (!empty($_FILES['aadhaarphoto']['name'])) {
            $aphotoresult = uploadFile($_FILES['aadhaarphoto'], APPROOT . '/uploads/aadhaar', ['jpg', 'jpeg', 'png']);
            if ($aphotoresult['success']) {
                $aadhaarphoto = $aphotoresult['filename'];
            }
        }

        $hasaadhaar = 1;
    } else {
        $houseno = cleanInput($_POST['houseno'] ?? '');
        $address = cleanInput($_POST['addresshouse'] ?? '');
        if ($houseno === '') {
            jsonOut(false, 'House number is required');
        }
        if ($address === '') {
            $pstmt = $pdo->prepare("SELECT name FROM panchayat WHERE id = ?");
            $pstmt->execute([$panchayatid]);
            $prow = $pstmt->fetch();
            $address = ($prow ? $prow['name'] : '') . ', Divar';
        }
    }

    $ins = $pdo->prepare("INSERT INTO villager (fullname, phone, photo, hasaadhaar, aadhaarnumber, aadhaarphoto,
        verifymethod, address, houseno, village, panchayatid, dob, age, status, approvedby, approvedat,
        paymentstatus)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'approved', ?, NOW(), 'unpaid')");
    $ins->execute([$fullname, $phone, $photo, $hasaadhaar, $aadhaarnumber, $aadhaarphoto,
        $verifymethod, $address, $houseno, $village, $panchayatid, $dob, $age, currentUserId()]);
    $villagerid = $pdo->lastInsertId();

    foreach ($vehicles as $vehiclenumber) {
        $vehiclenumber = strtoupper(cleanInput($vehiclenumber));
        if ($vehiclenumber !== '') {
            $vins = $pdo->prepare("INSERT INTO villagervehicle (villagerid, vehiclenumber) VALUES (?, ?)");
            $vins->execute([$villagerid, $vehiclenumber]);
        }
    }

    logActivity($pdo, 'villager', $villagerid, 'assistedregister', 'panchayatuser', currentUserId(), 'Registered and auto-approved by panchayat staff');

    $fee = getSetting($pdo, 'registrationfee', '100.00');

    if (bccomp(moneyStr($fee), '0.00', 2) === 0) {
        activateFreePass($pdo, $villagerid);
        jsonOut(true, 'Villager registered successfully. Registration fee is currently Rs. 0, so the pass is already active.', ['id' => $villagerid]);
    }

    if (in_array($paymentmethodinput, ['cash', 'upi'], true)) {
        $validityyears = getSetting($pdo, 'passvalidityyears', '2');
        $startdate = date('Y-m-d');
        $enddate = calcPassEndDate($startdate, $validityyears);
        $barcode = generateBarcodeText($villagerid);
        $syntheticorderid = strtoupper($paymentmethodinput) . '-' . $villagerid . '-' . time();

        $vupd = $pdo->prepare("UPDATE villager SET paymentstatus = 'paid', paidat = NOW(), registrationfee = ?,
            passstartdate = ?, passenddate = ?, passactive = 1, barcodetext = ? WHERE id = ?");
        $vupd->execute([moneyStr($fee), $startdate, $enddate, $barcode, $villagerid]);

        $pins = $pdo->prepare("INSERT INTO paymentorder (villagerid, razorpayorderid, amount, currency, status, createdbytype, createdbyid, paymentmethod, paidat)
            VALUES (?, ?, ?, 'INR', 'paid', 'panchayat', ?, ?, NOW())");
        $pins->execute([$villagerid, $syntheticorderid, moneyStr($fee), currentUserId(), $paymentmethodinput]);

        logActivity($pdo, 'villager', $villagerid, 'assistedpayment', 'panchayatuser', currentUserId(), 'Fee collected via ' . $paymentmethodinput);

        jsonOut(true, 'Villager registered, approved and marked as paid via ' . strtoupper($paymentmethodinput) . '. Pass is now active.', ['id' => $villagerid]);
    }

    jsonOut(true, 'Villager registered and approved. Payment is still pending - they can pay later via the app.', ['id' => $villagerid]);
} catch (Exception $e) {
    logDebug('[ajax_panchayat_registerassisted] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
