<?php
session_start();
if (!isset($_SESSION['admin_id']) && $_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit();
}
include '../../include/config.php';

$users = $conn->query("
    SELECT p.*, 
           (SELECT COUNT(*) FROM hps_subscriptions WHERE user_id = p.patient_id) as subscription_count,
           (SELECT SUM(amount_invested) FROM hps_user_investments WHERE user_id = p.patient_id) as total_invested
    FROM patients p
    ORDER BY p.created_at DESC
");

$page_title = 'HPS Users Management';
include '../../include/header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HPS Users - Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
    <div class="d-flex justify-content-between mb-4">
        <h2><i class="fas fa-users me-2"></i> HPS Users</h2>
        <a href="dashboard.php" class="btn btn-secondary">← Back</a>
    </div>

    <div class="card shadow">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr><th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Status</th><th>Subscriptions</th><th>Invested</th><th>Joined</th><th>Action</th></tr>
                    </thead>
                    <tbody>
                        <?php while($u = $users->fetch_assoc()): ?>
                        <tr>
                            <td><?= $u['patient_id'] ?></td
                            <td><?= htmlspecialchars($u['first_name'] . ' ' . $u['last_name']) ?></td
                            <td><?= htmlspecialchars($u['email']) ?></td
                            <td><?= htmlspecialchars($u['phone']) ?></td
                            <td>
                                <span class="badge bg-<?= $u['status'] == 'active' ? 'success' : 'warning' ?>">
                                    <?= ucfirst($u['status']) ?>
                                </span>
                             </td
                            <td><?= $u['subscription_count'] ?></td
                            <td>₦<?= number_format($u['total_invested'] ?? 0, 2) ?></td
                            <td><?= date('M d, Y', strtotime($u['created_at'])) ?></td
                            <td>
                                <button class="btn btn-sm btn-info" onclick="viewUser(<?= $u['patient_id'] ?>)">View</button>
                             </td
                          </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<script>
function viewUser(id) {
    window.location.href = 'user_details.php?id=' + id;
}
</script>
<?php include '../../include/footer.php'; ?>