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

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

try {
    if ($action === 'list') {
        $rows = $pdo->query("SELECT v.id, v.fullname, v.phone, v.passenddate, v.passactive, v.isprinted, p.name AS panchayatname
            FROM villager v LEFT JOIN panchayat p ON p.id = v.panchayatid
            WHERE v.isdeleted = 0 AND v.status = 'approved' AND v.paymentstatus = 'paid'
            ORDER BY v.id DESC")->fetchAll();
        jsonOut(true, '', $rows);
    }

    if ($action === 'markprinted') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $pdo->prepare("SELECT id FROM villager WHERE id = ? AND isdeleted = 0 AND status = 'approved' AND paymentstatus = 'paid'");
        $stmt->execute([$id]);
        if (!$stmt->fetch()) {
            jsonOut(false, 'Registration not found or not yet completed');
        }
        $upd = $pdo->prepare("UPDATE villager SET isprinted = 1, printedat = NOW(), printedby = ? WHERE id = ?");
        $upd->execute([currentUserId(), $id]);
        logActivity($pdo, 'villager', $id, 'markprinted', 'rnduser', currentUserId(), 'Physical pass marked as printed');
        jsonOut(true, 'Marked as printed successfully');
    }

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