<?php
require_once __DIR__ . '/../../includes/init.php';
middleware(['super_admin']);

$db = getDBConnection();

$singleId = (int)($_GET['id'] ?? 0);

if ($singleId) {
    $rows = dbRows($db,
        "SELECT u.full_name, u.username, u.phone AS login_phone, u.division,
                k.mobile, k.current_address, k.aadhaar_number, k.aadhaar_address,
                k.bank_account, k.bank_ifsc,
                k.pf_number, k.esi_number, k.pan_number,
                k.submitted_at, k.updated_at
         FROM users u
         LEFT JOIN mr_kyc k ON k.user_id = u.id
         WHERE u.id = ? AND u.role = 'mr'", [$singleId]);
} else {
    $rows = dbRows($db,
        "SELECT u.full_name, u.username, u.phone AS login_phone, u.division,
                k.mobile, k.current_address, k.aadhaar_number, k.aadhaar_address,
                k.bank_account, k.bank_ifsc,
                k.pf_number, k.esi_number, k.pan_number,
                k.submitted_at, k.updated_at
         FROM users u
         LEFT JOIN mr_kyc k ON k.user_id = u.id
         WHERE u.role = 'mr' AND u.is_active = 1
         ORDER BY u.full_name");
}

$filename = 'MR_KYC_' . date('Ymd_His') . '.csv';

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Pragma: no-cache');
header('Expires: 0');

// UTF-8 BOM for Excel
echo "\xEF\xBB\xBF";

$out = fopen('php://output', 'w');

// Header row
fputcsv($out, array(
    'Sr No',
    'Full Name',
    'Username',
    'Login Mobile',
    'Division',
    'KYC Mobile',
    'Current Address',
    'Aadhaar Number',
    'Aadhaar Address',
    'Bank Account No',
    'IFSC Code',
    'PF Number',
    'ESI Number',
    'PAN Number',
    'KYC Submitted On',
    'KYC Updated On',
    'KYC Status',
));

foreach ($rows as $i => $r) {
    $status = !empty($r['aadhaar_number']) || !empty($r['bank_account']) ? 'Submitted' : 'Pending';
    fputcsv($out, array(
        $i + 1,
        $r['full_name']      ?? '',
        $r['username']       ?? '',
        $r['login_phone']    ?? '',
        $r['division']       ?? '',
        $r['mobile']         ?? '',
        $r['current_address'] ?? '',
        $r['aadhaar_number'] ?? '',
        $r['aadhaar_address'] ?? '',
        $r['bank_account']   ?? '',
        $r['bank_ifsc']      ?? '',
        $r['pf_number']      ?? '',
        $r['esi_number']     ?? '',
        $r['pan_number']     ?? '',
        $r['submitted_at']   ? date('d M Y', strtotime($r['submitted_at'])) : '',
        $r['updated_at']     ? date('d M Y', strtotime($r['updated_at']))   : '',
        $status,
    ));
}

fclose($out);
exit;
