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

$action = cleanInput($_POST['action'] ?? $_GET['action'] ?? '');
$panchayatid = currentPanchayatId();

try {
    if ($action === 'list') {
        $stmt = $pdo->prepare("SELECT id, fullname, phone, status, paymentstatus, passactive, createdat, verifymethod
            FROM villager WHERE isdeleted = 0 AND panchayatid = ? ORDER BY id DESC");
        $stmt->execute([$panchayatid]);
        jsonOut(true, '', $stmt->fetchAll());
    }

    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0 && in_array($action, ['approve', 'reject', 'deactivate'], true)) {
        // Defensive: ensure this villager belongs to the logged-in panchayat before any write
        $check = $pdo->prepare("SELECT id, status, phone, fullname FROM villager WHERE id = ? AND panchayatid = ? AND isdeleted = 0");
        $check->execute([$id, $panchayatid]);
        $villager = $check->fetch();
        if (!$villager) {
            jsonOut(false, 'Villager not found in your panchayat');
        }
    }

    if ($action === 'approve') {
        if ($villager['status'] !== 'pending') {
            jsonOut(false, 'Only pending registrations can be approved');
        }
        $stmt = $pdo->prepare("UPDATE villager SET status = 'approved', approvedby = ?, approvedat = NOW() WHERE id = ?");
        $stmt->execute([currentUserId(), $id]);
        logActivity($pdo, 'villager', $id, 'approve', 'panchayatuser', currentUserId(), 'Registration approved');

        $fee = getSetting($pdo, 'registrationfee', '100.00');
        if (bccomp(moneyStr($fee), '0.00', 2) === 0) {
            activateFreePass($pdo, $id);
            sendSms($pdo, $villager['phone'], "Hi {$villager['fullname']}, your Divar Ferry Pass registration is approved and your pass is now active (no fee required). Open the app to view your pass.", 'approval');
            jsonOut(true, 'Registration approved. Registration fee is currently Rs. 0, so the pass has been activated immediately.');
        }

        sendSms($pdo, $villager['phone'], "Hi {$villager['fullname']}, your Divar Ferry Pass registration is approved. Open the app to pay the registration fee and activate your pass.", 'approval');
        jsonOut(true, 'Registration approved successfully');
    }

    if ($action === 'reject') {
        $reason = cleanInput($_POST['reason'] ?? '');
        if ($villager['status'] !== 'pending') {
            jsonOut(false, 'Only pending registrations can be rejected');
        }
        if ($reason === '') {
            jsonOut(false, 'A rejection reason is required');
        }
        $stmt = $pdo->prepare("UPDATE villager SET status = 'rejected', rejectreason = ?, approvedby = ?, approvedat = NOW() WHERE id = ?");
        $stmt->execute([$reason, currentUserId(), $id]);
        logActivity($pdo, 'villager', $id, 'reject', 'panchayatuser', currentUserId(), 'Registration rejected: ' . $reason);
        sendSms($pdo, $villager['phone'], "Hi {$villager['fullname']}, your Divar Ferry Pass registration was rejected. Reason: {$reason}", 'rejection');
        jsonOut(true, 'Registration rejected successfully');
    }

    if ($action === 'deactivate') {
        $reason = cleanInput($_POST['reason'] ?? '');
        if ($reason === '') {
            jsonOut(false, 'A deactivation reason is required');
        }
        $stmt = $pdo->prepare("UPDATE villager SET passactive = 0, deactivatedby = ?, deactivatedat = NOW(), deactivatereason = ? WHERE id = ?");
        $stmt->execute([currentUserId(), $reason, $id]);
        logActivity($pdo, 'villager', $id, 'deactivate', 'panchayatuser', currentUserId(), 'Pass deactivated: ' . $reason);
        sendSms($pdo, $villager['phone'], "Hi {$villager['fullname']}, your Divar Ferry Pass has been deactivated. Reason: {$reason}", 'deactivation');
        jsonOut(true, 'Pass deactivated successfully');
    }

    jsonOut(false, 'Invalid action');
} catch (Exception $e) {
    logDebug('[ajax_panchayat_registration] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
