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

use Shuchkin\SimpleXLSXGen;

$rows = $pdo->query("SELECT v.fullname, v.phone, p.name AS panchayatname, v.passstartdate, v.passenddate,
    v.passactive, v.isprinted
    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();

$data = [['Name', 'Phone', 'Panchayat', 'Valid From', 'Valid Until', 'Pass Active', 'Physical Pass Printed']];
foreach ($rows as $r) {
    $data[] = [
        html_entity_decode($r['fullname'], ENT_QUOTES),
        $r['phone'], $r['panchayatname'], $r['passstartdate'] ?: '-', $r['passenddate'] ?: '-',
        $r['passactive'] == 1 ? 'Yes' : 'No', $r['isprinted'] == 1 ? 'Yes' : 'No'
    ];
}

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

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