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

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

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

    $id = (int)($_POST['id'] ?? 0);
    if ($id <= 0 && in_array($action, ['deactivate', 'activate', 'delete'], true)) {
        jsonOut(false, 'Invalid villager reference');
    }

    if ($action === 'deactivate') {
        $stmt = $pdo->prepare("UPDATE villager SET passactive = 0, deactivatedby = ?, deactivatedat = NOW(), deactivatereason = 'Deactivated by admin' WHERE id = ?");
        $stmt->execute([currentUserId(), $id]);
        logActivity($pdo, 'villager', $id, 'deactivate', 'admin', currentUserId(), 'Pass deactivated by admin');
        jsonOut(true, 'Pass deactivated successfully');
    }

    if ($action === 'activate') {
        $stmt = $pdo->prepare("SELECT status, paymentstatus FROM villager WHERE id = ?");
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        if (!$row || $row['status'] !== 'approved' || $row['paymentstatus'] !== 'paid') {
            jsonOut(false, 'Pass can only be activated for an approved and paid villager');
        }
        $upd = $pdo->prepare("UPDATE villager SET passactive = 1, deactivatedby = NULL, deactivatedat = NULL, deactivatereason = NULL WHERE id = ?");
        $upd->execute([$id]);
        logActivity($pdo, 'villager', $id, 'activate', 'admin', currentUserId(), 'Pass re-activated by admin');
        jsonOut(true, 'Pass activated successfully');
    }

    if ($action === 'delete') {
        $stmt = $pdo->prepare("UPDATE villager SET isdeleted = 1 WHERE id = ?");
        $stmt->execute([$id]);
        logActivity($pdo, 'villager', $id, 'delete', 'admin', currentUserId(), 'Villager record soft-deleted by admin');
        jsonOut(true, 'Villager record deleted successfully');
    }

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