<?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="laundry_' . $start . '_to_' . $end . '.csv"');

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

fputcsv($out, [
  'Event ID','Created At','Building','Unit','Bag #',
  'Item Type','Action','Status After','Staff',
  'Geo Address','Lat','Lng','Accuracy(m)'
]);

try {
  if ($isAdmin) {
    $stmt = db()->prepare("
      SELECT e.*, u.full_name staff_name,
             lb.bag_number, un.unit_code, bl.name building_name
      FROM laundry_bag_events e
      JOIN laundry_bags lb ON lb.id=e.bag_id
      JOIN units un ON un.id=lb.unit_id
      JOIN buildings bl ON bl.id=un.building_id
      LEFT JOIN users u ON u.id=e.changed_by_user_id
      WHERE e.created_at BETWEEN ? AND ?
      ORDER BY e.created_at DESC, e.id DESC
    ");
    $stmt->execute([$startDt, $endDt]);
  } else {
    $stmt = db()->prepare("
      SELECT e.*, u.full_name staff_name,
             lb.bag_number, un.unit_code, bl.name building_name
      FROM laundry_bag_events e
      JOIN laundry_bags lb ON lb.id=e.bag_id
      JOIN units un ON un.id=lb.unit_id
      JOIN buildings bl ON bl.id=un.building_id
      LEFT JOIN users u ON u.id=e.changed_by_user_id
      WHERE e.changed_by_user_id=? AND e.created_at BETWEEN ? AND ?
      ORDER BY e.created_at DESC, e.id DESC
    ");
    $stmt->execute([(int)$user['id'], $startDt, $endDt]);
  }

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

fclose($out);
exit;
