<?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');

$pageTitle = 'Reports';
require_once __DIR__ . '/../app/views/partials/header.php';

$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';

// Summary cards
$sum = [
  'inspections' => 0,
  'laundry_events' => 0,
  'tenants_added' => 0,
  'units_added' => 0,
];

try {
  // inspections
  if ($isAdmin) {
    $s = db()->prepare("SELECT COUNT(*) c FROM inspections WHERE inspected_at BETWEEN ? AND ?");
    $s->execute([$startDt, $endDt]);
  } else {
    $s = db()->prepare("SELECT COUNT(*) c FROM inspections WHERE staff_user_id=? AND inspected_at BETWEEN ? AND ?");
    $s->execute([(int)$user['id'], $startDt, $endDt]);
  }
  $sum['inspections'] = (int)($s->fetch()['c'] ?? 0);

  // laundry events
  if ($isAdmin) {
    $s = db()->prepare("SELECT COUNT(*) c FROM laundry_bag_events WHERE created_at BETWEEN ? AND ?");
    $s->execute([$startDt, $endDt]);
  } else {
    $s = db()->prepare("SELECT COUNT(*) c FROM laundry_bag_events WHERE changed_by_user_id=? AND created_at BETWEEN ? AND ?");
    $s->execute([(int)$user['id'], $startDt, $endDt]);
  }
  $sum['laundry_events'] = (int)($s->fetch()['c'] ?? 0);

  // optional: tenant/unit created_at filters (admin only)
  if ($isAdmin) {
    $s = db()->prepare("SELECT COUNT(*) c FROM tenants WHERE created_at BETWEEN ? AND ?");
    $s->execute([$startDt, $endDt]);
    $sum['tenants_added'] = (int)($s->fetch()['c'] ?? 0);

    $s = db()->prepare("SELECT COUNT(*) c FROM units WHERE created_at BETWEEN ? AND ?");
    $s->execute([$startDt, $endDt]);
    $sum['units_added'] = (int)($s->fetch()['c'] ?? 0);
  }

} catch (Throwable $e) {}

function q(array $extra): string {
  $q = array_merge($_GET, $extra);
  return http_build_query($q);
}
?>

<div class="container">
  <div class="card p-4 mb-3">
    <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
      <div>
        <h5 class="page-title mb-1">Reports</h5>
        <div class="text-muted small">
          <?= $isAdmin ? 'Admin summary (system-wide).' : 'Staff summary (your activity only).' ?>
        </div>
      </div>

      <form method="get" class="d-flex gap-2 flex-wrap align-items-end">
        <div>
          <label class="form-label mb-1 small">Start</label>
          <input type="date" name="start" class="form-control form-control-sm" value="<?= htmlspecialchars($start) ?>">
        </div>
        <div>
          <label class="form-label mb-1 small">End</label>
          <input type="date" name="end" class="form-control form-control-sm" value="<?= htmlspecialchars($end) ?>">
        </div>
        <button class="btn btn-sm btn-primary">Apply</button>
      </form>
    </div>
  </div>

  <div class="row g-3 mb-3">
    <div class="col-md-3">
      <div class="card p-3 h-100">
        <div class="text-muted small">Inspections</div>
        <div class="fs-3 fw-semibold"><?= (int)$sum['inspections'] ?></div>
      </div>
    </div>
    <div class="col-md-3">
      <div class="card p-3 h-100">
        <div class="text-muted small">Laundry Events</div>
        <div class="fs-3 fw-semibold"><?= (int)$sum['laundry_events'] ?></div>
      </div>
    </div>

    <?php if ($isAdmin): ?>
      <div class="col-md-3">
        <div class="card p-3 h-100">
          <div class="text-muted small">Tenants Added</div>
          <div class="fs-3 fw-semibold"><?= (int)$sum['tenants_added'] ?></div>
        </div>
      </div>
      <div class="col-md-3">
        <div class="card p-3 h-100">
          <div class="text-muted small">Units Added</div>
          <div class="fs-3 fw-semibold"><?= (int)$sum['units_added'] ?></div>
        </div>
      </div>
    <?php endif; ?>
  </div>

  <div class="card p-4">
    <h6 class="mb-2">Exports</h6>
    <div class="text-muted small mb-3">CSV works in Excel/Google Sheets and is cPanel-friendly.</div>

    <div class="d-flex gap-2 flex-wrap">
      <a class="btn btn-outline-primary" href="<?= BASE_URL ?>/export_inspections.php?<?= q([]) ?>">Export Inspections CSV</a>
      <a class="btn btn-outline-primary" href="<?= BASE_URL ?>/export_laundry.php?<?= q([]) ?>">Export Laundry CSV</a>

      <?php if ($isAdmin): ?>
        <a class="btn btn-outline-secondary" href="<?= BASE_URL ?>/export_units.php?<?= q([]) ?>">Export Units CSV</a>
        <a class="btn btn-outline-secondary" href="<?= BASE_URL ?>/export_tenants.php?<?= q([]) ?>">Export Tenants CSV</a>
      <?php endif; ?>
    </div>

    <hr class="my-4">

    <h6 class="mb-2">Printable view</h6>
    <div class="text-muted small mb-3">Use browser Print → Save as PDF.</div>
    <button class="btn btn-outline-dark" onclick="window.print()">Print this page</button>
  </div>
</div>

<?php require_once __DIR__ . '/../app/views/partials/footer.php'; ?>
