<?php
$pageTitle = 'Members List';
require_once __DIR__ . '/includes/header.php';
$db = getDB();
$members = $db->query("
    SELECT m.*,
           (SELECT COALESCE(SUM(CASE WHEN type='earn' THEN points ELSE -points END),0)
            FROM transactions WHERE member_id = m.id) AS balance
    FROM members m
    ORDER BY m.created_at DESC
")->fetchAll();
?>

<div class="card shadow-sm">
  <div class="card-header bg-white d-flex justify-content-between align-items-center">
    <span><i class="bi bi-people me-2 text-primary"></i>All Members (<?= count($members) ?>)</span>
    <div class="d-flex gap-2">
      <a href="<?= BASE_URL ?>/ajax/export_csv.php?type=members" class="btn btn-sm btn-outline-success">
        <i class="bi bi-download me-1"></i>Export CSV
      </a>
      <button class="btn btn-sm btn-outline-secondary" onclick="window.print()">
        <i class="bi bi-printer me-1"></i>Print
      </button>
      <a href="<?= BASE_URL ?>/card-generator.php" class="btn btn-sm btn-primary">
        <i class="bi bi-plus-lg me-1"></i>New Card
      </a>
    </div>
  </div>
  <div class="table-responsive">
    <table class="table table-hover align-middle mb-0" id="membersTable">
      <thead class="table-light">
        <tr>
          <th>#</th>
          <th>Card Code</th>
          <th>Name</th>
          <th>Phone</th>
          <th>Points Balance</th>
          <th>Status</th>
          <th>Registered</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($members as $m): ?>
        <tr>
          <td class="text-muted small"><?= $m['id'] ?></td>
          <td><code class="small"><?= e($m['card_code']) ?></code></td>
          <td class="fw-semibold"><?= $m['name'] ? e($m['name']) : '<span class="text-muted fst-italic">Unregistered</span>' ?></td>
          <td><?= $m['phone'] ? e($m['phone']) : '—' ?></td>
          <td>
            <span class="badge bg-<?= $m['balance'] > 0 ? 'warning text-dark' : 'secondary' ?>">
              <?= number_format(max(0,(int)$m['balance'])) ?> pts
            </span>
          </td>
          <td>
            <span class="badge bg-<?= $m['status']==='active' ? 'success' : 'danger' ?>">
              <?= ucfirst($m['status']) ?>
            </span>
          </td>
          <td class="small text-muted">
            <?= $m['registered_at'] ? date('M d, Y', strtotime($m['registered_at'])) : '—' ?>
          </td>
          <td>
            <div class="btn-group btn-group-sm">
              <a href="<?= BASE_URL ?>/member-registration.php?card=<?= urlencode($m['card_code']) ?>"
                 class="btn btn-outline-primary" title="Edit">
                <i class="bi bi-pencil"></i>
              </a>
              <a href="<?= BASE_URL ?>/purchase-scanner.php" class="btn btn-outline-success" title="Purchase">
                <i class="bi bi-bag-check"></i>
              </a>
              <?php if (isAdmin()): ?>
              <button class="btn btn-outline-danger btn-delete" data-id="<?= $m['id'] ?>"
                      data-name="<?= e($m['name'] ?? $m['card_code']) ?>" title="Delete">
                <i class="bi bi-trash"></i>
              </button>
              <?php endif; ?>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- Delete confirm modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered modal-sm">
    <div class="modal-content">
      <div class="modal-header">
        <h6 class="modal-title fw-bold"><i class="bi bi-exclamation-triangle text-danger me-2"></i>Confirm Delete</h6>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body small">
        Delete member <strong id="deleteName"></strong>? All transaction history will also be removed.
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-sm btn-danger" id="confirmDelete">Delete</button>
      </div>
    </div>
  </div>
</div>

<?php
$jsBaseUrl = json_encode(BASE_URL);
$extraJS   = '<script>const BASE_URL=' . $jsBaseUrl . ';</script>' . <<<'ENDJS'
<script>
$(function() {
    $('#membersTable').DataTable({
        order:       [[0, 'desc']],
        pageLength:  25,
        columnDefs:  [{ orderable: false, targets: [7] }]
    });

    var deleteId = null;
    $(document).on('click', '.btn-delete', function() {
        deleteId = $(this).data('id');
        document.getElementById('deleteName').textContent = $(this).data('name');
        new bootstrap.Modal(document.getElementById('deleteModal')).show();
    });

    document.getElementById('confirmDelete').addEventListener('click', function() {
        if (!deleteId) return;
        $.post(BASE_URL + '/ajax/delete_member.php', { id: deleteId }, function(res) {
            if (res.success) { location.reload(); }
            else { alert(res.error || 'Delete failed'); }
        }, 'json');
    });
});
</script>
ENDJS;
require_once __DIR__ . '/includes/footer.php';
