<?php
require 'db.php';
require 'functions.php';
requireRole(['panchayatuser']);
require 'vendor/simplexlsxgen/SimpleXLSXGen.php';

use Shuchkin\SimpleXLSXGen;

$panchayatid = currentPanchayatId();

$stmt = $pdo->prepare("SELECT fullname, phone, address, houseno, status, paymentstatus, passactive, passstartdate, passenddate
    FROM villager WHERE isdeleted = 0 AND panchayatid = ? ORDER BY id DESC");
$stmt->execute([$panchayatid]);
$rows = $stmt->fetchAll();

$data = [['Name', 'Phone', 'Address', 'House No', 'Status', 'Payment Status', 'Pass Active', 'Valid From', 'Valid Until']];
foreach ($rows as $r) {
    $data[] = [
        html_entity_decode($r['fullname'], ENT_QUOTES),
        $r['phone'], html_entity_decode($r['address'], ENT_QUOTES), $r['houseno'] ?: '-',
        $r['status'], $r['paymentstatus'], $r['passactive'] == 1 ? 'Yes' : 'No',
        $r['passstartdate'] ?: '-', $r['passenddate'] ?: '-'
    ];
}

$filename = 'DivarFerryPass_Panchayat_Villagers_' . date('Ymd_His') . '.xlsx';
logActivity($pdo, 'report', 0, 'export', 'panchayatuser', currentUserId(), $filename);

SimpleXLSXGen::fromArray($data)->downloadAs($filename);
