<?php
require_once "../php/db_connect.php";

$limit = 6;
$pageNum = isset($_GET["p"]) && is_numeric($_GET["p"]) ? (int)$_GET["p"] : 1;
if ($pageNum < 1) $pageNum = 1;
$offset = ($pageNum - 1) * $limit;

$countSql = "SELECT COUNT(*) AS total FROM users WHERE role != 'superadmin'";
$countResult = $conn->query($countSql);
$totalUsers = 0;

if ($countResult && $row = $countResult->fetch_assoc()) {
    $totalUsers = (int)$row["total"];
}

$totalPages = max(1, ceil($totalUsers / $limit));

$sql = "SELECT id, first_name, last_name, username, mobile_number, role, created_at, status
        FROM users
        WHERE role != 'superadmin'
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$users = $stmt->get_result();

$message = $_GET["message"] ?? "";
?>

<div class="user-management-wrapper">
    <h1>User Management</h1>
    <p class="subtitle">Total Users: <strong><?php echo $totalUsers; ?></strong></p>

    <?php if ($message === "deactivated"): ?>
        <div class="alert success">User deactivated successfully.</div>
    <?php elseif ($message === "activated"): ?>
        <div class="alert success">User activated successfully.</div>
    <?php endif; ?>

    <div class="table-wrapper">
        <table>
            <thead>
                <tr>
                    <th>Full Name</th>
                    <th>Username</th>
                    <th>Contact Number</th>
                    <th>Role</th>
                    <th>Join Date</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($users && $users->num_rows > 0): ?>
                    <?php while ($user = $users->fetch_assoc()): ?>
                        <?php
                        $status = strtolower($user["status"] ?? "");
                        $statusClass = "status-default";

                        if ($status === "active") $statusClass = "status-active";
                        elseif ($status === "inactive") $statusClass = "status-inactive";
                        elseif ($status === "pending") $statusClass = "status-pending";
                        elseif ($status === "rejected") $statusClass = "status-rejected";
                        ?>
                        <tr>
                            <td><?php echo htmlspecialchars(trim(($user["first_name"] ?? "") . " " . ($user["last_name"] ?? ""))); ?></td>
                            <td><?php echo htmlspecialchars($user["username"] ?? ""); ?></td>
                            <td><?php echo htmlspecialchars($user["mobile_number"] ?? ""); ?></td>
                            <td><?php echo ucfirst(htmlspecialchars($user["role"] ?? "")); ?></td>
                            <td><?php echo htmlspecialchars(date("m/d/Y", strtotime($user["created_at"]))); ?></td>
                            <td>
                                <span class="<?php echo $statusClass; ?>">
                                    <?php echo ucfirst(htmlspecialchars($status)); ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($status === "active"): ?>
                                    <a class="deactivate-btn"
                                       href="superadmin-update-user-status.php?id=<?php echo (int)$user['id']; ?>&action=deactivate"
                                       onclick="return confirm('Deactivate this user?');">
                                       Deactivate
                                    </a>
                                <?php elseif ($status === "inactive"): ?>
                                    <a class="activate-btn"
                                       href="superadmin-update-user-status.php?id=<?php echo (int)$user['id']; ?>&action=activate"
                                       onclick="return confirm('Activate this user?');">
                                       Activate
                                    </a>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="7" class="no-data">No users found.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <div class="pagination">
            <a class="page-arrow <?php echo ($pageNum <= 1) ? 'disabled' : ''; ?>"
               href="<?php echo ($pageNum > 1) ? '?page=users&p=' . ($pageNum - 1) : '#'; ?>">
               &laquo;
            </a>

            <span>Page <?php echo $pageNum; ?> of <?php echo $totalPages; ?></span>

            <a class="page-arrow <?php echo ($pageNum >= $totalPages) ? 'disabled' : ''; ?>"
               href="<?php echo ($pageNum < $totalPages) ? '?page=users&p=' . ($pageNum + 1) : '#'; ?>">
               &raquo;
            </a>
        </div>
    </div>
</div>
<style>
.deactivate-btn {
    display: inline-block;
    padding: 6px 12px;
    background-color: #e74c3c; /* red */
    color: #fff;
    text-decoration: none;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    transition: 0.2s ease;
}

.deactivate-btn:hover {
    background-color: #c0392b;
}

.activate-btn {
    display: inline-block;
    padding: 6px 12px;
    background-color: #2ecc71;
    color: #fff;
    border-radius: 6px;
    text-decoration: none;
}
</style>
