<?php
session_start();
if (!isset($_SESSION['unohs'])) {
    header("Location: index.php");
    exit();
}
include "conn.php";

$message = '';
if (isset($_GET['msg'])) {
    switch ($_GET['msg']) {
        case 'banned':   $message = '✅ User সফলভাবে Ban করা হয়েছে — এখন সে আর Login করতে পারবে না।'; break;
        case 'unbanned': $message = '✅ User সফলভাবে Unban করা হয়েছে।'; break;
        case 'error':     $message = '❌ কিছু একটা সমস্যা হয়েছে, আবার চেষ্টা করুন।'; break;
        case 'invalid':   $message = '❌ ভুল request।'; break;
    }
}

// ─────────────────────────────────────────────
// Search (mobile number দিয়ে) — না দিলে সাম্প্রতিক ৫০ জন দেখাবে
// ─────────────────────────────────────────────
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$users = [];

if ($search !== '') {
    $searchParam = "%" . $search . "%";
    $stmt = $conn->prepare("
        SELECT s.id, s.mobile, s.owncode, s.status, s.createdate,
               COALESCE(k.motta, 0) AS coin_balance,
               COALESCE((SELECT SUM(t.motta) FROM thevani t WHERE t.balakedara = s.id AND t.sthiti = 1), 0) AS total_deposit,
               COALESCE((SELECT SUM(w.motta) FROM hintegedukolli w WHERE w.balakedara = s.id AND w.sthiti = 1), 0) AS total_withdraw
        FROM shonu_subjects s
        LEFT JOIN shonu_kaichila k ON k.balakedara = s.id
        WHERE s.mobile LIKE ? OR s.owncode LIKE ?
        ORDER BY s.createdate DESC
        LIMIT 50
    ");
    $stmt->bind_param("ss", $searchParam, $searchParam);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) { $users[] = $row; }
    $stmt->close();
} else {
    $result = $conn->query("
        SELECT s.id, s.mobile, s.owncode, s.status, s.createdate,
               COALESCE(k.motta, 0) AS coin_balance,
               COALESCE((SELECT SUM(t.motta) FROM thevani t WHERE t.balakedara = s.id AND t.sthiti = 1), 0) AS total_deposit,
               COALESCE((SELECT SUM(w.motta) FROM hintegedukolli w WHERE w.balakedara = s.id AND w.sthiti = 1), 0) AS total_withdraw
        FROM shonu_subjects s
        LEFT JOIN shonu_kaichila k ON k.balakedara = s.id
        ORDER BY s.createdate DESC
        LIMIT 50
    ");
    if ($result) {
        while ($row = $result->fetch_assoc()) { $users[] = $row; }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Users - RAJ365 Admin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="admin-gold-theme.css">
    <style>
        body { background: #0A0A0A; padding: 20px; }
        .user-card {
            background: #171512;
            border: 1px solid rgba(212,175,55,.25);
            border-radius: 14px;
            padding: 14px 18px;
            margin-bottom: 12px;
        }
        .user-card.banned { opacity: .55; border-color: rgba(220,38,38,.4); }
        .status-badge {
            font-size: 11px; font-weight: 700; padding: 3px 10px;
            border-radius: 999px; letter-spacing: .3px;
        }
        .status-active { background: rgba(31,185,121,.15); color: #1FB979; }
        .status-banned { background: rgba(220,38,38,.15); color: #E8544A; }
        .user-meta { color: #8A8270; font-size: 12.5px; }
        .user-name { color: #F5EFDC; font-weight: 700; font-size: 15px; }
        .search-box {
            background: #171512; border: 1px solid #3A3226; color: #F5EFDC;
            border-radius: 10px; padding: 8px 14px; width: 100%;
        }
    </style>
</head>
<body>
<div class="container" style="max-width:720px;">
    <h3 style="color:#D4AF37; margin-bottom:20px;">👤 Manage Users</h3>

    <?php if ($message): ?>
        <div class="alert" style="background:#171512; border:1px solid #D4AF37; color:#F5EFDC;">
            <?= htmlspecialchars($message) ?>
        </div>
    <?php endif; ?>

    <form method="GET" style="margin-bottom:18px; display:flex; gap:8px;">
        <input type="text" name="search" class="search-box" placeholder="Mobile number বা Code দিয়ে খুঁজো..."
               value="<?= htmlspecialchars($search) ?>">
        <button type="submit" class="btn" style="background:#D4AF37; color:#1A1400; font-weight:700; border-radius:10px;">খুঁজো</button>
    </form>

    <?php if (empty($users)): ?>
        <p style="color:#8A8270;">কোনো User পাওয়া যায়নি।</p>
    <?php else: ?>
        <?php if ($search === ''): ?>
            <p class="user-meta" style="margin-bottom:12px;">সাম্প্রতিক ৫০ জন দেখানো হচ্ছে — নির্দিষ্ট কাউকে খুঁজতে উপরে Mobile number লিখো।</p>
        <?php endif; ?>
        <?php foreach ($users as $user): ?>
            <?php $isActive = intval($user['status']) === 1; // Login.php-এ verified: status==1 হলেই শুধু login সফল হয় ?>
            <div class="user-card <?= $isActive ? '' : 'banned' ?>">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="user-name">
                            <?= htmlspecialchars($user['mobile']) ?>
                            <span class="status-badge <?= $isActive ? 'status-active' : 'status-banned' ?>">
                                <?= $isActive ? 'ACTIVE' : 'BANNED' ?>
                            </span>
                        </div>
                        <div class="user-meta">
                            🆔 UID: <?= htmlspecialchars($user['id']) ?>
                            &nbsp;|&nbsp; Code: <?= htmlspecialchars($user['owncode']) ?>
                            &nbsp;|&nbsp; যোগদান: <?= htmlspecialchars($user['createdate']) ?>
                        </div>
                        <div style="display:flex; gap:14px; margin-top:6px; flex-wrap:wrap;">
                            <span style="color:#D4AF37; font-weight:700; font-size:13px;">
                                🪙 Balance: <?= number_format((float)$user['coin_balance'], 2) ?>
                            </span>
                            <span style="color:#1FB979; font-weight:600; font-size:13px;">
                                ⬇ Total Deposit: <?= number_format((float)$user['total_deposit'], 2) ?>
                            </span>
                            <span style="color:#E8544A; font-weight:600; font-size:13px;">
                                ⬆ Total Withdraw: <?= number_format((float)$user['total_withdraw'], 2) ?>
                            </span>
                        </div>
                    </div>
                    <form method="POST" action="ban_user.php"
                          onsubmit="return confirm('<?= $isActive ? "এই User-কে Ban করতে চান? সে আর Login করতে পারবে না।" : "এই User-কে Unban করতে চান?" ?>');">
                        <input type="hidden" name="user_id" value="<?= htmlspecialchars($user['id']) ?>">
                        <input type="hidden" name="new_status" value="<?= $isActive ? 0 : 1 ?>">
                        <input type="hidden" name="search" value="<?= htmlspecialchars($search) ?>">
                        <?php if ($isActive): ?>
                            <button type="submit" class="btn btn-sm" style="background:#E8544A; color:#fff; border-radius:8px; font-weight:600;">Ban</button>
                        <?php else: ?>
                            <button type="submit" class="btn btn-sm" style="background:#1FB979; color:#fff; border-radius:8px; font-weight:600;">Unban</button>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <a href="dashboard.php" style="color:#D4AF37;">← Dashboard-এ ফিরে যান</a>
</div>
</body>
</html>
