<?php
// FILE VERSION: 8.2 — FIXED: include side.php AFTER POST handlers so redirects work
// 8.1 — Bulk delete added (checkboxes + select-all + transactional bulk handler)
// 8.0 — Cross-country KES commission + full prepared statements + edit-status commission trigger
require_once '../config/database.php';
require_once '../includes/functions.php';

// ✅ CRITICAL: admin_protect MUST run BEFORE any output.
//    side.php emits HTML, so including it before POST handlers breaks redirect().
require_once 'admin_protect.php';

$conn = getConnection();

// ════════════════════════════════════════════════════════════════════════════
// POST ACTIONS
// ════════════════════════════════════════════════════════════════════════════
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    switch ($action) {

        // ── RESET PASSWORD ────────────────────────────────────────────────────
        case 'reset_password':
            if (!hasPermission('reset_passwords') && !hasPermission('edit_users') && !hasPermission('manage_users')) {
                setFlash('error','No permission to reset passwords.'); redirect('users.php'); exit;
            }
            $userId      = intval($_POST['user_id']);
            $newPassword = $_POST['new_password']     ?? '';
            $confirmPass = $_POST['confirm_password'] ?? '';
            if (empty($newPassword))           { setFlash('error','Password cannot be empty.');          redirect('users.php'); exit; }
            if (strlen($newPassword) < 6)      { setFlash('error','Password must be at least 6 chars.'); redirect('users.php'); exit; }
            if ($newPassword !== $confirmPass) { setFlash('error','Passwords do not match.');            redirect('users.php'); exit; }

            $s = $conn->prepare("SELECT username,email FROM users WHERE id=?");
            $s->bind_param("i",$userId); $s->execute();
            $user = $s->get_result()->fetch_assoc();
            if (!$user) { setFlash('error','User not found.'); redirect('users.php'); exit; }

            $hash = password_hash($newPassword, PASSWORD_DEFAULT);
            $u = $conn->prepare("UPDATE users SET password=? WHERE id=?");
            $u->bind_param("si",$hash,$userId);
            if ($u->execute()) {
                logAdminAction('reset_password',"Reset password for {$user['username']} (ID: $userId)",$userId);
                setFlash('success',"Password reset for {$user['username']}!");
            } else {
                setFlash('error','Failed to reset password.');
            }
            break;

        // ── LOGIN AS USER ─────────────────────────────────────────────────────
        case 'login_as_user':
            if ($_SESSION['admin_role'] !== 'super_admin' && $_SESSION['admin_role'] !== 'assistant_admin') {
                setFlash('error','Insufficient permissions.'); break;
            }
            $userId = intval($_POST['user_id']);
            $s = $conn->prepare("SELECT * FROM users WHERE id=?");
            $s->bind_param("i",$userId); $s->execute();
            $user = $s->get_result()->fetch_assoc();
            if ($user) {
                $_SESSION['admin_impersonating']      = true;
                $_SESSION['original_admin_id']        = $_SESSION['admin_id'];
                $_SESSION['original_admin_username']  = $_SESSION['admin_username'];
                $_SESSION['original_admin_role']      = $_SESSION['admin_role'];
                $logS = $conn->prepare("INSERT INTO admin_logs(admin_id,action,details,target_id,ip_address)VALUES(?,'login_as_user',?,?,?)");
                $det  = "Admin logged in as: {$user['username']} (ID: {$user['id']})";
                $ip   = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
                $logS->bind_param("isis",$_SESSION['admin_id'],$det,$userId,$ip); $logS->execute();
                $_SESSION['user_id']      = $user['id'];
                $_SESSION['username']     = $user['username'];
                $_SESSION['email']        = $user['email'];
                $_SESSION['user_country'] = $user['country'];
                $_SESSION['user_status']  = $user['status'];
                header('Location: ../user/dashboard.php'); exit;
            } else {
                setFlash('error','User not found.');
            }
            break;

        // ── ACTIVATE USER ─────────────────────────────────────────────────────
        case 'activate':
            if (!hasPermission('activate_users') && !hasPermission('manage_users')) {
                setFlash('error','No permission to activate users.'); redirect('users.php'); exit;
            }
            $userId = intval($_POST['user_id']);

            $s = $conn->prepare("
                SELECT u.*, c.id AS country_id, c.name AS country_name,
                       c.exchange_rate, c.activation_fee
                FROM users u
                LEFT JOIN countries c ON u.country = c.name
                WHERE u.id = ?
            ");
            $s->bind_param("i",$userId); $s->execute();
            $user = $s->get_result()->fetch_assoc();

            if ($user && $user['status'] === 'inactive') {
                $upd = $conn->prepare("UPDATE users SET status='active', activation_date=NOW() WHERE id=?");
                $upd->bind_param("i",$userId); $upd->execute();

                if (isset($_SESSION['user_id']) && $_SESSION['user_id'] == $userId) {
                    $_SESSION['user_status'] = 'active';
                }

                if (!empty($user['referred_by']) && !empty($user['country_id'])) {
                    try {
                        distributeReferralCommissions($userId, $user['referred_by'], (int)$user['country_id']);
                    } catch (Exception $e) {
                        error_log("Commission error activating user #$userId: " . $e->getMessage());
                    }
                }

                logAdminAction('activate_user',
                    "Activated: {$user['username']} (ID: $userId, Country: {$user['country_name']})",
                    $userId
                );
                setFlash('success', "'{$user['username']}' activated! Referral commissions distributed in KES.");
            } else {
                setFlash('error','User is already active or not found.');
            }
            break;

        // ── DEACTIVATE USER ───────────────────────────────────────────────────
        case 'deactivate':
            if (!hasPermission('deactivate_users') && !hasPermission('manage_users')) {
                setFlash('error','No permission to deactivate users.'); redirect('users.php'); exit;
            }
            $userId = intval($_POST['user_id']);
            $upd = $conn->prepare("UPDATE users SET status='inactive' WHERE id=?");
            $upd->bind_param("i",$userId); $upd->execute();
            logAdminAction('deactivate_user',"Deactivated user ID: $userId",$userId);
            setFlash('success','User deactivated.');
            break;

        // ── EDIT USER ─────────────────────────────────────────────────────────
        case 'edit':
            if (!hasPermission('edit_users') && !hasPermission('manage_users')) {
                setFlash('error','No permission to edit users.'); redirect('users.php'); exit;
            }
            $userId   = intval($_POST['user_id']);
            $username = sanitize($_POST['username']);
            $email    = sanitize($_POST['email']);
            $phone    = sanitize($_POST['phone']);
            $country  = sanitize($_POST['country']);
            $newStatus= sanitize($_POST['status']);

            $ck = $conn->prepare("SELECT id FROM users WHERE username=? AND id!=?");
            $ck->bind_param("si",$username,$userId); $ck->execute();
            if ($ck->get_result()->num_rows > 0) { setFlash('error','Username already exists!'); redirect('users.php'); exit; }

            $ck = $conn->prepare("SELECT id FROM users WHERE email=? AND id!=?");
            $ck->bind_param("si",$email,$userId); $ck->execute();
            if ($ck->get_result()->num_rows > 0) { setFlash('error','Email already exists!'); redirect('users.php'); exit; }

            $referredBy = null;
            if (!empty(trim($_POST['referred_by_username'] ?? ''))) {
                $ul = sanitize(trim($_POST['referred_by_username']));
                $us = $conn->prepare("SELECT id FROM users WHERE username=? AND id!=?");
                $us->bind_param("si",$ul,$userId); $us->execute();
                $ur = $us->get_result()->fetch_assoc();
                if (!$ur) { setFlash('error',"Upline '@{$ul}' not found!"); redirect('users.php'); exit; }
                $referredBy = $ur['id'];
            }

            $prevStmt = $conn->prepare("
                SELECT u.status as old_status, c.id AS country_id, c.exchange_rate
                FROM users u LEFT JOIN countries c ON u.country=c.name
                WHERE u.id=?
            ");
            $prevStmt->bind_param("i",$userId); $prevStmt->execute();
            $prevUser = $prevStmt->get_result()->fetch_assoc();
            $oldStatus = $prevUser['old_status'] ?? 'inactive';

            $stmt = $conn->prepare("UPDATE users SET username=?,email=?,phone=?,country=?,status=?,referred_by=? WHERE id=?");
            $stmt->bind_param("sssssii",$username,$email,$phone,$country,$newStatus,$referredBy,$userId);
            if ($stmt->execute()) {

                if ($oldStatus === 'inactive' && $newStatus === 'active') {
                    $hasActDate = $conn->query("SHOW COLUMNS FROM users LIKE 'activation_date'");
                    if ($hasActDate && $hasActDate->num_rows > 0) {
                        $adStmt = $conn->prepare("UPDATE users SET activation_date=NOW() WHERE id=? AND (activation_date IS NULL OR activation_date='0000-00-00 00:00:00')");
                        $adStmt->bind_param("i",$userId); $adStmt->execute();
                    }

                    $cid = (int)($prevUser['country_id'] ?? 0);
                    if ($cid > 0 && !empty($referredBy)) {
                        try {
                            distributeReferralCommissions($userId, $referredBy, $cid);
                        } catch (Exception $e) {
                            error_log("Commission error on edit-activate user #$userId: " . $e->getMessage());
                        }
                    } elseif ($cid > 0) {
                        $rbStmt = $conn->prepare("SELECT referred_by FROM users WHERE id=?");
                        $rbStmt->bind_param("i",$userId); $rbStmt->execute();
                        $rbRow = $rbStmt->get_result()->fetch_assoc();
                        if (!empty($rbRow['referred_by'])) {
                            try {
                                distributeReferralCommissions($userId, $rbRow['referred_by'], $cid);
                            } catch (Exception $e) {
                                error_log("Commission error on edit-activate user #$userId: " . $e->getMessage());
                            }
                        }
                    }
                }

                $canEditWallets = hasPermission('edit_wallets') || hasPermission('manage_wallets');
                if ($canEditWallets) {
                    ensureWalletExists($conn, $userId);

                    $walletFields = [
                        'balance_referral' => 'referral_wallet',
                        'balance_task'     => 'main_wallet',
                        'balance_video'    => 'video_wallet',
                        'balance_trivia'   => 'trivia_wallet',
                        'balance_ads'      => 'ads_wallet',
                        'balance_bonus'    => 'bonus_wallet',
                        'balance_spin'     => 'spin_wallet',
                        'balance_blog'     => 'blog_wallet',
                        'balance_meme'     => 'meme_wallet',
                    ];
                    $setClauses = [];
                    $binds = [];
                    $types = '';
                    foreach ($walletFields as $postKey => $dbCol) {
                        if (isset($_POST[$postKey])) {
                            $setClauses[] = "{$dbCol} = ?";
                            $binds[]       = floatval($_POST[$postKey]);
                            $types        .= 'd';
                        }
                    }
                    if (!empty($setClauses)) {
                        $setClauses[] = 'updated_at = NOW()';
                        $wSql  = "UPDATE wallets SET " . implode(', ', $setClauses) . " WHERE user_id = ?";
                        $wStmt = $conn->prepare($wSql);
                        $binds[] = $userId;
                        $types  .= 'i';
                        $wStmt->bind_param($types, ...$binds);
                        $wStmt->execute();
                        recalcWalletBalance($conn, $userId);
                    }
                }

                logAdminAction('edit_user',"Edited: $username (ID: $userId)",$userId);
                setFlash('success','User updated!' . ($oldStatus==='inactive'&&$newStatus==='active' ? ' Commissions distributed.' : ''));
            } else {
                setFlash('error','Failed to update user: ' . $stmt->error);
            }
            break;

        // ── DELETE USER (single) ──────────────────────────────────────────────
        case 'delete':
            $userId = intval($_POST['user_id']);
            $s = $conn->prepare("SELECT * FROM users WHERE id=?");
            $s->bind_param("i",$userId); $s->execute();
            $userToDelete = $s->get_result()->fetch_assoc();
            if (!$userToDelete) { setFlash('error','User not found.'); redirect('users.php'); exit; }
            if (!canDeleteUser($userToDelete)) { setFlash('error','No permission to delete this user.'); redirect('users.php'); exit; }
            try {
                $inTx = false;
                $conn->begin_transaction(); $inTx = true;
                $d1=$conn->prepare("DELETE FROM wallets      WHERE user_id=?"); $d1->bind_param("i",$userId); $d1->execute();
                $d2=$conn->prepare("DELETE FROM transactions WHERE user_id=?"); $d2->bind_param("i",$userId); $d2->execute();
                $d3=$conn->prepare("UPDATE users SET referred_by=NULL WHERE referred_by=?"); $d3->bind_param("i",$userId); $d3->execute();
                $d4=$conn->prepare("DELETE FROM users WHERE id=?"); $d4->bind_param("i",$userId);
                if ($d4->execute()) {
                    $conn->commit(); $inTx = false;
                    logAdminAction('delete_user',"Deleted: {$userToDelete['username']} (ID: $userId)",$userId);
                    setFlash('success','User deleted.');
                } else {
                    throw new Exception('Failed to delete user.');
                }
            } catch (Exception $e) {
                if (!empty($inTx)) { try { $conn->rollback(); } catch (Throwable $_) {} }
                setFlash('error','Delete failed: ' . $e->getMessage());
            }
            break;

        // ── BULK DELETE USERS ─────────────────────────────────────────────────
        // Accepts user_ids[] as POST array. Permission-checks each user
        // individually via canDeleteUser(), skipping any that fail.
        // Runs the whole batch in a single transaction; rolls back on fatal error.
        case 'bulk_delete':
            $ids = $_POST['user_ids'] ?? [];
            if (!is_array($ids) || count($ids) === 0) {
                setFlash('error','No users selected.');
                redirect('users.php'); exit;
            }
            // Sanitize → unique positive ints
            $ids = array_values(array_unique(array_filter(array_map('intval', $ids), function($v){ return $v > 0; })));
            if (empty($ids)) {
                setFlash('error','No valid user IDs provided.');
                redirect('users.php'); exit;
            }
            // Optional hard cap to prevent runaway requests
            if (count($ids) > 500) {
                setFlash('error','Too many users selected (max 500 per batch).');
                redirect('users.php'); exit;
            }

            // Fetch the users so we can permission-check each one
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $types = str_repeat('i', count($ids));
            $fetchStmt = $conn->prepare("SELECT * FROM users WHERE id IN ($placeholders)");
            $fetchStmt->bind_param($types, ...$ids);
            $fetchStmt->execute();
            $candidates = $fetchStmt->get_result()->fetch_all(MYSQLI_ASSOC);

            // Filter to ones the admin can actually delete
            $allowed = [];
            $skipped = [];
            foreach ($candidates as $cu) {
                if (canDeleteUser($cu)) {
                    $allowed[] = $cu;
                } else {
                    $skipped[] = $cu['username'];
                }
            }

            if (empty($allowed)) {
                setFlash('error','None of the selected users could be deleted (permission denied).');
                redirect('users.php'); exit;
            }

            $deletedCount = 0;
            $deletedNames = [];
            $deletedIds   = [];

            try {
                $inTx = false;
                $conn->begin_transaction(); $inTx = true;

                // Prepare statements ONCE, reuse across IDs
                $sWallets = $conn->prepare("DELETE FROM wallets      WHERE user_id=?");
                $sTxns    = $conn->prepare("DELETE FROM transactions WHERE user_id=?");
                $sNullRef = $conn->prepare("UPDATE users SET referred_by=NULL WHERE referred_by=?");
                $sUser    = $conn->prepare("DELETE FROM users WHERE id=?");

                foreach ($allowed as $cu) {
                    $uid = (int)$cu['id'];
                    $sWallets->bind_param("i",$uid); $sWallets->execute();
                    $sTxns->bind_param("i",$uid);    $sTxns->execute();
                    $sNullRef->bind_param("i",$uid); $sNullRef->execute();
                    $sUser->bind_param("i",$uid);
                    if ($sUser->execute() && $sUser->affected_rows > 0) {
                        $deletedCount++;
                        $deletedNames[] = $cu['username'];
                        $deletedIds[]   = $uid;
                    }
                }

                $conn->commit(); $inTx = false;

                // Log it — single combined log entry for the batch
                $namesPreview = implode(', ', array_slice($deletedNames, 0, 10));
                if (count($deletedNames) > 10) $namesPreview .= ', …';
                logAdminAction(
                    'bulk_delete_users',
                    "Bulk-deleted $deletedCount user(s): $namesPreview [IDs: " . implode(',', $deletedIds) . "]",
                    0
                );

                $msg = "Deleted $deletedCount user" . ($deletedCount === 1 ? '' : 's') . '.';
                if (!empty($skipped)) {
                    $skippedPreview = implode(', ', array_slice($skipped, 0, 5));
                    if (count($skipped) > 5) $skippedPreview .= ', …';
                    $msg .= ' Skipped (no permission): ' . $skippedPreview;
                }
                setFlash('success', $msg);
            } catch (Exception $e) {
                if (!empty($inTx)) { try { $conn->rollback(); } catch (Throwable $_) {} }
                setFlash('error','Bulk delete failed: ' . $e->getMessage());
            }
            break;
    }

    redirect('users.php');
}

// ── SEARCH / FILTER / PAGINATION ─────────────────────────────────────────
$search  = isset($_GET['search'])  ? sanitize($_GET['search'])  : '';
$status  = isset($_GET['status'])  ? sanitize($_GET['status'])  : '';
$country = isset($_GET['country']) ? sanitize($_GET['country']) : '';
$page    = max(1, isset($_GET['page']) ? intval($_GET['page']) : 1);
$perPage = 20;
$offset  = ($page - 1) * $perPage;

$where = "1=1";
if ($search)  $where .= " AND (u.username LIKE '%".addslashes($search)."%' OR u.email LIKE '%".addslashes($search)."%' OR u.phone LIKE '%".addslashes($search)."%')";
if ($status)  $where .= " AND u.status='".addslashes($status)."'";
if ($country) $where .= " AND u.country='".addslashes($country)."'";

$totalResult = $conn->query("SELECT COUNT(*) as total FROM users u WHERE $where");
$total       = $totalResult->fetch_assoc()['total'];
$totalPages  = max(1, ceil($total / $perPage));

$users = $conn->query("
    SELECT u.*,
           c.currency_symbol,
           c.exchange_rate,
           (SELECT COUNT(*) FROM users WHERE referred_by=u.id) as referral_count,
           upline.username as upline_username,
           upline.id       as upline_id,
           COALESCE((SELECT referral_wallet      FROM wallets WHERE user_id=u.id LIMIT 1), 0) as referral_wallet,
           COALESCE((SELECT main_wallet          FROM wallets WHERE user_id=u.id LIMIT 1), 0) as main_wallet,
           COALESCE((SELECT video_wallet         FROM wallets WHERE user_id=u.id LIMIT 1), 0) as video_wallet,
           COALESCE((SELECT trivia_wallet        FROM wallets WHERE user_id=u.id LIMIT 1), 0) as trivia_wallet,
           COALESCE((SELECT ads_wallet           FROM wallets WHERE user_id=u.id LIMIT 1), 0) as ads_wallet,
           COALESCE((SELECT bonus_wallet         FROM wallets WHERE user_id=u.id LIMIT 1), 0) as bonus_wallet,
           COALESCE((SELECT spin_wallet          FROM wallets WHERE user_id=u.id LIMIT 1), 0) as spin_wallet,
           COALESCE((SELECT blog_wallet          FROM wallets WHERE user_id=u.id LIMIT 1), 0) as blog_wallet,
           COALESCE((SELECT meme_wallet          FROM wallets WHERE user_id=u.id LIMIT 1), 0) as meme_wallet
    FROM users u
    LEFT JOIN countries c ON u.country=c.name
    LEFT JOIN users upline ON u.referred_by=upline.id
    WHERE $where
    ORDER BY u.created_at DESC
    LIMIT $offset, $perPage
");

$countries = $conn->query("SELECT DISTINCT name FROM countries WHERE status='active' ORDER BY name");

$stats = $conn->query("
    SELECT COUNT(*) as total_users,
        SUM(CASE WHEN status='active'   THEN 1 ELSE 0 END) as active_users,
        SUM(CASE WHEN status='inactive' THEN 1 ELSE 0 END) as inactive_users,
        SUM(CASE WHEN DATE(created_at)=CURDATE() THEN 1 ELSE 0 END) as today_signups
    FROM users
")->fetch_assoc();

$canEditUsers       = hasPermission('edit_users')       || hasPermission('manage_users');
$canEditWallets     = hasPermission('edit_wallets')     || hasPermission('manage_wallets');
$canActivateUsers   = hasPermission('activate_users')   || hasPermission('manage_users');
$canDeactivateUsers = hasPermission('deactivate_users') || hasPermission('manage_users');
$canResetPasswords  = hasPermission('reset_passwords')  || hasPermission('edit_users') || hasPermission('manage_users');
$canLoginAsUser     = in_array($_SESSION['admin_role'] ?? '', ['super_admin','assistant_admin']);

// ✅ Now safe to include side.php (which emits HTML) — all POST redirects already ran above.
$pageTitle = 'Users Management';
include 'side.php';
?>

<style>
.page-header{margin-bottom:24px}
.page-title{font-size:28px;font-weight:900;color:var(--text-primary);display:flex;align-items:center;gap:12px;margin-bottom:6px}
.page-title i{background:linear-gradient(135deg,var(--theme-color),#ec4899);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}
.page-subtitle{font-size:14px;color:var(--text-secondary);font-weight:500}
.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px;margin-bottom:24px}
.stat-card{background:var(--card-bg);border:1px solid var(--border-color);border-radius:14px;padding:20px;transition:all .3s}
.stat-card:hover{transform:translateY(-2px);box-shadow:0 8px 24px rgba(0,0,0,.1);border-color:rgba(var(--theme-rgb),.3)}
.stat-icon{width:48px;height:48px;background:linear-gradient(135deg,var(--theme-color),#ec4899);border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:22px;color:white;margin-bottom:12px}
.stat-label{font-size:12px;color:var(--text-secondary);font-weight:600;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px}
.stat-value{font-size:32px;font-weight:900;color:var(--text-primary)}
.filters-bar{background:var(--card-bg);border:1px solid var(--border-color);border-radius:14px;padding:20px;margin-bottom:24px;display:flex;gap:12px;flex-wrap:wrap;align-items:end}
.filter-group{flex:1;min-width:200px}
.filter-label{display:block;font-size:12px;font-weight:600;color:var(--text-secondary);margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px}
.filter-control{width:100%;padding:11px 14px;font-size:14px;border:1px solid var(--border-color);border-radius:10px;background:var(--darker-bg);color:var(--text-primary);font-weight:500;transition:all .3s}
.filter-control:focus{outline:none;border-color:var(--theme-color);box-shadow:0 0 0 3px rgba(var(--theme-rgb),.1)}
.filter-control option{background:var(--card-bg);color:var(--text-primary)}
.btn-filter{padding:11px 24px;background:linear-gradient(135deg,var(--theme-color),#ec4899);color:white;border:none;border-radius:10px;font-size:14px;font-weight:600;cursor:pointer;transition:all .3s;white-space:nowrap;display:flex;align-items:center;gap:8px}
.btn-filter:hover{transform:translateY(-2px);box-shadow:0 4px 12px rgba(var(--theme-rgb),.4)}
.btn-reset{padding:11px 18px;background:var(--card-bg);color:var(--text-secondary);border:1px solid var(--border-color);border-radius:10px;font-size:14px;font-weight:600;cursor:pointer;transition:all .3s}
.btn-reset:hover{background:var(--darker-bg);color:var(--text-primary)}
.users-table-container{background:var(--card-bg);border:1px solid var(--border-color);border-radius:14px;overflow:hidden}
.table-wrapper{overflow-x:auto}
.users-table{width:100%;border-collapse:collapse;min-width:1100px}
.users-table thead{background:var(--darker-bg)}
.users-table th{padding:16px;text-align:left;font-size:11px;font-weight:700;color:var(--text-secondary);text-transform:uppercase;letter-spacing:.5px;border-bottom:1px solid var(--border-color)}
.users-table td{padding:16px;font-size:14px;color:var(--text-primary);border-bottom:1px solid var(--border-color);font-weight:500}
.users-table tbody tr{transition:all .2s}
.users-table tbody tr:hover{background:var(--darker-bg)}
.users-table tbody tr.row-selected{background:rgba(var(--theme-rgb),.08)}
.users-table tbody tr.row-selected:hover{background:rgba(var(--theme-rgb),.12)}
.status-badge{padding:6px 12px;border-radius:8px;font-size:11px;font-weight:700;text-transform:uppercase;display:inline-block}
.status-active{background:rgba(16,185,129,.15);color:#10b981;border:1px solid rgba(16,185,129,.3)}
.status-inactive{background:rgba(239,68,68,.15);color:#ef4444;border:1px solid rgba(239,68,68,.3)}
.action-buttons{display:flex;gap:6px;align-items:center;flex-wrap:wrap}
.btn-action{width:36px;height:36px;padding:0;background:var(--darker-bg);color:var(--text-secondary);border:1px solid var(--border-color);border-radius:8px;font-size:14px;cursor:pointer;transition:all .3s;display:flex;align-items:center;justify-content:center}
.btn-action:hover{transform:translateY(-2px);box-shadow:0 4px 12px rgba(0,0,0,.15)}
.btn-view:hover{background:#3b82f6;color:white;border-color:#3b82f6}
.btn-edit:hover{background:#8b5cf6;color:white;border-color:#8b5cf6}
.btn-password:hover{background:#06b6d4;color:white;border-color:#06b6d4}
.btn-login:hover{background:#f59e0b;color:white;border-color:#f59e0b}
.btn-activate:hover{background:#10b981;color:white;border-color:#10b981}
.btn-deactivate:hover{background:#f59e0b;color:white;border-color:#f59e0b}
.btn-delete:hover{background:#ef4444;color:white;border-color:#ef4444}
.btn-action:disabled{opacity:.4;cursor:not-allowed;transform:none!important;box-shadow:none!important}

/* ── BULK SELECT ── */
.bulk-checkbox{
    width:18px;height:18px;cursor:pointer;accent-color:var(--theme-color);
    vertical-align:middle;
}
.bulk-checkbox:disabled{cursor:not-allowed;opacity:.4}
.users-table th.col-select,
.users-table td.col-select{width:42px;text-align:center;padding-left:14px;padding-right:0}

.bulk-bar{
    position:sticky;bottom:0;left:0;right:0;z-index:50;
    background:linear-gradient(135deg,rgba(239,68,68,.97),rgba(220,38,38,.97));
    backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);
    border:1px solid rgba(255,255,255,.15);border-radius:14px;
    padding:14px 18px;margin-top:18px;
    display:none;align-items:center;gap:14px;flex-wrap:wrap;
    box-shadow:0 10px 30px rgba(239,68,68,.35);
    animation:bulkBarIn .25s cubic-bezier(.22,1,.36,1) both;
}
.bulk-bar.show{display:flex}
@keyframes bulkBarIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:none}}
.bulk-bar-count{
    color:#fff;font-weight:800;font-size:15px;
    display:flex;align-items:center;gap:8px;flex:1;min-width:140px;
}
.bulk-bar-count i{font-size:18px}
.bulk-bar-count strong{font-size:22px;font-variant-numeric:tabular-nums}
.bulk-bar-actions{display:flex;gap:8px;flex-wrap:wrap}
.bulk-btn{
    padding:9px 16px;border-radius:9px;border:none;font-size:13px;font-weight:700;
    cursor:pointer;transition:all .2s;display:inline-flex;align-items:center;gap:7px;
    font-family:inherit;
}
.bulk-btn.danger{background:#fff;color:#dc2626}
.bulk-btn.danger:hover{background:#fef2f2;transform:translateY(-1px);box-shadow:0 6px 16px rgba(0,0,0,.2)}
.bulk-btn.ghost{background:rgba(255,255,255,.15);color:#fff;border:1px solid rgba(255,255,255,.25)}
.bulk-btn.ghost:hover{background:rgba(255,255,255,.25)}
@media(max-width:520px){
    .bulk-bar{flex-direction:column;align-items:stretch}
    .bulk-bar-count{justify-content:center}
    .bulk-bar-actions{justify-content:center}
}

.pagination{display:flex;justify-content:center;align-items:center;gap:8px;margin-top:24px;padding:20px}
.page-btn{padding:10px 16px;background:var(--card-bg);border:1px solid var(--border-color);border-radius:8px;color:var(--text-primary);font-size:14px;font-weight:600;cursor:pointer;transition:all .3s;text-decoration:none}
.page-btn:hover{background:var(--darker-bg);transform:translateY(-2px)}
.page-btn.active{background:linear-gradient(135deg,var(--theme-color),#ec4899);color:white;border-color:var(--theme-color)}
.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.7);backdrop-filter:blur(4px);z-index:10000;align-items:center;justify-content:center;padding:20px;overflow-y:auto}
.modal.active{display:flex}
.modal-content{background:var(--card-bg);border:1px solid var(--border-color);border-radius:20px;padding:32px;max-width:700px;width:100%;max-height:90vh;overflow-y:auto;box-shadow:0 20px 60px rgba(0,0,0,.3)}
.modal-content.small{max-width:450px}
.modal-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:24px;padding-bottom:16px;border-bottom:1px solid var(--border-color)}
.modal-title{font-size:22px;font-weight:900;color:var(--text-primary);display:flex;align-items:center;gap:10px}
.modal-title i{background:linear-gradient(135deg,var(--theme-color),#ec4899);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}
.modal-close{width:36px;height:36px;background:var(--darker-bg);border:1px solid var(--border-color);border-radius:10px;color:var(--text-secondary);cursor:pointer;transition:all .3s;display:flex;align-items:center;justify-content:center;font-size:18px}
.modal-close:hover{background:var(--card-bg);color:var(--text-primary);transform:rotate(90deg)}
.form-grid{display:grid;grid-template-columns:repeat(2,1fr);gap:16px}
.form-group{margin-bottom:16px}
.form-group.full-width{grid-column:1/-1}
.form-label{display:block;font-size:13px;font-weight:600;color:var(--text-secondary);margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px}
.form-control{width:100%;padding:12px 14px;font-size:14px;border:1px solid var(--border-color);border-radius:10px;background:var(--darker-bg);color:var(--text-primary);font-weight:500;transition:all .3s}
.form-control:focus{outline:none;border-color:var(--theme-color);box-shadow:0 0 0 3px rgba(var(--theme-rgb),.1)}
.form-control:disabled{opacity:.6;cursor:not-allowed}
.form-control option{background:var(--card-bg);color:var(--text-primary)}
.btn-primary{width:100%;padding:14px 32px;background:linear-gradient(135deg,var(--theme-color),#ec4899);color:white;border:none;border-radius:10px;font-size:15px;font-weight:700;cursor:pointer;transition:all .3s;display:inline-flex;align-items:center;justify-content:center;gap:8px;margin-top:20px;text-transform:uppercase;letter-spacing:.5px}
.btn-primary:hover{transform:translateY(-2px);box-shadow:0 8px 24px rgba(var(--theme-rgb),.4)}
.btn-primary:disabled{opacity:.6;cursor:not-allowed;transform:none}
.info-section{background:var(--darker-bg);border:1px solid var(--border-color);border-radius:12px;padding:18px;margin-bottom:18px}
.info-section-title{font-size:14px;font-weight:700;color:var(--text-primary);margin-bottom:14px;text-transform:uppercase;letter-spacing:.5px;display:flex;align-items:center;gap:8px}
.info-section-title i{background:linear-gradient(135deg,var(--theme-color),#ec4899);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}
.info-row{display:flex;justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--border-color)}
.info-row:last-child{border-bottom:none}
.info-label{font-size:13px;color:var(--text-secondary);font-weight:600}
.info-value{font-size:14px;color:var(--text-primary);font-weight:700}
.permission-notice{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);border-radius:8px;padding:12px;margin-bottom:16px;color:#ef4444;font-size:13px;display:flex;align-items:center;gap:8px}
.password-requirements{background:rgba(59,130,246,.1);border:1px solid rgba(59,130,246,.3);border-radius:8px;padding:12px;margin-bottom:16px;color:#3b82f6;font-size:12px}
.password-requirements ul{margin:8px 0 0 16px;padding:0}
.password-requirements li{margin-bottom:4px}
.user-info-header{display:flex;align-items:center;gap:12px;padding:16px;background:var(--darker-bg);border-radius:10px;margin-bottom:20px}
.user-avatar{width:50px;height:50px;background:linear-gradient(135deg,var(--theme-color),#ec4899);border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;font-weight:900;color:white}
.user-details h4{font-size:16px;font-weight:700;color:var(--text-primary);margin-bottom:4px}
.user-details p{font-size:13px;color:var(--text-secondary)}
.comm-note{background:rgba(16,185,129,.06);border:1px solid rgba(16,185,129,.2);border-radius:9px;padding:10px 12px;font-size:11.5px;color:#10b981;margin-top:14px;line-height:1.6}
.comm-note strong{font-weight:800}
@media(max-width:768px){
    .stats-grid{grid-template-columns:1fr;gap:12px}
    .filters-bar{flex-direction:column}
    .filter-group{min-width:100%}
    .form-grid{grid-template-columns:1fr}
    .modal-content{padding:24px 20px}
    .action-buttons{justify-content:flex-start}
}
</style>

<!-- Page Header -->
<div class="page-header">
    <h1 class="page-title"><i class="fas fa-users"></i> Users Management</h1>
    <p class="page-subtitle">Manage accounts, wallets, passwords and activation — commissions auto-distributed in KES on activation</p>
</div>

<!-- Stats -->
<div class="stats-grid">
    <div class="stat-card"><div class="stat-icon"><i class="fas fa-users"></i></div><div class="stat-label">Total Users</div><div class="stat-value"><?= number_format($stats['total_users']) ?></div></div>
    <div class="stat-card"><div class="stat-icon"><i class="fas fa-user-check"></i></div><div class="stat-label">Active</div><div class="stat-value"><?= number_format($stats['active_users']) ?></div></div>
    <div class="stat-card"><div class="stat-icon"><i class="fas fa-user-clock"></i></div><div class="stat-label">Inactive</div><div class="stat-value"><?= number_format($stats['inactive_users']) ?></div></div>
    <div class="stat-card"><div class="stat-icon"><i class="fas fa-user-plus"></i></div><div class="stat-label">Today Signups</div><div class="stat-value"><?= number_format($stats['today_signups']) ?></div></div>
</div>

<!-- Filters -->
<form method="GET" class="filters-bar">
    <div class="filter-group">
        <label class="filter-label"><i class="fas fa-search"></i> Search</label>
        <input type="text" name="search" class="filter-control" placeholder="Username, email or phone…" value="<?= htmlspecialchars($search) ?>">
    </div>
    <div class="filter-group">
        <label class="filter-label"><i class="fas fa-filter"></i> Status</label>
        <select name="status" class="filter-control">
            <option value="">All Status</option>
            <option value="active"   <?= $status==='active'?'selected':'' ?>>Active</option>
            <option value="inactive" <?= $status==='inactive'?'selected':'' ?>>Inactive</option>
        </select>
    </div>
    <div class="filter-group">
        <label class="filter-label"><i class="fas fa-globe"></i> Country</label>
        <select name="country" class="filter-control">
            <option value="">All Countries</option>
            <?php $countries->data_seek(0); while($c=$countries->fetch_assoc()): ?>
            <option value="<?= htmlspecialchars($c['name']) ?>" <?= $country===$c['name']?'selected':'' ?>><?= htmlspecialchars($c['name']) ?></option>
            <?php endwhile; ?>
        </select>
    </div>
    <div style="display:flex;gap:8px">
        <button type="submit" class="btn-filter"><i class="fas fa-search"></i> Search</button>
        <a href="users.php" class="btn-reset" style="text-decoration:none;display:flex;align-items:center"><i class="fas fa-redo"></i></a>
    </div>
</form>

<!-- Users Table -->
<div class="users-table-container">
<div class="table-wrapper">
<table class="users-table" id="usersTable">
    <thead>
        <tr>
            <th class="col-select">
                <input type="checkbox" class="bulk-checkbox" id="selectAll" title="Select all on this page" onclick="toggleSelectAll(this)">
            </th>
            <th style="width:60px">ID</th>
            <th>Username</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Country</th>
            <th style="width:110px">Status</th>
            <th style="width:80px">Refs</th>
            <th style="width:110px">Joined</th>
            <th style="width:260px">Actions</th>
        </tr>
    </thead>
    <tbody>
    <?php if ($users && $users->num_rows > 0): ?>
        <?php while ($user = $users->fetch_assoc()):
            $canDel = canDeleteUser($user);
        ?>
        <tr data-user-id="<?= $user['id'] ?>">
            <td class="col-select">
                <?php if ($canDel): ?>
                <input type="checkbox" class="bulk-checkbox row-check"
                       value="<?= $user['id'] ?>"
                       data-username="<?= htmlspecialchars($user['username'], ENT_QUOTES) ?>"
                       onclick="onRowCheck(this)">
                <?php else: ?>
                <input type="checkbox" class="bulk-checkbox" disabled title="You don't have permission to delete this user">
                <?php endif; ?>
            </td>
            <td><strong>#<?= $user['id'] ?></strong></td>
            <td><strong><?= htmlspecialchars($user['username']) ?></strong></td>
            <td><?= htmlspecialchars($user['email']) ?></td>
            <td><?= htmlspecialchars($user['phone']) ?></td>
            <td><?= htmlspecialchars($user['country']) ?></td>
            <td><span class="status-badge status-<?= $user['status'] ?>"><?= $user['status'] ?></span></td>
            <td><?= $user['referral_count'] ?></td>
            <td><?= date('M j, Y', strtotime($user['created_at'])) ?></td>
            <td>
                <div class="action-buttons">
                    <button class="btn-action btn-view"
                        onclick="viewUser(<?= htmlspecialchars(json_encode($user)) ?>)"
                        title="View Details"><i class="fas fa-eye"></i></button>

                    <?php if ($canEditUsers): ?>
                    <button class="btn-action btn-edit"
                        onclick="editUser(<?= htmlspecialchars(json_encode($user)) ?>)"
                        title="Edit User"><i class="fas fa-edit"></i></button>
                    <?php endif; ?>

                    <?php if ($canResetPasswords): ?>
                    <button class="btn-action btn-password"
                        onclick="resetPassword(<?= $user['id'] ?>,'<?= htmlspecialchars($user['username'],ENT_QUOTES) ?>','<?= htmlspecialchars($user['email'],ENT_QUOTES) ?>')"
                        title="Reset Password"><i class="fas fa-key"></i></button>
                    <?php endif; ?>

                    <?php if ($canLoginAsUser): ?>
                    <button class="btn-action btn-login"
                        onclick="loginAsUser(<?= $user['id'] ?>,'<?= htmlspecialchars($user['username'],ENT_QUOTES) ?>')"
                        title="Login as User"><i class="fas fa-sign-in-alt"></i></button>
                    <?php endif; ?>

                    <?php if ($user['status']==='inactive' && $canActivateUsers): ?>
                    <button class="btn-action btn-activate"
                        onclick="activateUser(<?= $user['id'] ?>,'<?= htmlspecialchars($user['username'],ENT_QUOTES) ?>','<?= htmlspecialchars($user['country'],ENT_QUOTES) ?>')"
                        title="Activate"><i class="fas fa-check"></i></button>
                    <?php elseif ($user['status']==='active' && $canDeactivateUsers): ?>
                    <button class="btn-action btn-deactivate"
                        onclick="deactivateUser(<?= $user['id'] ?>)"
                        title="Deactivate"><i class="fas fa-pause"></i></button>
                    <?php endif; ?>

                    <?php if ($canDel): ?>
                    <button class="btn-action btn-delete"
                        onclick="deleteUser(<?= $user['id'] ?>,'<?= htmlspecialchars($user['username'],ENT_QUOTES) ?>')"
                        title="Delete"><i class="fas fa-trash"></i></button>
                    <?php endif; ?>
                </div>
            </td>
        </tr>
        <?php endwhile; ?>
    <?php else: ?>
        <tr><td colspan="10" style="text-align:center;padding:40px;color:var(--text-secondary)">
            <i class="fas fa-users" style="font-size:48px;margin-bottom:16px;opacity:.5;display:block"></i>No users found
        </td></tr>
    <?php endif; ?>
    </tbody>
</table>
</div>
</div>

<!-- ── BULK ACTION BAR (shown when ≥1 selected) ── -->
<div class="bulk-bar" id="bulkBar">
    <div class="bulk-bar-count">
        <i class="fas fa-check-square"></i>
        <span><strong id="bulkCount">0</strong> user<span id="bulkPlural">s</span> selected</span>
    </div>
    <div class="bulk-bar-actions">
        <button type="button" class="bulk-btn ghost" onclick="clearSelection()">
            <i class="fas fa-times"></i> Clear
        </button>
        <button type="button" class="bulk-btn danger" onclick="bulkDeleteSelected()">
            <i class="fas fa-trash"></i> Delete Selected
        </button>
    </div>
</div>

<!-- Pagination -->
<?php if ($totalPages > 1): ?>
<div class="pagination">
    <?php if ($page > 1): ?>
    <a href="?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>&country=<?= urlencode($country) ?>" class="page-btn"><i class="fas fa-chevron-left"></i></a>
    <?php endif; ?>
    <?php for ($i=max(1,$page-2); $i<=min($totalPages,$page+2); $i++): ?>
    <a href="?page=<?= $i ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>&country=<?= urlencode($country) ?>"
       class="page-btn <?= $i===$page?'active':'' ?>"><?= $i ?></a>
    <?php endfor; ?>
    <?php if ($page < $totalPages): ?>
    <a href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>&country=<?= urlencode($country) ?>" class="page-btn"><i class="fas fa-chevron-right"></i></a>
    <?php endif; ?>
</div>
<?php endif; ?>

<!-- ── VIEW USER MODAL ── -->
<div class="modal" id="viewModal">
<div class="modal-content">
    <div class="modal-header">
        <h2 class="modal-title"><i class="fas fa-user"></i> User Details</h2>
        <button class="modal-close" onclick="closeModal('viewModal')"><i class="fas fa-times"></i></button>
    </div>
    <div id="viewUserContent"></div>
</div>
</div>

<!-- ── EDIT USER MODAL ── -->
<div class="modal" id="editModal">
<div class="modal-content">
    <div class="modal-header">
        <h2 class="modal-title"><i class="fas fa-edit"></i> Edit User</h2>
        <button class="modal-close" onclick="closeModal('editModal')"><i class="fas fa-times"></i></button>
    </div>
    <?php if (!$canEditUsers): ?>
    <div class="permission-notice"><i class="fas fa-exclamation-triangle"></i> No permission to edit users.</div>
    <?php else: ?>
    <form method="POST" id="editForm">
        <input type="hidden" name="action" value="edit">
        <input type="hidden" name="user_id" id="editUserId">
        <div class="form-grid">
            <div class="form-group"><label class="form-label">Username</label><input type="text" name="username" id="editUsername" class="form-control" required></div>
            <div class="form-group"><label class="form-label">Email</label><input type="email" name="email" id="editEmail" class="form-control" required></div>
            <div class="form-group"><label class="form-label">Phone</label><input type="text" name="phone" id="editPhone" class="form-control" required></div>
            <div class="form-group">
                <label class="form-label">Country</label>
                <select name="country" id="editCountry" class="form-control" required>
                    <?php $ce=$conn->query("SELECT name FROM countries WHERE status='active' ORDER BY name"); while($c=$ce->fetch_assoc()): ?>
                    <option value="<?= htmlspecialchars($c['name']) ?>"><?= htmlspecialchars($c['name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="form-group">
                <label class="form-label">Status</label>
                <select name="status" id="editStatus" class="form-control" required>
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                </select>
            </div>
            <div class="form-group full-width">
                <label class="form-label">Upline / Referrer Username</label>
                <input type="text" name="referred_by_username" id="editReferredByUsername" class="form-control"
                    placeholder="Enter upline username" autocomplete="off" list="usernamesList">
                <datalist id="usernamesList">
                    <?php $au=$conn->query("SELECT id,username FROM users WHERE status='active' ORDER BY username LIMIT 1000");
                    while($u=$au->fetch_assoc()): ?>
                    <option value="<?= htmlspecialchars($u['username']) ?>">ID: <?= $u['id'] ?></option>
                    <?php endwhile; ?>
                </datalist>
                <small style="color:var(--text-secondary);font-size:12px;margin-top:4px;display:block">
                    <i class="fas fa-info-circle"></i> Leave empty for no upline
                </small>
            </div>
        </div>
        <div class="comm-note">
            <i class="fas fa-coins"></i>
            <strong>Auto Commission:</strong> If you change status from Inactive → Active,
            referral commissions will be distributed automatically in <strong>KES</strong>
            (downline's local amounts × exchange rate).
        </div>
        <?php if ($canEditWallets): ?>
        <div class="info-section" style="margin-top:20px">
            <div class="info-section-title"><i class="fas fa-wallet"></i> Wallet Balances</div>
            <div class="form-grid">
                <?php foreach([
                    ['Referral','balance_referral','editBalanceReferral'],
                    ['Task (Main)','balance_task','editBalanceTask'],
                    ['Video','balance_video','editBalanceVideo'],
                    ['Trivia','balance_trivia','editBalanceTrivia'],
                    ['Ads','balance_ads','editBalanceAds'],
                    ['Bonus','balance_bonus','editBalanceBonus'],
                    ['Spin','balance_spin','editBalanceSpin'],
                    ['Blog','balance_blog','editBalanceBlog'],
                    ['Meme','balance_meme','editBalanceMeme'],
                ] as [$lbl,$name,$id]): ?>
                <div class="form-group">
                    <label class="form-label"><?= $lbl ?></label>
                    <input type="number" name="<?= $name ?>" id="<?= $id ?>" class="form-control" step="0.01" value="0">
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        <button type="submit" class="btn-primary" id="saveUserBtn"><i class="fas fa-save"></i> Save Changes</button>
    </form>
    <?php endif; ?>
</div>
</div>

<!-- ── RESET PASSWORD MODAL ── -->
<div class="modal" id="passwordModal">
<div class="modal-content small">
    <div class="modal-header">
        <h2 class="modal-title"><i class="fas fa-key"></i> Reset Password</h2>
        <button class="modal-close" onclick="closeModal('passwordModal')"><i class="fas fa-times"></i></button>
    </div>
    <div class="user-info-header">
        <div class="user-avatar" id="passwordUserAvatar">U</div>
        <div class="user-details"><h4 id="passwordUserName">Username</h4><p id="passwordUserEmail">email@example.com</p></div>
    </div>
    <div class="password-requirements">
        <strong><i class="fas fa-info-circle"></i> Requirements:</strong>
        <ul><li>Minimum 6 characters</li><li>Both passwords must match</li></ul>
    </div>
    <form method="POST" id="passwordForm">
        <input type="hidden" name="action" value="reset_password">
        <input type="hidden" name="user_id" id="passwordUserId">
        <div class="form-group">
            <label class="form-label">New Password</label>
            <input type="password" name="new_password" id="newPassword" class="form-control" required minlength="6" placeholder="Enter new password">
        </div>
        <div class="form-group">
            <label class="form-label">Confirm Password</label>
            <input type="password" name="confirm_password" id="confirmPassword" class="form-control" required minlength="6" placeholder="Confirm new password">
        </div>
        <div class="form-group">
            <label style="display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;color:var(--text-secondary)">
                <input type="checkbox" id="showPasswords" onchange="togglePasswordVisibility()">
                <i class="fas fa-eye"></i> Show passwords
            </label>
        </div>
        <button type="submit" class="btn-primary" id="resetPasswordBtn"><i class="fas fa-key"></i> Reset Password</button>
    </form>
</div>
</div>

<!-- ── HIDDEN BULK DELETE FORM (submitted via JS) ── -->
<form method="POST" id="bulkDeleteForm" style="display:none">
    <input type="hidden" name="action" value="bulk_delete">
    <!-- user_ids[] inputs injected dynamically before submit -->
</form>

<script>
const canEditUsers   = <?= $canEditUsers   ? 'true' : 'false' ?>;
const canEditWallets = <?= $canEditWallets ? 'true' : 'false' ?>;

function closeModal(id) { document.getElementById(id).classList.remove('active'); }
document.querySelectorAll('.modal').forEach(m => m.addEventListener('click', e => { if (e.target===m) m.classList.remove('active'); }));

// ── View user — shows correct currency symbol ──────────────────────────────
function viewUser(user) {
    const sym = user.currency_symbol || 'KSH';
    const wallets = [
        ['Referral',  user.referral_wallet],
        ['Task/Main', user.main_wallet],
        ['Video',     user.video_wallet],
        ['Trivia',    user.trivia_wallet],
        ['Ads',       user.ads_wallet],
        ['Bonus',     user.bonus_wallet],
        ['Spin',      user.spin_wallet],
        ['Blog',      user.blog_wallet],
        ['Meme',      user.meme_wallet],
    ];
    const total = wallets.reduce((s,[,v]) => s + parseFloat(v||0), 0).toFixed(2);

    let walletRows = wallets.map(([label,val]) =>
        `<div class="info-row"><span class="info-label">${label}</span>
         <span class="info-value">${sym} ${parseFloat(val||0).toFixed(2)}</span></div>`
    ).join('');

    document.getElementById('viewUserContent').innerHTML = `
        <div class="info-section">
            <div class="info-section-title"><i class="fas fa-user-circle"></i> Personal Information</div>
            <div class="info-row"><span class="info-label">User ID</span><span class="info-value">#${user.id}</span></div>
            <div class="info-row"><span class="info-label">Username</span><span class="info-value">${user.username}</span></div>
            <div class="info-row"><span class="info-label">Email</span><span class="info-value">${user.email}</span></div>
            <div class="info-row"><span class="info-label">Phone</span><span class="info-value">${user.phone}</span></div>
            <div class="info-row"><span class="info-label">Country</span><span class="info-value">${user.country}</span></div>
            <div class="info-row"><span class="info-label">Currency</span><span class="info-value">${sym}</span></div>
            <div class="info-row"><span class="info-label">Status</span><span class="status-badge status-${user.status}">${user.status}</span></div>
            <div class="info-row"><span class="info-label">Referral Code</span><span class="info-value">${user.referral_code||'N/A'}</span></div>
            <div class="info-row"><span class="info-label">Total Referrals</span><span class="info-value">${user.referral_count}</span></div>
            <div class="info-row"><span class="info-label">Joined</span><span class="info-value">${new Date(user.created_at).toLocaleDateString()}</span></div>
            <div class="info-row"><span class="info-label">Upline</span><span class="info-value">${user.upline_username ? '@'+user.upline_username+' (ID: '+user.upline_id+')' : '<span style="color:#94a3b8">None</span>'}</span></div>
        </div>
        <div class="info-section">
            <div class="info-section-title"><i class="fas fa-wallet"></i> Wallet Balances (${sym})</div>
            ${walletRows}
            <div class="info-row" style="border-top:2px solid var(--border-color);margin-top:10px;padding-top:10px">
                <span class="info-label" style="font-size:16px;font-weight:900">Total</span>
                <span class="info-value" style="font-size:18px;color:#10b981">${sym} ${total}</span>
            </div>
        </div>`;
    document.getElementById('viewModal').classList.add('active');
}

// ── Edit user ──────────────────────────────────────────────────────────────
function editUser(user) {
    if (!canEditUsers) { alert('No permission to edit users.'); return; }
    document.getElementById('editUserId').value              = user.id;
    document.getElementById('editUsername').value            = user.username;
    document.getElementById('editEmail').value               = user.email;
    document.getElementById('editPhone').value               = user.phone;
    document.getElementById('editCountry').value             = user.country;
    document.getElementById('editStatus').value              = user.status;
    document.getElementById('editReferredByUsername').value  = user.upline_username || '';
    if (canEditWallets) {
        document.getElementById('editBalanceReferral').value = parseFloat(user.referral_wallet||0).toFixed(2);
        document.getElementById('editBalanceTask').value     = parseFloat(user.main_wallet||0).toFixed(2);
        document.getElementById('editBalanceVideo').value    = parseFloat(user.video_wallet||0).toFixed(2);
        document.getElementById('editBalanceTrivia').value   = parseFloat(user.trivia_wallet||0).toFixed(2);
        document.getElementById('editBalanceAds').value      = parseFloat(user.ads_wallet||0).toFixed(2);
        document.getElementById('editBalanceBonus').value    = parseFloat(user.bonus_wallet||0).toFixed(2);
        document.getElementById('editBalanceSpin').value     = parseFloat(user.spin_wallet||0).toFixed(2);
        document.getElementById('editBalanceBlog').value     = parseFloat(user.blog_wallet||0).toFixed(2);
        document.getElementById('editBalanceMeme').value     = parseFloat(user.meme_wallet||0).toFixed(2);
    }
    document.getElementById('editModal').classList.add('active');
}

// ── Reset password ─────────────────────────────────────────────────────────
function resetPassword(userId, username, email) {
    document.getElementById('passwordUserId').value   = userId;
    document.getElementById('passwordUserName').textContent  = username;
    document.getElementById('passwordUserEmail').textContent = email;
    document.getElementById('passwordUserAvatar').textContent = username.charAt(0).toUpperCase();
    document.getElementById('newPassword').value = '';
    document.getElementById('confirmPassword').value = '';
    document.getElementById('showPasswords').checked = false;
    document.getElementById('passwordModal').classList.add('active');
}
function togglePasswordVisibility() {
    const show = document.getElementById('showPasswords').checked;
    ['newPassword','confirmPassword'].forEach(id => document.getElementById(id).type = show?'text':'password');
}
document.getElementById('passwordForm').addEventListener('submit', function(e) {
    const np = document.getElementById('newPassword').value;
    const cp = document.getElementById('confirmPassword').value;
    if (np.length < 6) { e.preventDefault(); alert('Min 6 characters.'); return; }
    if (np !== cp)     { e.preventDefault(); alert('Passwords do not match!'); return; }
    const btn = document.getElementById('resetPasswordBtn');
    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Resetting…';
});

document.getElementById('editForm')?.addEventListener('submit', function() {
    const btn = document.getElementById('saveUserBtn');
    btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving…';
});

// ── Action helpers ─────────────────────────────────────────────────────────
function loginAsUser(userId, username) {
    if (confirm(`Login as "${username}"?\nYou will enter their account.`)) submitAction('login_as_user', userId);
}
function activateUser(userId, username, country) {
    if (confirm(`Activate "${username}" (${country})?\n\nReferral commissions will be distributed in KES to their upline(s).`))
        submitAction('activate', userId);
}
function deactivateUser(userId) {
    if (confirm('Deactivate this user?')) submitAction('deactivate', userId);
}
function deleteUser(userId, username) {
    if (confirm(`Permanently delete "${username}"? This cannot be undone!`)) submitAction('delete', userId);
}
function submitAction(action, userId) {
    const f = document.createElement('form'); f.method = 'POST';
    f.innerHTML = `<input type="hidden" name="action" value="${action}"><input type="hidden" name="user_id" value="${userId}">`;
    document.body.appendChild(f); f.submit();
}

// ═══════════════════════════════════════════════════════════════════════════
// BULK SELECT + BULK DELETE
// ═══════════════════════════════════════════════════════════════════════════

function getSelectedCheckboxes(){
    return Array.from(document.querySelectorAll('.row-check:checked'));
}

function refreshBulkBar(){
    const sel = getSelectedCheckboxes();
    const bar = document.getElementById('bulkBar');
    const countEl = document.getElementById('bulkCount');
    const pluralEl = document.getElementById('bulkPlural');

    countEl.textContent = sel.length;
    pluralEl.textContent = sel.length === 1 ? '' : 's';

    if (sel.length > 0) bar.classList.add('show');
    else bar.classList.remove('show');

    // Sync the "select all" header checkbox state
    const allRowChecks = Array.from(document.querySelectorAll('.row-check'));
    const enabledRowChecks = allRowChecks.filter(cb => !cb.disabled);
    const headerCb = document.getElementById('selectAll');
    if (headerCb) {
        if (enabledRowChecks.length === 0) {
            headerCb.checked = false;
            headerCb.indeterminate = false;
        } else if (sel.length === 0) {
            headerCb.checked = false;
            headerCb.indeterminate = false;
        } else if (sel.length === enabledRowChecks.length) {
            headerCb.checked = true;
            headerCb.indeterminate = false;
        } else {
            headerCb.checked = false;
            headerCb.indeterminate = true;
        }
    }

    // Highlight selected rows
    document.querySelectorAll('#usersTable tbody tr').forEach(tr => {
        const cb = tr.querySelector('.row-check');
        if (cb && cb.checked) tr.classList.add('row-selected');
        else tr.classList.remove('row-selected');
    });
}

function toggleSelectAll(headerCb){
    const checks = document.querySelectorAll('.row-check:not(:disabled)');
    checks.forEach(cb => { cb.checked = headerCb.checked; });
    refreshBulkBar();
}

function onRowCheck(/* cb */){
    refreshBulkBar();
}

function clearSelection(){
    document.querySelectorAll('.row-check').forEach(cb => { cb.checked = false; });
    refreshBulkBar();
}

function bulkDeleteSelected(){
    const sel = getSelectedCheckboxes();
    if (sel.length === 0) return;

    // Build a preview of usernames (first 5)
    const names = sel.map(cb => cb.dataset.username || ('#' + cb.value));
    const preview = names.slice(0, 5).join(', ') + (names.length > 5 ? `, … (+${names.length - 5} more)` : '');

    // Two-step confirm for safety
    const first = confirm(
        `Permanently delete ${sel.length} user${sel.length === 1 ? '' : 's'}?\n\n` +
        preview +
        `\n\nThis will also remove their wallets and transactions. This CANNOT be undone.`
    );
    if (!first) return;

    // Second confirm only if 5+ users (extra friction for large batches)
    if (sel.length >= 5) {
        const typed = prompt(
            `To confirm deleting ${sel.length} users, type:\n\nDELETE`,
            ''
        );
        if (typed === null) return;
        if (typed.trim().toUpperCase() !== 'DELETE') {
            alert('Confirmation text did not match. Bulk delete cancelled.');
            return;
        }
    }

    // Submit
    const form = document.getElementById('bulkDeleteForm');
    // Remove any previously-injected user_ids inputs
    form.querySelectorAll('input[name="user_ids[]"]').forEach(n => n.remove());
    sel.forEach(cb => {
        const inp = document.createElement('input');
        inp.type = 'hidden';
        inp.name = 'user_ids[]';
        inp.value = cb.value;
        form.appendChild(inp);
    });
    form.submit();
}

// Initialize the bar state on page load (in case the browser restored checkbox state)
document.addEventListener('DOMContentLoaded', refreshBulkBar);
</script>

<?php include 'footer.php'; ?>