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

$start_date = (string)($_GET['start_date'] ?? date('Y-m-01'));
$end_date   = (string)($_GET['end_date'] ?? date('Y-m-d'));
$gp_id      = strtoupper(trim((string)($_GET['gp_id'] ?? '')));
$school_id  = trim((string)($_GET['school_id'] ?? ''));
$status     = (string)($_GET['status'] ?? '');

$sql = "
SELECT 
  v.id, v.visit_date, v.permission_status, v.authority_response, v.followup_required, v.followup_date,
  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
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 1=1
";

$params = [];

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

// Date filter
if ($start_date !== '') {
  $sql .= " AND v.visit_date >= ?";
  $params[] = $start_date;
}
if ($end_date !== '') {
  $sql .= " AND v.visit_date <= ?";
  $params[] = $end_date;
}

// GP filter
if ($gp_id !== '') {
  $sql .= " AND v.gp_id=?";
  $params[] = $gp_id;
}

// School filter
if ($school_id !== '') {
  $sql .= " AND v.school_id LIKE ?";
  $params[] = "%{$school_id}%";
}

// Permission status filter
if ($status !== '') {
  $sql .= " AND v.permission_status=?";
  $params[] = $status;
}

$sql .= " ORDER BY v.visit_date DESC, v.id DESC LIMIT 2000";

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

$page_title = "Visits";
require_once __DIR__ . "/partials/header.php";
?>

<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h5 class="mb-0">Visits</h5>
    <div class="text-muted small">Latest 2000 records</div>
  </div>
  <a class="btn btn-dark btn-sm" href="/school-crm/public/visit_add.php">+ Add Visit</a>
</div>

<?php if ($role === 'ADMIN'): ?>
<div class="card card-soft shadow-soft p-3 mb-3">
  <form class="row g-2" method="get">
    <div class="col-12 col-md-2">
      <label class="form-label small">Start Date</label>
      <input type="date" class="form-control form-control-sm" name="start_date" value="<?= htmlspecialchars($start_date) ?>">
    </div>
    <div class="col-12 col-md-2">
      <label class="form-label small">End Date</label>
      <input type="date" class="form-control form-control-sm" name="end_date" value="<?= htmlspecialchars($end_date) ?>">
    </div>
    <div class="col-12 col-md-2">
      <label class="form-label small">GP</label>
      <input type="text" class="form-control form-control-sm" name="gp_id" value="<?= htmlspecialchars($gp_id) ?>" placeholder="GP ID">
    </div>
    <div class="col-12 col-md-2">
      <label class="form-label small">School</label>
      <input type="text" class="form-control form-control-sm" name="school_id" value="<?= htmlspecialchars($school_id) ?>" placeholder="School ID">
    </div>
    <div class="col-12 col-md-2">
      <label class="form-label small">Status</label>
      <select class="form-select form-select-sm" name="status">
        <option value="">All</option>
        <option value="APPROVED" <?= $status === 'APPROVED' ? 'selected' : '' ?>>Approved</option>
        <option value="PENDING" <?= $status === 'PENDING' ? 'selected' : '' ?>>Pending</option>
        <option value="REJECTED" <?= $status === 'REJECTED' ? 'selected' : '' ?>>Rejected</option>
      </select>
    </div>
    <div class="col-12 col-md-2 d-grid">
      <button class="btn btn-outline-dark btn-sm">Filter</button>
    </div>
  </form>
</div>
<?php endif; ?>

<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>Date</th>
          <th>School</th>
          <th>GP / Block</th>
          <th>Permission</th>
          <th>Follow-up</th>
          <?php if ($role === 'ADMIN'): ?>
            <th>Visited By</th>
          <?php endif; ?>
          <th>Notes</th>
        </tr>
      </thead>
      <tbody>
        <?php if (!$visits): ?>
          <tr><td colspan="<?= $role === 'ADMIN' ? 7 : 6 ?>" class="text-muted text-center py-3">No visits found.</td></tr>
        <?php endif; ?>

        <?php foreach ($visits as $v): ?>
          <tr>
            <td class="text-nowrap fw-semibold"><?= htmlspecialchars(substr((string)$v['visit_date'], 0, 10)) ?></td>
            <td>
              <div class="fw-semibold"><?= htmlspecialchars($v['school_name']) ?></div>
              <div class="text-muted small"><?= htmlspecialchars($v['school_id']) ?></div>
            </td>
            <td>
              <div><?= htmlspecialchars($v['gp_name']) ?></div>
              <div class="text-muted small"><?= htmlspecialchars($v['block_name'] . ' / ' . ($v['district_name'] ?? '')) ?></div>
            </td>
            <td>
              <span class="badge <?= $v['permission_status'] === 'APPROVED' ? 'bg-success' : ($v['permission_status'] === 'REJECTED' ? 'bg-danger' : 'bg-warning') ?>">
                <?= htmlspecialchars($v['permission_status']) ?>
              </span>
            </td>
            <td>
              <?php if ((int)$v['followup_required'] === 1): ?>
                <span class="badge bg-info">Due: <?= htmlspecialchars((string)$v['followup_date']) ?></span>
              <?php else: ?>
                <span class="text-muted">—</span>
              <?php endif; ?>
            </td>
            <?php if ($role === 'ADMIN'): ?>
              <td><?= htmlspecialchars($v['visited_by_name']) ?></td>
            <?php endif; ?>
            <td class="text-muted small"><?= htmlspecialchars(substr((string)$v['remarks'], 0, 30)) ?></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

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