<?php
session_start();
include 'includes/auth.php';
include 'includes/db.php';

// Get search string
$search = mysqli_real_escape_string($conn, $_GET['search'] ?? '');

// Base WHERE clause
$where = "WHERE 1"; // Always true, allows safe appending

if (!empty($search)) {
    $where .= " AND (
        CAST(member_number AS CHAR) = '$search' OR
        CONCAT(first_name, ' ', surname) LIKE '%$search%' OR 
        nfc_uid LIKE '%$search%'
    )";
}

// Pagination
$limit = 15;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;

// Count and fetch
$total = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) AS count FROM members $where"))['count'];
$total_pages = ceil($total / $limit);

$sql = "SELECT m.*, 
           (SELECT COUNT(*) FROM warnings w WHERE w.member_id = m.id) AS warnings_count
        FROM members m 
        $where 
        ORDER BY m.member_number DESC 
        LIMIT $offset, $limit";
$result = mysqli_query($conn, $sql);
 

include 'includes/header.php';
?>

<h2>All Members</h2>

<form class="row mb-3" method="get">
  <div class="col-md-4">
    <input type="text" name="search" class="form-control" placeholder="Search by name or Member number" value="<?= htmlspecialchars($search) ?>">
  </div>
  <div class="col-md-2">
    <button class="btn btn-primary w-100"><i class="fas fa-search"></i> Search</button>
  </div>
</form>

<div class="table-responsive">
    <table class="table table-bordered table-striped table-sm">
        <thead class="table-dark">
            <tr>
                <th>Member #</th>
                <th>Name</th>
                <th>Phone</th>
                <th>Expiry Date</th>
                <th>Payment Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if (mysqli_num_rows($result) == 0) { ?>
                <tr>
                    <td colspan="6" class="text-center">No members expiring soon</td>
                </tr>
            <?php } else {
                while ($row = mysqli_fetch_assoc($result)) {
                    $expiry = ($row['expiry_date'] && $row['expiry_date'] != '0000-00-00')
                        ? date('d/m/Y', strtotime($row['expiry_date']))
                        : '';
            ?>
<?php
$status = strtolower($row['payment_status']);
$row_class = '';

if ($status === 'ok') {
    $row_class = 'table-success';
} elseif ($status === 'due') {
    $row_class = 'table-warning';
} elseif ($status === 'expired') {
    $row_class = 'table-danger';
}
?>

<tr class="<?php echo $row_class; ?>">
                    <td><?php echo htmlspecialchars($row['member_number']); ?></td>
                    <td><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['surname']); ?></td>
                    <td><?php echo htmlspecialchars($row['phone']); ?></td>
                    <td><?php echo $expiry; ?></td>
                    <td><?php echo htmlspecialchars($row['payment_status']); ?></td>
                    <td>
                        <a href="edit_member.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-warning" title="Edit">
                            <i class="fas fa-edit"></i>
                        </a>
                        <a href="view_member.php?id=<?php echo $row['id']; ?>" class="btn btn-sm btn-info" title="View">
                            <i class="fas fa-eye"></i> View
                        </a>
                    </td>
                </tr>
            <?php }} ?>
        </tbody>
    </table>
</div>



<!-- Pagination -->
<nav>
  <ul class="pagination">
    <?php if ($page > 1): ?>
      <li class="page-item"><a class="page-link" href="?search=<?php echo urlencode($search); ?>&page=<?php echo $page-1; ?>">Previous</a></li>
    <?php endif; ?>

    <?php
    $start = max(1, $page - 2);
    $end = min($total_pages, $page + 2);

    if ($start > 1) {
        echo '<li class="page-item"><a class="page-link" href="?search='.urlencode($search).'&page=1">1</a></li>';
        if ($start > 2) echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
    }

    for ($i = $start; $i <= $end; $i++) {
        $active = ($i == $page) ? 'active' : '';
        echo '<li class="page-item '.$active.'"><a class="page-link" href="?search='.urlencode($search).'&page='.$i.'">'.$i.'</a></li>';
    }

    if ($end < $total_pages) {
        if ($end < $total_pages - 1) echo '<li class="page-item disabled"><span class="page-link">...</span></li>';
        echo '<li class="page-item"><a class="page-link" href="?search='.urlencode($search).'&page='.$total_pages.'">'.$total_pages.'</a></li>';
    }
    ?>

    <?php if ($page < $total_pages): ?>
      <li class="page-item"><a class="page-link" href="?search=<?php echo urlencode($search); ?>&page=<?php echo $page+1; ?>">Next</a></li>
    <?php endif; ?>
  </ul>
</nav>

<!-- NFC Modal -->
<div class="modal fade" id="nfcModal" tabindex="-1">
  <div class="modal-dialog">
    <form method="POST" action="assign_card.php" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Assign NFC Card</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p>Assigning card to <strong id="nfcMemberName"></strong></p>
        <input type="hidden" name="member_id" id="nfcMemberId">
        <input type="text" name="uid" id="nfcUid" class="form-control" required>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success" type="submit">Assign</button>
      </div>
    </form>
  </div>
</div>

<!-- Warning Modal -->
<div class="modal fade" id="warningModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form method="POST" action="issue_warning.php" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="warningModalLabel">Issue Warning</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="member_id" id="warningMemberId">
        <p><strong>Member:</strong> <span id="warningMemberName"></span></p>
        <div class="mb-3">
          <label>Reason</label>
          <select name="reason" class="form-select" id="warningReason">
            <option value="Payment Issues">Payment Issues</option>
            <option value="Policy Violation">Policy Violation</option>
            <option value="Inappropriate Conduct">Inappropriate Conduct</option>
            <option value="Service Misuse">Service Misuse</option>
            <option value="Other">Other</option>
          </select>
        </div>
        <div class="mb-3" id="otherReasonGroup" style="display:none;">
          <label>Other Reason</label>
          <input type="text" id="otherReasonInput" class="form-control">
        </div>
        <div class="mb-3">
          <label>Details</label>
          <textarea name="details" class="form-control" required></textarea>
        </div>
        <div class="mb-3">
          <label>Action Required</label>
          <input type="text" name="action_required" class="form-control">
        </div>
        <div class="mb-3">
          <label>Consequences</label>
          <input type="text" name="consequences" class="form-control">
        </div>
        <div class="mb-3">
          <label>Issued By</label>
          <input type="text" name="issued_by" class="form-control" value="Admin">
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-danger" type="submit">Issue Warning</button>
      </div>
    </form>
  </div>
</div>

<script>
document.querySelectorAll('.assign-nfc-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    document.getElementById('nfcMemberName').innerText = btn.dataset.name;
    document.getElementById('nfcMemberId').value = btn.dataset.id;
  });
});

document.querySelectorAll('.issue-warning-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    const name = btn.dataset.name;
    const warnings = parseInt(btn.dataset.warnings);
    document.getElementById('warningModalLabel').innerText = (warnings >= 2 ? 'Final Warning for ' : 'Issue Warning for ') + name;
    document.getElementById('warningMemberName').innerText = name;
    document.getElementById('warningMemberId').value = btn.dataset.id;
  });
});

document.getElementById('warningReason')?.addEventListener('change', function () {
  const otherGroup = document.getElementById('otherReasonGroup');
  const otherInput = document.getElementById('otherReasonInput');
  if (this.value === 'Other') {
    otherGroup.style.display = 'block';
    otherInput.name = 'reason';
  } else {
    otherGroup.style.display = 'none';
    otherInput.removeAttribute('name');
  }
});
</script>

<?php include 'includes/footer.php'; ?>
