<?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, passenddate FROM villager
            WHERE isdeleted = 0 AND panchayatid = ? AND passactive = 1
            AND passenddate BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 60 DAY)
            ORDER BY passenddate ASC");
        $stmt->execute([$panchayatid]);
        jsonOut(true, '', $stmt->fetchAll());
    }

    if ($action === 'renew') {
        $id = (int)($_POST['id'] ?? 0);
        $years = cleanInput($_POST['years'] ?? '1');
        if (!in_array($years, ['1', '2'], true)) {
            jsonOut(false, 'Renewal period must be 1 or 2 years');
        }

        $stmt = $pdo->prepare("SELECT id, fullname, phone, passenddate FROM villager WHERE id = ? AND panchayatid = ? AND isdeleted = 0");
        $stmt->execute([$id, $panchayatid]);
        $villager = $stmt->fetch();
        if (!$villager) {
            jsonOut(false, 'Villager not found in your panchayat');
        }

        $basedate = $villager['passenddate'] && strtotime($villager['passenddate']) > time() ? $villager['passenddate'] : date('Y-m-d');
        $newenddate = calcPassEndDate($basedate, $years);

        $upd = $pdo->prepare("UPDATE villager SET passenddate = ? WHERE id = ?");
        $upd->execute([$newenddate, $id]);

        logActivity($pdo, 'villager', $id, 'renew', 'panchayatuser', currentUserId(), "Pass renewed by {$years} year(s), new end date {$newenddate}");
        sendSms($pdo, $villager['phone'], "Hi {$villager['fullname']}, your Divar Ferry Pass has been renewed until {$newenddate}.", 'renewal');

        jsonOut(true, 'Pass renewed successfully. New validity: ' . $newenddate);
    }

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