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

use Shuchkin\SimpleXLSXGen;

$type = cleanInput($_GET['type'] ?? 'villagers');

if ($type === 'payments') {
    $rows = $pdo->query("SELECT v.fullname, v.phone, po.razorpayorderid, po.razorpaypaymentid, po.amount,
        po.status, po.createdbytype, po.createdat, po.paidat
        FROM paymentorder po JOIN villager v ON v.id = po.villagerid
        WHERE po.isdeleted = 0 ORDER BY po.id DESC")->fetchAll();

    $data = [['Name', 'Phone', 'Order ID', 'Payment ID', 'Amount (Rs.)', 'Status', 'Created By', 'Created At', 'Paid At']];
    foreach ($rows as $r) {
        $data[] = [
            html_entity_decode($r['fullname'], ENT_QUOTES),
            $r['phone'], $r['razorpayorderid'], $r['razorpaypaymentid'] ?: '-',
            moneyStr($r['amount']), $r['status'], $r['createdbytype'], $r['createdat'], $r['paidat'] ?: '-'
        ];
    }
    $filename = 'DivarFerryPass_Payments_' . date('Ymd_His') . '.xlsx';
} else {
    $rows = $pdo->query("SELECT v.fullname, v.phone, p.name AS panchayatname, v.address, v.houseno,
        v.status, v.paymentstatus, v.passactive, v.passstartdate, v.passenddate
        FROM villager v LEFT JOIN panchayat p ON p.id = v.panchayatid
        WHERE v.isdeleted = 0 ORDER BY v.id DESC")->fetchAll();

    $data = [['Name', 'Phone', 'Panchayat', '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'], $r['panchayatname'], html_entity_decode($r['address'], ENT_QUOTES), $r['houseno'] ?: '-',
            $r['status'], $r['paymentstatus'], $r['passactive'] == 1 ? 'Yes' : 'No',
            $r['passstartdate'] ?: '-', $r['passenddate'] ?: '-'
        ];
    }
    $filename = 'DivarFerryPass_Villagers_' . date('Ymd_His') . '.xlsx';
}

logActivity($pdo, 'report', 0, 'export', 'admin', currentUserId(), $filename);

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