<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: admin_login.php");
    exit();
}
require_once 'db.php';

// Handle user actions
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $user_id = intval($_POST['user_id']);
    $action  = $_POST['action'];

    if ($action == 'delete_user') {
        mysqli_begin_transaction($conn);
        try {
            mysqli_query($conn, "DELETE FROM deposits             WHERE user_id = $user_id");
            mysqli_query($conn, "DELETE FROM withdrawals          WHERE user_id = $user_id");
            mysqli_query($conn, "DELETE FROM profits              WHERE user_id = $user_id");
            // Delete commissions linked to this user's investments BEFORE deleting investments (FK constraint)
            mysqli_query($conn, "DELETE FROM referral_commissions WHERE investment_id IN (SELECT id FROM investments WHERE user_id = $user_id)");
            mysqli_query($conn, "DELETE FROM referral_commissions WHERE user_id = $user_id OR from_user_id = $user_id");
            mysqli_query($conn, "DELETE FROM investments          WHERE user_id = $user_id");
            $stmt = mysqli_prepare($conn, "DELETE FROM users WHERE id = ?");
            mysqli_stmt_bind_param($stmt, 'i', $user_id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_close($stmt);
            mysqli_commit($conn);
            $success = "User deleted successfully.";
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error = "Failed to delete user: " . $e->getMessage();
        }

    } elseif ($action == 'login_as_user') {
        $_SESSION['admin_session_backup'] = [
            'admin_logged_in' => $_SESSION['admin_logged_in'],
            'admin_username'  => $_SESSION['admin_username'] ?? 'admin',
        ];
        $_SESSION['user_id'] = $user_id;
        unset($_SESSION['admin_logged_in'], $_SESSION['admin_username']);
        header("Location: home.php");
        exit();

    } elseif ($action == 'adjust_balance') {
        $adjustment_type = $_POST['adjustment_type'];
        $amount          = abs(floatval($_POST['amount']));

        switch ($adjustment_type) {
            case 'add_deposit':
                $stmt = mysqli_prepare($conn,
                    "INSERT INTO deposits (user_id, amount, status, created_at) VALUES (?, ?, 'processed', NOW())");
                mysqli_stmt_bind_param($stmt, 'id', $user_id, $amount);
                $ok  = mysqli_stmt_execute($stmt);
                // Also credit balance directly
                if ($ok) mysqli_query($conn, "UPDATE users SET balance = balance + $amount WHERE id = $user_id");
                $success = $ok ? "Added ZMW " . number_format($amount, 2) . " deposit successfully." : null;
                $error   = $ok ? null : "Failed to add deposit.";
                mysqli_stmt_close($stmt);
                break;

            case 'deduct_balance':
                $stmt = mysqli_prepare($conn,
                    "INSERT INTO withdrawals (user_id, amount, status, created_at) VALUES (?, ?, 'processed', NOW())");
                mysqli_stmt_bind_param($stmt, 'id', $user_id, $amount);
                $ok  = mysqli_stmt_execute($stmt);
                if ($ok) mysqli_query($conn, "UPDATE users SET balance = GREATEST(0, balance - $amount) WHERE id = $user_id");
                $success = $ok ? "Deducted ZMW " . number_format($amount, 2) . " from balance successfully." : null;
                $error   = $ok ? null : "Failed to deduct balance.";
                mysqli_stmt_close($stmt);
                break;

            case 'add_profit':
                $stmt = mysqli_prepare($conn,
                    "INSERT INTO profits (user_id, amount, source, created_at) VALUES (?, ?, 'Admin Adjustment', NOW())");
                mysqli_stmt_bind_param($stmt, 'id', $user_id, $amount);
                $ok  = mysqli_stmt_execute($stmt);
                if ($ok) mysqli_query($conn, "UPDATE users SET balance = balance + $amount WHERE id = $user_id");
                $success = $ok ? "Added ZMW " . number_format($amount, 2) . " profit successfully." : null;
                $error   = $ok ? null : "Failed to add profit.";
                mysqli_stmt_close($stmt);
                break;

            case 'set_balance':
                // Directly set the user's balance to a specific amount
                $stmt = mysqli_prepare($conn, "UPDATE users SET balance = ? WHERE id = ?");
                mysqli_stmt_bind_param($stmt, 'di', $amount, $user_id);
                $ok      = mysqli_stmt_execute($stmt);
                $success = $ok ? "Balance set to ZMW " . number_format($amount, 2) . " successfully." : null;
                $error   = $ok ? null : "Failed to set balance.";
                mysqli_stmt_close($stmt);
                break;
        }

    } elseif ($action == 'ban_user') {
        $stmt = mysqli_prepare($conn, "UPDATE users SET banned = 1 WHERE id = ?");
        mysqli_stmt_bind_param($stmt, 'i', $user_id);
        $success = mysqli_stmt_execute($stmt) ? "User banned successfully." : null;
        $error   = $success ? null : "Failed to ban user.";
        mysqli_stmt_close($stmt);

    } elseif ($action == 'unban_user') {
        $stmt = mysqli_prepare($conn, "UPDATE users SET banned = 0 WHERE id = ?");
        mysqli_stmt_bind_param($stmt, 'i', $user_id);
        $success = mysqli_stmt_execute($stmt) ? "User unbanned successfully." : null;
        $error   = $success ? null : "Failed to unban user.";
        mysqli_stmt_close($stmt);
    }
}

// Ensure banned column exists
$cc = mysqli_query($conn, "SHOW COLUMNS FROM users LIKE 'banned'");
if (mysqli_num_rows($cc) == 0) {
    mysqli_query($conn, "ALTER TABLE users ADD COLUMN banned TINYINT(1) DEFAULT 0");
}

// ── Search ────────────────────────────────────────────────────────────────────
$search_phone = '';
$search_where = '';
if (!empty($_GET['search_phone'])) {
    $search_phone = mysqli_real_escape_string($conn, trim($_GET['search_phone']));
    $search_where = "WHERE u.phone_number LIKE '%$search_phone%'";
}

// ── Fetch users with stats ────────────────────────────────────────────────────
$users_query = "SELECT u.*,
                COALESCE((SELECT SUM(amount) FROM deposits    WHERE user_id = u.id AND status = 'processed'), 0)              AS total_deposits,
                COALESCE((SELECT SUM(amount) FROM withdrawals WHERE user_id = u.id AND status = 'processed'), 0)              AS total_withdrawals,
                COALESCE((SELECT SUM(amount) FROM profits     WHERE user_id = u.id), 0)                                       AS total_profits,
                COALESCE((SELECT SUM(amount) FROM investments WHERE user_id = u.id AND status IN ('running','active','')), 0) AS active_investments,
                COALESCE(u.banned, 0) AS banned
                FROM users u
                $search_where
                ORDER BY u.created_at DESC";
$users_result = mysqli_query($conn, $users_query);

// ── Global stats ──────────────────────────────────────────────────────────────
$stats = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT COUNT(*) AS total_users,
            COALESCE(SUM(CASE WHEN banned = 1 THEN 1 ELSE 0 END), 0) AS banned_users
     FROM users"));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Users - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            background-color: #000; color: #fff;
            font-family: Arial, sans-serif; font-size: 13px;
        }

        /* ── Header ── */
        .header {
            background: #111; padding: 12px 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.5);
            position: sticky; top: 0; z-index: 100;
            display: flex; align-items: center;
            justify-content: space-between;
        }
        .header-left { display: flex; align-items: center; gap: 15px; }
        .header h1  { color: #fff; font-size: 18px; }
        .back-btn   { color: #FFD700; text-decoration: none; font-size: 20px; }
        .logout-btn {
            background: #f87171; color: #fff;
            padding: 8px 15px; border-radius: 5px;
            text-decoration: none; font-size: 12px;
            display: flex; align-items: center; gap: 5px;
        }

        .container { padding: 12px; max-width: 1200px; margin: 0 auto; }

        /* ── Alerts ── */
        .alert {
            padding: 12px; border-radius: 8px;
            margin-bottom: 12px; font-size: 12px;
            display: flex; align-items: center; gap: 8px;
        }
        .alert-success { background:#1a4d1a; border:1px solid #2d7a2d; color:#4ade80; }
        .alert-error   { background:#4d1a1a; border:1px solid #7a2d2d; color:#f87171; }

        /* ── Stats ── */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
            gap: 10px; margin-bottom: 14px;
        }
        .stat-card { background:#111; padding:14px; border-radius:8px; text-align:center; }
        .stat-number { font-size:24px; font-weight:bold; color:#FFD700; margin-bottom:4px; }
        .stat-label  { color:#888; font-size:11px; }
        .stat-card.banned .stat-number { color:#f87171; }

        /* ── Search bar ── */
        .search-bar {
            display: flex; gap: 8px;
            margin-bottom: 14px;
        }
        .search-bar input {
            flex: 1; padding: 10px 14px;
            background: #111; border: 1px solid #333;
            border-radius: 8px; color: #fff; font-size: 13px;
        }
        .search-bar input:focus { outline: none; border-color: #FFD700; }
        .search-bar input::placeholder { color: #555; }
        .search-bar button {
            padding: 10px 18px;
            background: #FFD700; color: #000;
            border: none; border-radius: 8px;
            font-weight: bold; cursor: pointer; font-size: 13px;
            display: flex; align-items: center; gap: 6px;
        }
        .search-bar button:hover { background: #FFA500; }
        .search-bar .clear-btn {
            padding: 10px 14px;
            background: #222; color: #888;
            border: 1px solid #333; border-radius: 8px;
            text-decoration: none; font-size: 13px;
            display: flex; align-items: center; gap: 6px;
        }
        .search-bar .clear-btn:hover { border-color: #555; color: #fff; }
        .search-result-label {
            font-size: 11px; color: #888;
            margin-bottom: 10px; margin-top: -6px;
        }
        .search-result-label span { color: #FFD700; font-weight: bold; }

        /* ── User Cards ── */
        .users-list { display: flex; flex-direction: column; gap: 12px; }
        .user-card {
            background: #111; border-radius: 10px;
            padding: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.5);
            border-left: 4px solid #FFD700;
        }
        .user-card.banned { border-left-color: #f87171; opacity: 0.75; }

        .user-header {
            display: flex; justify-content: space-between;
            align-items: flex-start; margin-bottom: 12px;
        }
        .user-info { flex: 1; }
        .user-name  { font-size: 15px; font-weight: bold; color: #FFD700; margin-bottom: 5px; }
        .user-contact { font-size: 11px; color: #888; margin-top: 2px; }
        .user-status {
            padding: 5px 10px; border-radius: 5px;
            font-size: 10px; font-weight: bold; text-transform: uppercase;
        }
        .status-active { background: #4ade80; color: #000; }
        .status-banned { background: #f87171; color: #fff; }

        .user-stats {
            display: grid; grid-template-columns: repeat(2, 1fr);
            gap: 8px; margin-bottom: 12px;
            padding: 10px; background: #000; border-radius: 5px;
        }
        .stat-item {}
        .stat-item-label { color: #888; display: block; font-size: 10px; }
        .stat-item-value { color: #FFD700; font-weight: bold; font-size: 13px; }

        /* ── Action Buttons ── */
        .action-buttons {
            display: grid; grid-template-columns: repeat(2, 1fr);
            gap: 8px; margin-top: 12px;
        }
        .btn {
            padding: 8px; border: none; border-radius: 5px;
            font-weight: bold; cursor: pointer;
            display: flex; align-items: center;
            justify-content: center; gap: 5px;
            font-size: 11px; transition: all 0.3s;
            text-decoration: none; width: 100%;
        }
        .btn-login   { background:#FFD700; color:#000; }
        .btn-login:hover { background:#FFA500; }
        .btn-adjust  { background:#3b82f6; color:#fff; }
        .btn-adjust:hover { background:#2563eb; }
        .btn-ban     { background:#FFA500; color:#000; }
        .btn-ban:hover { background:#ff8800; }
        .btn-unban   { background:#4ade80; color:#000; }
        .btn-unban:hover { background:#22c55e; }
        .btn-delete  { background:#f87171; color:#fff; }
        .btn-delete:hover { background:#ef4444; }

        /* ── No results ── */
        .no-users { text-align:center; padding:40px; color:#555; }
        .no-users i { font-size:50px; margin-bottom:15px; opacity:0.3; display:block; }

        /* ── Modal ── */
        .modal {
            display: none; position: fixed; z-index: 1000;
            left: 0; top: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.85); overflow-y: auto;
        }
        .modal-content {
            background: #111; margin: 50px auto;
            padding: 20px; border: 1px solid #333;
            width: 90%; max-width: 480px;
            border-radius: 10px; position: relative;
        }
        .close {
            color: #888; float: right;
            font-size: 28px; font-weight: bold;
            cursor: pointer; line-height: 20px;
        }
        .close:hover { color: #fff; }
        .modal h2 { color: #FFD700; margin-bottom: 16px; font-size: 16px; }
        .form-group { margin-bottom: 14px; }
        .form-group label { display: block; margin-bottom: 5px; color: #ccc; font-size: 12px; }
        .form-group select,
        .form-group input {
            width: 100%; padding: 10px;
            background: #000; border: 1px solid #333;
            border-radius: 5px; color: #fff; font-size: 13px;
        }
        .form-group select:focus,
        .form-group input:focus { outline: none; border-color: #FFD700; }
        .btn-submit {
            width: 100%; padding: 12px;
            background: #FFD700; color: #000;
            border: none; border-radius: 5px;
            font-weight: bold; cursor: pointer;
            font-size: 14px; margin-top: 8px;
        }
        .btn-submit:hover { background: #FFA500; }

        @media (max-width: 600px) {
            .user-header    { flex-direction: column; gap: 8px; }
            .action-buttons { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

<div class="header">
    <div class="header-left">
        <a href="admin_dashboard.php" class="back-btn"><i class="fas fa-arrow-left"></i></a>
        <h1><i class="fas fa-users"></i> Manage Users</h1>
    </div>
    <a href="admin_logout.php" class="logout-btn">
        <i class="fas fa-sign-out-alt"></i> Logout
    </a>
</div>

<div class="container">

    <?php if (isset($success)): ?>
        <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?></div>
    <?php endif; ?>
    <?php if (isset($error)): ?>
        <div class="alert alert-error"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>

    <!-- Stats -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['total_users']; ?></div>
            <div class="stat-label">Total Users</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['total_users'] - $stats['banned_users']; ?></div>
            <div class="stat-label">Active Users</div>
        </div>
        <div class="stat-card banned">
            <div class="stat-number"><?php echo $stats['banned_users']; ?></div>
            <div class="stat-label">Banned Users</div>
        </div>
    </div>

    <!-- Search Bar -->
    <form method="GET" action="">
        <div class="search-bar">
            <input
                type="text"
                name="search_phone"
                placeholder="Search by phone number e.g. 0977..."
                value="<?php echo htmlspecialchars($search_phone); ?>"
                autocomplete="off"
            >
            <button type="submit">
                <i class="fas fa-search"></i> Search
            </button>
            <?php if ($search_phone): ?>
                <a href="?" class="clear-btn">
                    <i class="fas fa-times"></i> Clear
                </a>
            <?php endif; ?>
        </div>
    </form>

    <?php if ($search_phone): ?>
        <div class="search-result-label">
            Showing results for: <span><?php echo htmlspecialchars($search_phone); ?></span>
            &mdash; <?php echo mysqli_num_rows($users_result); ?> user(s) found
        </div>
    <?php endif; ?>

    <!-- Users List -->
    <div class="users-list">
    <?php if ($users_result && mysqli_num_rows($users_result) > 0):
        while ($user = mysqli_fetch_assoc($users_result)):
            $balance = floatval($user['balance'] ?? 0);
    ?>
        <div class="user-card <?php echo $user['banned'] ? 'banned' : ''; ?>">
            <div class="user-header">
                <div class="user-info">
                    <div class="user-name"><i class="fas fa-user"></i> User #<?php echo $user['id']; ?></div>
                    <div class="user-contact"><i class="fas fa-phone"></i> <?php echo htmlspecialchars($user['phone_number']); ?></div>
                    <div class="user-contact"><i class="fas fa-envelope"></i> <?php echo htmlspecialchars($user['email']); ?></div>
                    <div class="user-contact"><i class="fas fa-calendar"></i> Joined: <?php echo date('d M Y', strtotime($user['created_at'])); ?></div>
                    <?php if (!empty($user['referral_code'])): ?>
                    <div class="user-contact"><i class="fas fa-gift"></i> Ref Code: <strong style="color:#FFD700;"><?php echo $user['referral_code']; ?></strong></div>
                    <?php endif; ?>
                </div>
                <span class="user-status status-<?php echo $user['banned'] ? 'banned' : 'active'; ?>">
                    <?php echo $user['banned'] ? 'BANNED' : 'ACTIVE'; ?>
                </span>
            </div>

            <!-- Stats -->
            <div class="user-stats">
                <div class="stat-item">
                    <span class="stat-item-label">Account Balance</span>
                    <span class="stat-item-value">ZMW <?php echo number_format($balance, 2); ?></span>
                </div>
                <div class="stat-item">
                    <span class="stat-item-label">Total Deposits</span>
                    <span class="stat-item-value">ZMW <?php echo number_format($user['total_deposits'], 2); ?></span>
                </div>
                <div class="stat-item">
                    <span class="stat-item-label">Total Withdrawals</span>
                    <span class="stat-item-value">ZMW <?php echo number_format($user['total_withdrawals'], 2); ?></span>
                </div>
                <div class="stat-item">
                    <span class="stat-item-label">Total Profits</span>
                    <span class="stat-item-value">ZMW <?php echo number_format($user['total_profits'], 2); ?></span>
                </div>
                <div class="stat-item">
                    <span class="stat-item-label">Active Investments</span>
                    <span class="stat-item-value">ZMW <?php echo number_format($user['active_investments'], 2); ?></span>
                </div>
                <div class="stat-item">
                    <span class="stat-item-label">Referral Earnings</span>
                    <span class="stat-item-value">ZMW <?php echo number_format($user['total_referral_earnings'] ?? 0, 2); ?></span>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="action-buttons">
                <form method="POST">
                    <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                    <input type="hidden" name="action"  value="login_as_user">
                    <button type="submit" class="btn btn-login">
                        <i class="fas fa-sign-in-alt"></i> Login as User
                    </button>
                </form>

                <button type="button" class="btn btn-adjust"
                    onclick="openAdjustModal(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['phone_number']); ?>')">
                    <i class="fas fa-sliders-h"></i> Adjust Balance
                </button>

                <?php if ($user['banned']): ?>
                <form method="POST">
                    <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                    <input type="hidden" name="action"  value="unban_user">
                    <button type="submit" class="btn btn-unban">
                        <i class="fas fa-unlock"></i> Unban User
                    </button>
                </form>
                <?php else: ?>
                <form method="POST" onsubmit="return confirm('Ban this user?');">
                    <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                    <input type="hidden" name="action"  value="ban_user">
                    <button type="submit" class="btn btn-ban">
                        <i class="fas fa-ban"></i> Ban User
                    </button>
                </form>
                <?php endif; ?>

                <form method="POST" onsubmit="return confirm('DELETE this user permanently? This cannot be undone!');">
                    <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                    <input type="hidden" name="action"  value="delete_user">
                    <button type="submit" class="btn btn-delete">
                        <i class="fas fa-trash"></i> Delete User
                    </button>
                </form>
            </div>
        </div>
    <?php endwhile;
    else: ?>
        <div class="no-users">
            <i class="fas fa-search"></i>
            <?php if ($search_phone): ?>
                <p>No user found with phone number containing "<strong><?php echo htmlspecialchars($search_phone); ?></strong>"</p>
                <p style="margin-top:8px;font-size:11px;">Try a different number or <a href="?" style="color:#FFD700;">view all users</a>.</p>
            <?php else: ?>
                <p>No users found.</p>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    </div>

</div><!-- /.container -->

<!-- Adjust Balance Modal -->
<div id="adjustModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeAdjustModal()">&times;</span>
        <h2><i class="fas fa-sliders-h"></i> Adjust User Balance</h2>
        <p style="color:#888; margin-bottom:16px; font-size:12px;">
            Phone: <strong style="color:#FFD700;" id="modalUserPhone"></strong>
        </p>
        <form method="POST">
            <input type="hidden" name="user_id" id="modalUserId">
            <input type="hidden" name="action"  value="adjust_balance">

            <div class="form-group">
                <label>Adjustment Type</label>
                <select name="adjustment_type" required>
                    <option value="">-- Select Type --</option>
                    <option value="add_deposit">Add Deposit (increase balance)</option>
                    <option value="deduct_balance">Deduct from Balance (decrease balance)</option>
                    <option value="add_profit">Add Profit (increase balance)</option>
                    <option value="set_balance">Set Exact Balance</option>
                </select>
            </div>

            <div class="form-group">
                <label>Amount (ZMW)</label>
                <input type="number" name="amount" step="0.01" min="0.01"
                       placeholder="Enter amount in ZMW" required>
            </div>

            <button type="submit" class="btn-submit">
                <i class="fas fa-check-circle"></i> Apply Adjustment
            </button>
        </form>
    </div>
</div>

<script>
    // Auto-hide alerts after 5s
    setTimeout(function() {
        document.querySelectorAll('.alert').forEach(function(el) {
            el.style.transition = 'opacity 0.5s';
            el.style.opacity    = '0';
            setTimeout(function() { el.remove(); }, 500);
        });
    }, 5000);

    function openAdjustModal(userId, userPhone) {
        document.getElementById('modalUserId').value      = userId;
        document.getElementById('modalUserPhone').textContent = userPhone;
        document.getElementById('adjustModal').style.display = 'block';
    }
    function closeAdjustModal() {
        document.getElementById('adjustModal').style.display = 'none';
    }
    window.onclick = function(e) {
        if (e.target === document.getElementById('adjustModal')) closeAdjustModal();
    };
</script>
</body>
</html>
<?php mysqli_close($conn); ?>