<?php
require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/middleware/auth.php';
require_once __DIR__ . '/../app/config/db.php';

require_login();
$user = current_user();
if (($user['role'] ?? '') !== 'admin') { http_response_code(403); exit('Forbidden'); }

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="tenants.csv"');

$out = fopen('php://output', 'w');
fputcsv($out, ['Tenant ID','Name','Email','Phone','Unit','Building','Active','Move In','Move Out','Created At']);

try {
  $stmt = db()->query("
    SELECT t.*, u.unit_code, b.name building_name
    FROM tenants t
    JOIN units u ON u.id=t.unit_id
    JOIN buildings b ON b.id=u.building_id
    ORDER BY t.created_at DESC, t.id DESC
  ");
  while ($r = $stmt->fetch()) {
    fputcsv($out, [
      $r['id'] ?? '',
      $r['full_name'] ?? '',
      $r['email'] ?? '',
      $r['phone'] ?? '',
      $r['unit_code'] ?? '',
      $r['building_name'] ?? '',
      (int)($r['is_active'] ?? 0),
      $r['move_in_date'] ?? '',
      $r['move_out_date'] ?? '',
      $r['created_at'] ?? '',
    ]);
  }
} catch (Throwable $e) {}

fclose($out);
exit;
