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

if (isset($_GET['unban']) && is_numeric($_GET['unban'])) {
    $member_id = (int)$_GET['unban'];
    $delete = mysqli_query($conn, "DELETE FROM warnings WHERE member_id = $member_id");
    $_SESSION['warning_message'] = $delete ? 'Warnings cleared for member ID: ' . $member_id : 'Failed to unban member.';
    header("Location: warnings.php");
    exit;
}

$result = mysqli_query($conn, "
    SELECT m.id, m.first_name, m.surname, m.phone,
        COUNT(w.id) AS total_warnings,
        MAX(CASE w.warning_level
            WHEN 'Final' THEN 3
            WHEN 'Second' THEN 2
            WHEN 'First' THEN 1
            ELSE 0 END
        ) AS max_level
    FROM members m
    JOIN warnings w ON m.id = w.member_id
    GROUP BY m.id
    ORDER BY total_warnings DESC
");

include 'includes/header.php';
?>

<div class="container my-4">
    <h2>Members with Warnings</h2>

    <?php if (isset($_SESSION['warning_message'])): ?>
        <div class="alert alert-info"> <?= $_SESSION['warning_message']; unset($_SESSION['warning_message']); ?> </div>
    <?php endif; ?>

    <div class="table-responsive">
        <table class="table table-bordered table-hover">
            <thead class="table-dark">
                <tr>
                    <th>Member ID</th>
                    <th>Name</th>
                    <th>Phone</th>
                    <th>Total Warnings</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php while($row = mysqli_fetch_assoc($result)): ?>
                <?php
                    $status = 'First';
                    if ($row['max_level'] == 2) $status = 'Second';
                    elseif ($row['max_level'] == 3) $status = 'Final';
                ?>
                <tr>
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['first_name'] . ' ' . $row['surname']) ?></td>
                    <td><?= htmlspecialchars($row['phone']) ?></td>
                    <td><span class="badge bg-dark"><?= $row['total_warnings'] ?></span></td>
                    <td><span class="badge bg-warning text-dark"><?= $status ?></span></td>
                    <td>
                        <button class="btn btn-sm btn-info view-warnings-btn" 
                                data-member-id="<?= $row['id'] ?>" 
                                data-member-name="<?= htmlspecialchars($row['first_name'] . ' ' . $row['surname']) ?>">View Warnings</button>
                        <a href="?unban=<?= $row['id'] ?>" class="btn btn-sm btn-success" onclick="return confirm('Are you sure you want to unban this member?');">Unban</a>
                    </td>
                </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- View Warnings Modal -->
<div class="modal fade" id="viewWarningsModal" tabindex="-1" aria-labelledby="viewWarningsModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="viewWarningsModalLabel">Warnings</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="warningsContent">
        Loading warnings...
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.view-warnings-btn').forEach(button => {
        button.addEventListener('click', () => {
            const memberId = button.getAttribute('data-member-id');
            const name = button.getAttribute('data-member-name');

            fetch(`fetch_warnings.php?member_id=${memberId}`)
                .then(response => response.text())
                .then(html => {
                    document.getElementById('viewWarningsModalLabel').innerText = `Warnings for ${name}`;
                    document.getElementById('warningsContent').innerHTML = html;
                    new bootstrap.Modal(document.getElementById('viewWarningsModal')).show();
                });
        });
    });
});
</script>

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