<?php
declare(strict_types=1);
require_once __DIR__ . "/../config/db.php";
require_once __DIR__ . "/../config/auth.php";

require_login();

$u = current_user();
$uid = (int)($u['id'] ?? 0);
$role = (string)($u['role'] ?? 'REP');

$filter = (string)($_GET['filter'] ?? 'due'); // due, completed, all

$sql = "
SELECT 
  v.id, v.visit_date, v.followup_date, v.permission_status, v.authority_response,
  s.id AS school_id, s.name AS school_name,
  g.id AS gp_id, g.name AS gp_name,
  b.id AS block_id, b.name AS block_name,
  d.id AS district_id, d.name AS district_name,
  u.name AS visited_by_name,
  v.remarks,
  COALESCE(
    (SELECT followup_date FROM visits WHERE parent_visit_id = v.id ORDER BY visit_date DESC LIMIT 1),
    NULL
  ) AS last_followup_date
FROM visits v
JOIN schools s ON s.id=v.school_id
JOIN gps g ON g.id=v.gp_id
JOIN blocks b ON b.id=g.block_id
LEFT JOIN districts d ON d.id=b.district_id
JOIN users u ON u.id=v.visited_by
WHERE v.followup_required=1
";

$params = [];

// If REP, show only own followups
if ($role !== 'ADMIN') {
  $sql .= " AND v.visited_by=?";
  $params[] = $uid;
}

// Filter
if ($filter === 'due') {
  $sql .= " AND v.followup_date <= ?";
  $params[] = date('Y-m-d');
} elseif ($filter === 'completed') {
  $sql .= " AND v.followup_date < ?";
  $params[] = date('Y-m-d');
}

$sql .= " ORDER BY v.followup_date ASC, v.visit_date DESC LIMIT 1000";

$st = $pdo->prepare($sql);
$st->execute($params);
$followups = $st->fetchAll(PDO::FETCH_ASSOC);

// Count stats
$st_due = $pdo->prepare("
  SELECT COUNT(*) 
  FROM visits 
  WHERE followup_required=1 AND followup_date <= ?
  " . ($role !== 'ADMIN' ? " AND visited_by=?" : "")
);
$params_due = [date('Y-m-d')];
if ($role !== 'ADMIN') $params_due[] = $uid;
$st_due->execute($params_due);
$count_due = (int)($st_due->fetchColumn() ?? 0);

$page_title = "Follow-ups";
require_once __DIR__ . "/partials/header.php";
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h5 class="mb-0">Follow-ups</h5>
    <div class="text-muted small"><?= $count_due ?> due • Latest 1000 records</div>
  </div>
  <a class="btn btn-dark btn-sm" href="/school-crm/public/visit_add.php">+ Add Follow-up Visit</a>
</div>

<div class="card card-soft shadow-soft p-3 mb-3">
  <div class="btn-group" role="group">
    <a href="?filter=due" class="btn btn-sm <?= $filter === 'due' ? 'btn-dark' : 'btn-outline-dark' ?>">Due (<?= $count_due ?>)</a>
    <a href="?filter=all" class="btn btn-sm <?= $filter === 'all' ? 'btn-dark' : 'btn-outline-dark' ?>">All</a>
  </div>
</div>

<div class="card card-soft shadow-soft p-3">
  <div class="table-responsive">
    <table class="table table-hover align-middle mb-0 small">
      <thead>
        <tr>
          <th>School</th>
          <th>Initial Visit</th>
          <th>Follow-up Due</th>
          <th>Status</th>
          <th>Notes</th>
          <?php if ($role === 'ADMIN'): ?>
            <th>Assigned To</th>
          <?php endif; ?>
        </tr>
      </thead>
      <tbody>
        <?php if (!$followups): ?>
          <tr><td colspan="<?= $role === 'ADMIN' ? 6 : 5 ?>" class="text-muted text-center py-3">No follow-ups <?= $filter === 'due' ? 'due' : 'found' ?>.</td></tr>
        <?php endif; ?>

        <?php foreach ($followups as $f): $days_ago = (int)((strtotime(date('Y-m-d')) - strtotime($f['followup_date'])) / 86400); ?>
          <tr class="<?= $days_ago > 0 ? 'table-danger bg-opacity-10' : '' ?>">
            <td>
              <div class="fw-semibold"><?= htmlspecialchars($f['school_name']) ?></div>
              <div class="text-muted small"><?= htmlspecialchars($f['school_id']) ?></div>
            </td>
            <td class="text-nowrap"><?= htmlspecialchars($f['visit_date']) ?></td>
            <td class="text-nowrap">
              <span class="<?= $days_ago > 0 ? 'text-danger fw-semibold' : 'text-dark' ?>">
                <?= htmlspecialchars($f['followup_date']) ?>
                <?php if ($days_ago > 0): ?>
                  <br><small>(<?= $days_ago ?> days ago)</small>
                <?php endif; ?>
              </span>
            </td>
            <td>
              <span class="badge bg-warning text-dark"><?= htmlspecialchars($f['permission_status']) ?></span>
            </td>
            <td class="text-muted small"><?= htmlspecialchars(substr((string)$f['remarks'], 0, 30)) ?></td>
            <?php if ($role === 'ADMIN'): ?>
              <td><?= htmlspecialchars($f['visited_by_name']) ?></td>
            <?php endif; ?>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php require_once __DIR__ . "/partials/footer.php"; ?>