<?php
session_start();
require_once "../configs.php";

if (!isset($_SESSION['admin'])) {
    header("Location: admin_login.php");
    exit;
}

/* ================= DELETE USER (AJAX) ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    $id = intval($_POST['delete_id']);

    $q = $conn->prepare("SELECT email FROM customers WHERE id=? LIMIT 1");
    $q->bind_param("i",$id);
    $q->execute();
    $email = $q->get_result()->fetch_assoc()['email'] ?? null;
    $q->close();

    if ($email) {
        $conn->query("DELETE FROM balance WHERE user='".$conn->real_escape_string($email)."'");
    }

    $del = $conn->prepare("DELETE FROM customers WHERE id=? LIMIT 1");
    $del->bind_param("i",$id);
    $del->execute();
    $del->close();
    exit("ok");
}

/* ================= SEARCH USERS (AJAX) ================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search'])) {
    $search = trim($_POST['search']);

    $stmt = $conn->prepare("
        SELECT c.*, IFNULL(b.amount,0) balance
        FROM customers c
        LEFT JOIN balance b ON b.user = c.email
        WHERE c.email LIKE CONCAT('%',?,'%')
        ORDER BY c.id DESC
        LIMIT 100
    ");
    $stmt->bind_param("s",$search);
    $stmt->execute();
    $res = $stmt->get_result();

    while($u = $res->fetch_assoc()):
?>
<tr id="row<?= $u['id'] ?>">
<td><?= htmlspecialchars($u['full_name']) ?></td>
<td><?= htmlspecialchars($u['email']) ?></td>
<td>₦<?= number_format($u['balance'],2) ?></td>
<td>
<span class="badge <?= $u['is_active'] ? 'active':'inactive' ?>">
<?= $u['is_active'] ? 'Active':'Inactive' ?>
</span>
</td>
<td><?= $u['last_login'] ? date("d M Y H:i",strtotime($u['last_login'])) : 'Never' ?></td>
<td>
<button class="btn del" onclick="deleteUser(<?= $u['id'] ?>)">Delete</button>
</td>
</tr>
<?php
    endwhile;
    exit;
}

/* ================= STATS ================= */
$totalUsers = $conn->query("SELECT COUNT(*) c FROM customers")->fetch_assoc()['c'];
$activeUsers = $conn->query("SELECT COUNT(*) c FROM customers WHERE is_active=1")->fetch_assoc()['c'];
$inactiveUsers = $conn->query("SELECT COUNT(*) c FROM customers WHERE is_active=0")->fetch_assoc()['c'];
$todayLogins = $conn->query("
    SELECT COUNT(*) c 
    FROM customers 
    WHERE last_login IS NOT NULL 
    AND DATE(last_login) = CURDATE()
")->fetch_assoc()['c'];

/* ================= USERS LIST ================= */
$users = $conn->query("
    SELECT c.*, IFNULL(b.amount,0) balance
    FROM customers c
    LEFT JOIN balance b ON b.user = c.email
    ORDER BY c.id DESC
    LIMIT 200
");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Admin Users</title>
<meta name="viewport" content="width=device-width,initial-scale=1">

<style>
body{margin:0;font-family:Inter,Arial;background:#0f172a;color:#fff;padding:20px}
h2{margin-bottom:12px}
.stats{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(180px,1fr));
    gap:14px;
    margin-bottom:18px
}
.box{
    background:#020617;
    padding:16px;
    border-radius:14px;
    text-align:center;
    box-shadow:0 6px 20px rgba(0,0,0,.4)
}
.box h3{margin:0;font-size:26px}
.box span{font-size:13px;color:#94a3b8}

.search{margin-bottom:14px}
.search input{
    width:100%;
    max-width:340px;
    padding:12px;
    border-radius:10px;
    border:none;
    outline:none;
    font-size:14px
}

table{width:100%;border-collapse:collapse;font-size:14px}
th,td{
    padding:10px;
    border-bottom:1px solid rgba(255,255,255,.08);
    text-align:left
}
th{color:#93c5fd}

.badge{
    padding:4px 12px;
    border-radius:999px;
    font-size:12px;
    font-weight:700
}
.active{background:#22c55e;color:#022c22}
.inactive{background:#ef4444}

.btn{
    padding:6px 12px;
    border:none;
    border-radius:8px;
    cursor:pointer;
    font-weight:700
}
.del{background:#ef4444;color:#fff}

@media(max-width:900px){
    table{font-size:13px}
}
</style>
</head>
<body>

<h2>User Management</h2>

<div class="stats">
    <div class="box">
        <h3><?= $totalUsers ?></h3>
        <span>Total Users</span>
    </div>
    <div class="box">
        <h3><?= $activeUsers ?></h3>
        <span>Active Users</span>
    </div>
    <div class="box">
        <h3><?= $inactiveUsers ?></h3>
        <span>Inactive Users</span>
    </div>
    <div class="box">
        <h3><?= $todayLogins ?></h3>
        <span>Logged In Today</span>
    </div>
</div>

<div class="search">
    <input type="text" id="searchEmail" placeholder="Search user by email…">
</div>

<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Balance</th>
<th>Status</th>
<th>Last Login</th>
<th>Action</th>
</tr>
</thead>
<tbody id="userTable">
<?php while($u=$users->fetch_assoc()): ?>
<tr id="row<?= $u['id'] ?>">
<td><?= htmlspecialchars($u['full_name']) ?></td>
<td><?= htmlspecialchars($u['email']) ?></td>
<td>₦<?= number_format($u['balance'],2) ?></td>
<td>
<span class="badge <?= $u['is_active'] ? 'active':'inactive' ?>">
<?= $u['is_active'] ? 'Active':'Inactive' ?>
</span>
</td>
<td><?= $u['last_login'] ? date("d M Y H:i",strtotime($u['last_login'])) : 'Never' ?></td>
<td>
<button class="btn del" onclick="deleteUser(<?= $u['id'] ?>)">Delete</button>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

<script>
function deleteUser(id){
    if(!confirm("Delete this user permanently?")) return;
    fetch("admin_users.php",{
        method:"POST",
        headers:{"Content-Type":"application/x-www-form-urlencoded"},
        body:"delete_id="+id
    }).then(()=>document.getElementById("row"+id)?.remove());
}

document.getElementById("searchEmail").addEventListener("keyup",function(){
    fetch("admin_users.php",{
        method:"POST",
        headers:{"Content-Type":"application/x-www-form-urlencoded"},
        body:"search="+encodeURIComponent(this.value)
    })
    .then(r=>r.text())
    .then(html=>{
        document.getElementById("userTable").innerHTML = html;
    });
});
</script>

</body>
</html>