<?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();
$isAdmin = (($user['role'] ?? '') === 'admin');

$start = trim($_GET['start'] ?? date('Y-m-01'));
$end   = trim($_GET['end'] ?? date('Y-m-d'));
$startDt = $start . ' 00:00:00';
$endDt   = $end . ' 23:59:59';

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="inspections_' . $start . '_to_' . $end . '.csv"');

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

fputcsv($out, [
  'Inspection ID','Inspected At','Building','Unit','Staff',
  'Notes','Geo Address','Lat','Lng','Accuracy(m)'
]);

try {
  if ($isAdmin) {
    $stmt = db()->prepare("
      SELECT i.*, u.unit_code, b.name building_name, usr.full_name staff_name
      FROM inspections i
      JOIN units u ON u.id=i.unit_id
      JOIN buildings b ON b.id=u.building_id
      LEFT JOIN users usr ON usr.id=i.staff_user_id
      WHERE i.inspected_at BETWEEN ? AND ?
      ORDER BY i.inspected_at DESC, i.id DESC
    ");
    $stmt->execute([$startDt, $endDt]);
  } else {
    $stmt = db()->prepare("
      SELECT i.*, u.unit_code, b.name building_name, usr.full_name staff_name
      FROM inspections i
      JOIN units u ON u.id=i.unit_id
      JOIN buildings b ON b.id=u.building_id
      LEFT JOIN users usr ON usr.id=i.staff_user_id
      WHERE i.staff_user_id=? AND i.inspected_at BETWEEN ? AND ?
      ORDER BY i.inspected_at DESC, i.id DESC
    ");
    $stmt->execute([(int)$user['id'], $startDt, $endDt]);
  }

  while ($row = $stmt->fetch()) {
    fputcsv($out, [
      $row['id'] ?? '',
      $row['inspected_at'] ?? '',
      $row['building_name'] ?? '',
      $row['unit_code'] ?? '',
      $row['staff_name'] ?? '',
      $row['notes'] ?? '',
      $row['geo_address'] ?? '',
      $row['geo_lat'] ?? '',
      $row['geo_lng'] ?? '',
      $row['geo_accuracy'] ?? '',
    ]);
  }
} catch (Throwable $e) {}

fclose($out);
exit;
