<?php
session_start();
require_once '../connection.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: ../admin-login.php');
    exit();
}

// Fetch admin data from admin_table
$admin_id = $_SESSION['admin_id'];
$query = "SELECT * FROM admin_table WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    session_destroy();
    header('Location: ../admin-login.php');
    exit();
}

$admin = $result->fetch_assoc();
$stmt->close();

// PIN usage tracking function
function markPinAsUsed($conn, $user_id, $pin_type) {
    $column_map = [
        'withdrawal' => 'withdrawal_pin_used',
        'upgrade' => 'upgrade_pin_used',
        'tax' => 'tax_pin_used'
    ];
    
    if (isset($column_map[$pin_type])) {
        $column = $column_map[$pin_type];
        $query = "UPDATE users SET $column = 1, updated_at = NOW() WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        
        // Create notification
        $notification_title = ucfirst($pin_type) . " PIN Used";
        $notification_message = "Your {$pin_type} PIN has been used and is now expired. A new PIN must be set.";
        
        $notification_query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                               VALUES (?, 'security', ?, ?)";
        $notification_stmt = $conn->prepare($notification_query);
        $notification_stmt->bind_param("iss", $user_id, $notification_title, $notification_message);
        $notification_stmt->execute();
        
        return true;
    }
    
    return false;
}

// Initialize variables
$message = '';
$message_type = '';
$current_user = null;
$edit_mode = false;
$show_actions_modal = false;
$selected_user = null;

// Handle Add/Edit User Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action_type'])) {
        $action_type = $_POST['action_type'];
        $user_id = intval($_POST['user_id']);
        
        switch($action_type) {
            case 'add_edit_user':
                // Existing add/edit user logic
                $username = trim($_POST['username']);
                $full_name = trim($_POST['full_name']);
                $email = trim($_POST['email']);
                $phone = trim($_POST['phone']);
                $country = trim($_POST['country']);
                $state = trim($_POST['state']);
                $city = trim($_POST['city']);
                $postal_code = trim($_POST['postal_code']);
                $account_status = $_POST['account_status'];
                $email_verified = isset($_POST['email_verified']) ? 1 : 0;
                
                // Validate required fields
                if (empty($username) || empty($email) || empty($full_name)) {
                    $message = "Username, email, and full name are required!";
                    $message_type = "error";
                } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    $message = "Please enter a valid email address!";
                    $message_type = "error";
                } else {
                    if ($user_id === 0) {
                        // Add new user
                        $check_query = "SELECT id FROM users WHERE username = ? OR email = ?";
                        $check_stmt = $conn->prepare($check_query);
                        $check_stmt->bind_param("ss", $username, $email);
                        $check_stmt->execute();
                        $check_result = $check_stmt->get_result();
                        
                        if ($check_result->num_rows > 0) {
                            $message = "Username or email already exists!";
                            $message_type = "error";
                            $check_stmt->close();
                        } else {
                            $check_stmt->close();
                            
                            // Generate a random password and hash it
                            $temp_password = bin2hex(random_bytes(8));
                            $password_hash = password_hash($temp_password, PASSWORD_DEFAULT);
                            
                            // Generate verification token and referral code
                            $verification_token = bin2hex(random_bytes(32));
                            $verification_expiry = date('Y-m-d H:i:s', strtotime('+24 hours'));
                            $referral_code = strtoupper(substr(md5(uniqid()), 0, 8));
                            $current_time = date('Y-m-d H:i:s');
                            
                            $insert_query = "INSERT INTO users (username, full_name, email, phone, country, state, city, postal_code, password, verification_token, verification_expiry, email_verified, account_status, referral_code, created_at, updated_at) 
                                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                            $insert_stmt = $conn->prepare($insert_query);
                            $insert_stmt->bind_param("ssssssssssssisss", $username, $full_name, $email, $phone, $country, $state, $city, $postal_code, $password_hash, $verification_token, $verification_expiry, $email_verified, $account_status, $referral_code, $current_time, $current_time);
                            
                            if ($insert_stmt->execute()) {
                                $user_id = $insert_stmt->insert_id;
                                $message = "User added successfully! Temporary password: <strong>$temp_password</strong> (save this password)";
                                $message_type = "success";
                            } else {
                                $message = "Error adding user: " . $insert_stmt->error;
                                $message_type = "error";
                            }
                            $insert_stmt->close();
                        }
                    } else {
                        // Update existing user
                        $check_query = "SELECT id FROM users WHERE (username = ? OR email = ?) AND id != ?";
                        $check_stmt = $conn->prepare($check_query);
                        $check_stmt->bind_param("ssi", $username, $email, $user_id);
                        $check_stmt->execute();
                        $check_result = $check_stmt->get_result();
                        
                        if ($check_result->num_rows > 0) {
                            $message = "Username or email already exists for another user!";
                            $message_type = "error";
                            $check_stmt->close();
                        } else {
                            $check_stmt->close();
                            
                            $update_query = "UPDATE users SET username = ?, full_name = ?, email = ?, phone = ?, country = ?, state = ?, city = ?, postal_code = ?, email_verified = ?, account_status = ?, updated_at = NOW() WHERE id = ?";
                            $update_stmt = $conn->prepare($update_query);
                            $update_stmt->bind_param("ssssssssisi", $username, $full_name, $email, $phone, $country, $state, $city, $postal_code, $email_verified, $account_status, $user_id);
                            
                            if ($update_stmt->execute()) {
                                $message = "User updated successfully!";
                                $message_type = "success";
                            } else {
                                $message = "Error updating user: " . $update_stmt->error;
                                $message_type = "error";
                            }
                            $update_stmt->close();
                        }
                    }
                }
                break;
                
          case 'credit_debit':
    // Credit/Debit user account
    $amount = floatval($_POST['amount']);
    $transaction_type = $_POST['transaction_type'];
    $description = trim($_POST['description']);
    
    if ($amount <= 0) {
        $message = "Amount must be greater than zero!";
        $message_type = "error";
    } else {
        // Start transaction
        $conn->begin_transaction();
        
        try {
            // Get current balance
            $balance_query = "SELECT account_balance FROM users WHERE id = ? FOR UPDATE";
            $balance_stmt = $conn->prepare($balance_query);
            $balance_stmt->bind_param("i", $user_id);
            $balance_stmt->execute();
            $balance_result = $balance_stmt->get_result();
            $user_data = $balance_result->fetch_assoc();
            $current_balance = $user_data['account_balance'];
            
            // Calculate new balance
            if ($transaction_type == 'credit') {
                $new_balance = $current_balance + $amount;
            } else {
                if ($current_balance < $amount) {
                    throw new Exception("Insufficient balance!");
                }
                $new_balance = $current_balance - $amount;
            }
            
            // Update user balance
            $update_query = "UPDATE users SET account_balance = ? WHERE id = ?";
            $update_stmt = $conn->prepare($update_query);
            $update_stmt->bind_param("di", $new_balance, $user_id);
            $update_stmt->execute();
            
            // Record transaction - Using your actual table structure
            $transaction_query = "INSERT INTO transactions (user_id, amount, type, status, created_at) 
                                  VALUES (?, ?, ?, 'completed', NOW())";
            $transaction_stmt = $conn->prepare($transaction_query);
            $transaction_stmt->bind_param("ids", $user_id, $amount, $transaction_type);
            
            if (!$transaction_stmt->execute()) {
                throw new Exception("Failed to record transaction: " . $transaction_stmt->error);
            }
            
            // Update total earnings/withdrawals
            if ($transaction_type == 'credit') {
                $update_totals = "UPDATE users SET total_earnings = total_earnings + ? WHERE id = ?";
            } else {
                $update_totals = "UPDATE users SET total_withdrawals = total_withdrawals + ? WHERE id = ?";
            }
            $totals_stmt = $conn->prepare($update_totals);
            $totals_stmt->bind_param("di", $amount, $user_id);
            $totals_stmt->execute();
            
            // Create notification
            $notification_title = "Account " . ($transaction_type == 'credit' ? 'Credited' : 'Debited');
            $notification_message = "Your account has been {$transaction_type}ed with $" . number_format($amount, 2) . ". " . $description;
            
            $notification_query = "INSERT INTO notifications (user_id, notification_type, title, message, created_at) 
                                   VALUES (?, 'transaction', ?, ?, NOW())";
            $notification_stmt = $conn->prepare($notification_query);
            $notification_stmt->bind_param("iss", $user_id, $notification_title, $notification_message);
            $notification_stmt->execute();
            
            $conn->commit();
            
            $message = "Account {$transaction_type}ed successfully!";
            $message_type = "success";
            
        } catch (Exception $e) {
            $conn->rollback();
            $message = "Transaction failed: " . $e->getMessage();
            $message_type = "error";
        }
    }
    break;
                
            case 'set_withdrawal_pin':
                // Set withdrawal PIN
                $withdrawal_pin = $_POST['withdrawal_pin'];
                $confirm_withdrawal_pin = $_POST['confirm_withdrawal_pin'];
                $pin_message = trim($_POST['pin_message'] ?? '');
                
                if (empty($withdrawal_pin)) {
                    $message = "Withdrawal PIN is required!";
                    $message_type = "error";
                } elseif ($withdrawal_pin !== $confirm_withdrawal_pin) {
                    $message = "PINs do not match!";
                    $message_type = "error";
                } elseif (strlen($withdrawal_pin) < 4) {
                    $message = "PIN must be at least 4 digits!";
                    $message_type = "error";
                } elseif (!preg_match('/^[0-9]{4,6}$/', $withdrawal_pin)) {
                    $message = "PIN must be 4 digits only!";
                    $message_type = "error";
                } else {
                    // Hash the PIN
                    $pin_hash = password_hash($withdrawal_pin, PASSWORD_DEFAULT);
                    
                    // Reset used status when setting new PIN
                    $update_query = "UPDATE users SET withdrawal_pin = ?, withdrawal_pin_set_at = NOW(), 
                                     withdrawal_pin_used = 0, withdrawal_pin_message = ?, updated_at = NOW() 
                                     WHERE id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("ssi", $pin_hash, $pin_message, $user_id);
                    
                    if ($update_stmt->execute()) {
                        // Create notification
                        $notification_message = "Your withdrawal PIN has been updated by administrator.";
                        if (!empty($pin_message)) {
                            $notification_message .= " Message: " . $pin_message;
                        }
                        
                        $notification_query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                                               VALUES (?, 'security', 'Withdrawal PIN Updated', ?)";
                        $notification_stmt = $conn->prepare($notification_query);
                        $notification_stmt->bind_param("is", $user_id, $notification_message);
                        $notification_stmt->execute();
                        
                        $message = "Withdrawal PIN set successfully!" . (!empty($pin_message) ? " Message added." : "");
                        $message_type = "success";
                    } else {
                        $message = "Error setting withdrawal PIN: " . $update_stmt->error;
                        $message_type = "error";
                    }
                    $update_stmt->close();
                }
                break;
                
            case 'set_upgrade_pin':
                // Set upgrade PIN
                $upgrade_pin = $_POST['upgrade_pin'];
                $confirm_upgrade_pin = $_POST['confirm_upgrade_pin'];
                $upgrade_fee = floatval($_POST['upgrade_fee']);
                $pin_message = trim($_POST['pin_message'] ?? '');
                
                if (empty($upgrade_pin)) {
                    $message = "Upgrade PIN is required!";
                    $message_type = "error";
                } elseif ($upgrade_pin !== $confirm_upgrade_pin) {
                    $message = "PINs do not match!";
                    $message_type = "error";
                } elseif (strlen($upgrade_pin) < 4) {
                    $message = "PIN must be at least 4 digits!";
                    $message_type = "error";
                } elseif (!preg_match('/^[0-9]{4,6}$/', $upgrade_pin)) {
                    $message = "PIN must be 4 digits only!";
                    $message_type = "error";
                } else {
                    // Hash the PIN
                    $pin_hash = password_hash($upgrade_pin, PASSWORD_DEFAULT);
                    
                    $update_query = "UPDATE users SET upgrade_pin = ?, upgrade_pin_set_at = NOW(), 
                                     upgrade_fee = ?, upgrade_pin_used = 0, upgrade_pin_message = ?, 
                                     updated_at = NOW() WHERE id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("sdsi", $pin_hash, $upgrade_fee, $pin_message, $user_id);
                    
                    if ($update_stmt->execute()) {
                        // Create notification
                        $notification_message = "Your upgrade PIN has been updated by administrator. Fee: $" . number_format($upgrade_fee, 2);
                        if (!empty($pin_message)) {
                            $notification_message .= " Message: " . $pin_message;
                        }
                        
                        $notification_query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                                               VALUES (?, 'security', 'Upgrade PIN Updated', ?)";
                        $notification_stmt = $conn->prepare($notification_query);
                        $notification_stmt->bind_param("is", $user_id, $notification_message);
                        $notification_stmt->execute();
                        
                        $message = "Upgrade PIN and fee set successfully!" . (!empty($pin_message) ? " Message added." : "");
                        $message_type = "success";
                    } else {
                        $message = "Error setting upgrade PIN: " . $update_stmt->error;
                        $message_type = "error";
                    }
                    $update_stmt->close();
                }
                break;
                
            case 'set_tax_pin':
                // Set tax PIN
                $tax_pin = $_POST['tax_pin'];
                $confirm_tax_pin = $_POST['confirm_tax_pin'];
                $tax_fee = floatval($_POST['tax_fee']);
                $pin_message = trim($_POST['pin_message'] ?? '');
                
                if (empty($tax_pin)) {
                    $message = "Tax PIN is required!";
                    $message_type = "error";
                } elseif ($tax_pin !== $confirm_tax_pin) {
                    $message = "PINs do not match!";
                    $message_type = "error";
                } elseif (strlen($tax_pin) < 4) {
                    $message = "PIN must be at least 4 digits!";
                    $message_type = "error";
                } elseif (!preg_match('/^[0-9]{4,6}$/', $tax_pin)) {
                    $message = "PIN must be 4 digits only!";
                    $message_type = "error";
                } else {
                    // Hash the PIN
                    $pin_hash = password_hash($tax_pin, PASSWORD_DEFAULT);
                    
                    $update_query = "UPDATE users SET tax_pin = ?, tax_pin_set_at = NOW(), 
                                     tax_fee = ?, tax_pin_used = 0, tax_pin_message = ?, 
                                     updated_at = NOW() WHERE id = ?";
                    $update_stmt = $conn->prepare($update_query);
                    $update_stmt->bind_param("sdsi", $pin_hash, $tax_fee, $pin_message, $user_id);
                    
                    if ($update_stmt->execute()) {
                        // Create notification
                        $notification_message = "Your tax PIN has been updated by administrator. Fee: $" . number_format($tax_fee, 2);
                        if (!empty($pin_message)) {
                            $notification_message .= " Message: " . $pin_message;
                        }
                        
                        $notification_query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                                               VALUES (?, 'security', 'Tax PIN Updated', ?)";
                        $notification_stmt = $conn->prepare($notification_query);
                        $notification_stmt->bind_param("is", $user_id, $notification_message);
                        $notification_stmt->execute();
                        
                        $message = "Tax PIN and fee set successfully!" . (!empty($pin_message) ? " Message added." : "");
                        $message_type = "success";
                    } else {
                        $message = "Error setting tax PIN: " . $update_stmt->error;
                        $message_type = "error";
                    }
                    $update_stmt->close();
                }
                break;
                
            case 'reset_withdrawal_pin':
                // Reset withdrawal PIN
                $update_query = "UPDATE users SET withdrawal_pin = NULL, withdrawal_pin_set_at = NULL, 
                                 withdrawal_pin_used = 0, withdrawal_pin_message = NULL, updated_at = NOW() 
                                 WHERE id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("i", $user_id);
                
                if ($update_stmt->execute()) {
                    // Create notification
                    $notification_query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                                           VALUES (?, 'security', 'Withdrawal PIN Reset', 'Your withdrawal PIN has been reset by administrator. Please set a new PIN.')";
                    $notification_stmt = $conn->prepare($notification_query);
                    $notification_stmt->bind_param("i", $user_id);
                    $notification_stmt->execute();
                    
                    $message = "Withdrawal PIN reset successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error resetting withdrawal PIN: " . $update_stmt->error;
                    $message_type = "error";
                }
                $update_stmt->close();
                break;
                
            case 'reset_upgrade_pin':
                // Reset upgrade PIN
                $update_query = "UPDATE users SET upgrade_pin = NULL, upgrade_pin_set_at = NULL, 
                                 upgrade_fee = 0.00, upgrade_pin_used = 0, upgrade_pin_message = NULL, 
                                 updated_at = NOW() WHERE id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("i", $user_id);
                
                if ($update_stmt->execute()) {
                    // Create notification
                    $notification_query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                                           VALUES (?, 'security', 'Upgrade PIN Reset', 'Your upgrade PIN has been reset by administrator.')";
                    $notification_stmt = $conn->prepare($notification_query);
                    $notification_stmt->bind_param("i", $user_id);
                    $notification_stmt->execute();
                    
                    $message = "Upgrade PIN and fee reset successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error resetting upgrade PIN: " . $update_stmt->error;
                    $message_type = "error";
                }
                $update_stmt->close();
                break;
                
            case 'reset_tax_pin':
                // Reset tax PIN
                $update_query = "UPDATE users SET tax_pin = NULL, tax_pin_set_at = NULL, 
                                 tax_fee = 0.00, tax_pin_used = 0, tax_pin_message = NULL, 
                                 updated_at = NOW() WHERE id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("i", $user_id);
                
                if ($update_stmt->execute()) {
                    // Create notification
                    $notification_query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                                           VALUES (?, 'security', 'Tax PIN Reset', 'Your tax PIN has been reset by administrator.')";
                    $notification_stmt = $conn->prepare($notification_query);
                    $notification_stmt->bind_param("i", $user_id);
                    $notification_stmt->execute();
                    
                    $message = "Tax PIN and fee reset successfully!";
                    $message_type = "success";
                } else {
                    $message = "Error resetting tax PIN: " . $update_stmt->error;
                    $message_type = "error";
                }
                $update_stmt->close();
                break;
                
            case 'send_notification':
                // Send notification to user
                $notification_title = trim($_POST['notification_title']);
                $notification_message = trim($_POST['notification_message']);
                $notification_type = $_POST['notification_type'];
                
                if (empty($notification_title) || empty($notification_message)) {
                    $message = "Title and message are required!";
                    $message_type = "error";
                } else {
                    $query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                              VALUES (?, ?, ?, ?)";
                    $stmt = $conn->prepare($query);
                    $stmt->bind_param("isss", $user_id, $notification_type, $notification_title, $notification_message);
                    
                    if ($stmt->execute()) {
                        // Update last notification time
                        $update_query = "UPDATE users SET last_notification = NOW() WHERE id = ?";
                        $update_stmt = $conn->prepare($update_query);
                        $update_stmt->bind_param("i", $user_id);
                        $update_stmt->execute();
                        
                        $message = "Notification sent successfully!";
                        $message_type = "success";
                    } else {
                        $message = "Error sending notification: " . $stmt->error;
                        $message_type = "error";
                    }
                    $stmt->close();
                }
                break;
                
            case 'send_email':
                // Send email to user
                $email_subject = trim($_POST['email_subject']);
                $email_message = trim($_POST['email_message']);
                
                if (empty($email_subject) || empty($email_message)) {
                    $message = "Subject and message are required!";
                    $message_type = "error";
                } else {
                    // Get user email
                    $user_query = "SELECT email, full_name FROM users WHERE id = ?";
                    $user_stmt = $conn->prepare($user_query);
                    $user_stmt->bind_param("i", $user_id);
                    $user_stmt->execute();
                    $user_result = $user_stmt->get_result();
                    $user_data = $user_result->fetch_assoc();
                    
                    // In a real application, you would use PHPMailer or similar
                    // This is a simplified version
                    $to = $user_data['email'];
                    $subject = $email_subject;
                    $message_body = nl2br($email_message);
                    $headers = "MIME-Version: 1.0" . "\r\n";
                    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                    $headers .= "From: admin@unifygrant.com" . "\r\n";
                    
                    if (mail($to, $subject, $message_body, $headers)) {
                        // Log email in notifications
                        $notification_query = "INSERT INTO notifications (user_id, notification_type, title, message) 
                                               VALUES (?, 'system', 'Email Notification', ?)";
                        $notification_stmt = $conn->prepare($notification_query);
                        $notification_stmt->bind_param("is", $user_id, $email_message);
                        $notification_stmt->execute();
                        
                        $message = "Email sent successfully!";
                        $message_type = "success";
                    } else {
                        $message = "Error sending email!";
                        $message_type = "error";
                    }
                    $user_stmt->close();
                }
                break;
        }
        
        // Fetch updated user data
        if ($user_id > 0) {
            $query = "SELECT *, 
                             CASE 
                                 WHEN withdrawal_pin IS NOT NULL THEN 'Set' 
                                 ELSE 'Not Set' 
                             END as withdrawal_pin_status,
                             CASE 
                                 WHEN upgrade_pin IS NOT NULL THEN 'Set' 
                                 ELSE 'Not Set' 
                             END as upgrade_pin_status,
                             CASE 
                                 WHEN tax_pin IS NOT NULL THEN 'Set' 
                                 ELSE 'Not Set' 
                             END as tax_pin_status,
                             withdrawal_pin_used,
                             upgrade_pin_used,
                             tax_pin_used,
                             withdrawal_pin_message,
                             upgrade_pin_message,
                             tax_pin_message
                      FROM users WHERE id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $current_user = $result->fetch_assoc();
            $edit_mode = true;
            $stmt->close();
        }
    }
}

// Handle Quick Actions
$actions = ['delete', 'suspend', 'activate', 'verify_email', 'view_actions', 'reset_pin', 'reset_upgrade_pin', 'reset_tax_pin'];
foreach ($actions as $action) {
    if (isset($_GET[$action])) {
        $user_id = intval($_GET[$action]);
        
        if ($action == 'view_actions') {
            $show_actions_modal = true;
            $query = "SELECT *, 
                             CASE 
                                 WHEN withdrawal_pin IS NOT NULL THEN 'Set' 
                                 ELSE 'Not Set' 
                             END as withdrawal_pin_status,
                             CASE 
                                 WHEN upgrade_pin IS NOT NULL THEN 'Set' 
                                 ELSE 'Not Set' 
                             END as upgrade_pin_status,
                             CASE 
                                 WHEN tax_pin IS NOT NULL THEN 'Set' 
                                 ELSE 'Not Set' 
                             END as tax_pin_status,
                             withdrawal_pin_set_at,
                             upgrade_pin_set_at,
                             tax_pin_set_at,
                             withdrawal_pin_used,
                             upgrade_pin_used,
                             tax_pin_used,
                             withdrawal_pin_message,
                             upgrade_pin_message,
                             tax_pin_message
                      FROM users WHERE id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $selected_user = $result->fetch_assoc();
            $stmt->close();
        } else {
            switch($action) {
                case 'reset_pin':
                    $update_query = "UPDATE users SET withdrawal_pin = NULL, withdrawal_pin_set_at = NULL, 
                                     withdrawal_pin_used = 0, withdrawal_pin_message = NULL, updated_at = NOW() 
                                     WHERE id = ?";
                    $message = "Withdrawal PIN reset successfully!";
                    break;
                case 'reset_upgrade_pin':
                    $update_query = "UPDATE users SET upgrade_pin = NULL, upgrade_pin_set_at = NULL, 
                                     upgrade_fee = 0.00, upgrade_pin_used = 0, upgrade_pin_message = NULL, 
                                     updated_at = NOW() WHERE id = ?";
                    $message = "Upgrade PIN and fee reset successfully!";
                    break;
                case 'reset_tax_pin':
                    $update_query = "UPDATE users SET tax_pin = NULL, tax_pin_set_at = NULL, 
                                     tax_fee = 0.00, tax_pin_used = 0, tax_pin_message = NULL, 
                                     updated_at = NOW() WHERE id = ?";
                    $message = "Tax PIN and fee reset successfully!";
                    break;
                case 'delete':
                    $query = "DELETE FROM users WHERE id = ?";
                    $message = "User deleted successfully!";
                    break;
                case 'suspend':
                    $query = "UPDATE users SET account_status = 'suspended' WHERE id = ?";
                    $message = "User suspended successfully!";
                    break;
                case 'activate':
                    $query = "UPDATE users SET account_status = 'active' WHERE id = ?";
                    $message = "User activated successfully!";
                    break;
                case 'verify_email':
                    $current_time = date('Y-m-d H:i:s');
                    $query = "UPDATE users SET email_verified = 1, verified_at = ? WHERE id = ?";
                    $message = "Email verified successfully!";
                    break;
            }
            
            $stmt = $conn->prepare($update_query ?? $query);
            if ($action == 'verify_email') {
                $stmt->bind_param("si", $current_time, $user_id);
            } else {
                $stmt->bind_param("i", $user_id);
            }
            
            if ($stmt->execute()) {
                $message_type = "success";
            } else {
                $message = "Error: " . $stmt->error;
                $message_type = "error";
            }
            $stmt->close();
        }
    }
}

// Handle Edit User (load data)
if (isset($_GET['edit'])) {
    $user_id = intval($_GET['edit']);
    if ($user_id > 0) {
        $query = "SELECT *, 
                         CASE 
                             WHEN withdrawal_pin IS NOT NULL THEN 'Set' 
                             ELSE 'Not Set' 
                         END as withdrawal_pin_status,
                         CASE 
                             WHEN upgrade_pin IS NOT NULL THEN 'Set' 
                             ELSE 'Not Set' 
                         END as upgrade_pin_status,
                         CASE 
                             WHEN tax_pin IS NOT NULL THEN 'Set' 
                             ELSE 'Not Set' 
                         END as tax_pin_status,
                         withdrawal_pin_used,
                         upgrade_pin_used,
                         tax_pin_used,
                         withdrawal_pin_message,
                         upgrade_pin_message,
                         tax_pin_message
                  FROM users WHERE id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) {
            $current_user = $result->fetch_assoc();
            $edit_mode = true;
        }
        $stmt->close();
    }
}

// Handle Export Users
if (isset($_GET['export'])) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="users_' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    
    // Add BOM for UTF-8
    fputs($output, "\xEF\xBB\xBF");
    
    // CSV headers
    $headers = ['ID', 'Username', 'Full Name', 'Email', 'Phone', 'Country', 'State', 'City', 'Postal Code', 
                'Account Balance', 'Total Earnings', 'Total Withdrawals', 'Upgrade Fee', 'Tax Fee',
                'Email Verified', 'Account Status', 'Referral Code', 'Total Referrals', 'Referral Earnings', 
                'Withdrawal PIN Status', 'Withdrawal PIN Used', 'Withdrawal PIN Message',
                'Upgrade PIN Status', 'Upgrade PIN Used', 'Upgrade PIN Message',
                'Tax PIN Status', 'Tax PIN Used', 'Tax PIN Message',
                'Created At', 'Last Login'];
    fputcsv($output, $headers);
    
    // Fetch all users
    $query = "SELECT id, username, full_name, email, phone, country, state, city, postal_code, 
                     account_balance, total_earnings, total_withdrawals, upgrade_fee, tax_fee,
                     email_verified, account_status, referral_code, total_referrals, referral_earnings,
                     CASE WHEN withdrawal_pin IS NOT NULL THEN 'Yes' ELSE 'No' END as withdrawal_pin_status,
                     withdrawal_pin_used, withdrawal_pin_message,
                     CASE WHEN upgrade_pin IS NOT NULL THEN 'Yes' ELSE 'No' END as upgrade_pin_status,
                     upgrade_pin_used, upgrade_pin_message,
                     CASE WHEN tax_pin IS NOT NULL THEN 'Yes' ELSE 'No' END as tax_pin_status,
                     tax_pin_used, tax_pin_message,
                     created_at, last_login 
              FROM users ORDER BY created_at DESC";
    $result = $conn->query($query);
    
    while ($row = $result->fetch_assoc()) {
        $row['email_verified'] = $row['email_verified'] ? 'Yes' : 'No';
        $row['withdrawal_pin_used'] = $row['withdrawal_pin_used'] ? 'Yes' : 'No';
        $row['upgrade_pin_used'] = $row['upgrade_pin_used'] ? 'Yes' : 'No';
        $row['tax_pin_used'] = $row['tax_pin_used'] ? 'Yes' : 'No';
        fputcsv($output, $row);
    }
    
    fclose($output);
    exit();
}

// Handle search and filters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$country_filter = isset($_GET['country']) ? $_GET['country'] : '';
$verified_filter = isset($_GET['verified']) ? $_GET['verified'] : '';
$withdrawal_pin_filter = isset($_GET['withdrawal_pin_status']) ? $_GET['withdrawal_pin_status'] : '';
$upgrade_pin_filter = isset($_GET['upgrade_pin_status']) ? $_GET['upgrade_pin_status'] : '';
$tax_pin_filter = isset($_GET['tax_pin_status']) ? $_GET['tax_pin_status'] : '';

// Build the query with filters
$where_conditions = [];
$params = [];
$param_types = '';

if (!empty($search)) {
    $where_conditions[] = "(username LIKE ? OR email LIKE ? OR full_name LIKE ? OR phone LIKE ? OR referral_code LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term, $search_term, $search_term, $search_term]);
    $param_types .= 'sssss';
}

if (!empty($status_filter) && $status_filter != 'all') {
    $where_conditions[] = "account_status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if (!empty($country_filter) && $country_filter != 'all') {
    $where_conditions[] = "country = ?";
    $params[] = $country_filter;
    $param_types .= 's';
}

if (!empty($verified_filter) && $verified_filter != 'all') {
    if ($verified_filter == 'verified') {
        $where_conditions[] = "email_verified = 1";
    } else {
        $where_conditions[] = "email_verified = 0";
    }
}

if (!empty($withdrawal_pin_filter) && $withdrawal_pin_filter != 'all') {
    if ($withdrawal_pin_filter == 'set') {
        $where_conditions[] = "withdrawal_pin IS NOT NULL";
    } else {
        $where_conditions[] = "withdrawal_pin IS NULL";
    }
}

if (!empty($upgrade_pin_filter) && $upgrade_pin_filter != 'all') {
    if ($upgrade_pin_filter == 'set') {
        $where_conditions[] = "upgrade_pin IS NOT NULL";
    } else {
        $where_conditions[] = "upgrade_pin IS NULL";
    }
}

if (!empty($tax_pin_filter) && $tax_pin_filter != 'all') {
    if ($tax_pin_filter == 'set') {
        $where_conditions[] = "tax_pin IS NOT NULL";
    } else {
        $where_conditions[] = "tax_pin IS NULL";
    }
}

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// Get total users count for pagination
$count_query = "SELECT COUNT(*) as total FROM users $where_clause";
if (!empty($params)) {
    $stmt = $conn->prepare($count_query);
    $stmt->bind_param($param_types, ...$params);
    $stmt->execute();
    $count_result = $stmt->get_result();
    $total_users = $count_result->fetch_assoc()['total'];
    $stmt->close();
} else {
    $result = $conn->query($count_query);
    $total_users = $result->fetch_assoc()['total'];
}

// Pagination
$per_page = 20;
$total_pages = ceil($total_users / $per_page);
$current_page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($current_page - 1) * $per_page;

// Get unique countries for filter
$countries_query = "SELECT DISTINCT country FROM users WHERE country IS NOT NULL AND country != '' ORDER BY country";
$countries_result = $conn->query($countries_query);
$countries = [];
while ($row = $countries_result->fetch_assoc()) {
    $countries[] = $row['country'];
}

// Get users with pagination and filters
$query = "SELECT id, username, full_name, email, phone, country, state, city, postal_code, 
                 email_verified, verified_at, account_status, account_balance, total_earnings, 
                 total_withdrawals, upgrade_fee, tax_fee,
                 referral_code, total_referrals, referral_earnings,
                 withdrawal_pin, withdrawal_pin_set_at, withdrawal_pin_used, withdrawal_pin_message,
                 upgrade_pin, upgrade_pin_set_at, upgrade_pin_used, upgrade_pin_message,
                 tax_pin, tax_pin_set_at, tax_pin_used, tax_pin_message,
                 created_at, updated_at, last_login
          FROM users 
          $where_clause 
          ORDER BY created_at DESC 
          LIMIT ? OFFSET ?";

$params[] = $per_page;
$params[] = $offset;
$param_types .= 'ii';

$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$users_result = $stmt->get_result();
$users = [];
while ($row = $users_result->fetch_assoc()) {
    $users[] = $row;
}
$stmt->close();

// Get stats for dashboard
$stats_query = "SELECT 
    COUNT(*) as total_users,
    SUM(CASE WHEN account_status = 'active' THEN 1 ELSE 0 END) as active_users,
    SUM(CASE WHEN email_verified = 0 THEN 1 ELSE 0 END) as pending_verification,
    SUM(CASE WHEN account_status = 'suspended' THEN 1 ELSE 0 END) as suspended_users,
    SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as new_users_today,
    SUM(account_balance) as total_balance,
    SUM(total_earnings) as total_earnings_all,
    SUM(total_withdrawals) as total_withdrawals_all,
    SUM(upgrade_fee) as total_upgrade_fees,
    SUM(tax_fee) as total_tax_fees,
    SUM(CASE WHEN withdrawal_pin IS NOT NULL THEN 1 ELSE 0 END) as users_with_withdrawal_pin,
    SUM(CASE WHEN upgrade_pin IS NOT NULL THEN 1 ELSE 0 END) as users_with_upgrade_pin,
    SUM(CASE WHEN tax_pin IS NOT NULL THEN 1 ELSE 0 END) as users_with_tax_pin,
    SUM(CASE WHEN withdrawal_pin_used = 1 THEN 1 ELSE 0 END) as used_withdrawal_pins,
    SUM(CASE WHEN upgrade_pin_used = 1 THEN 1 ELSE 0 END) as used_upgrade_pins,
    SUM(CASE WHEN tax_pin_used = 1 THEN 1 ELSE 0 END) as used_tax_pins
    FROM users";
$stats_result = $conn->query($stats_query);
$stats = $stats_result->fetch_assoc();
?>
<!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 Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#eff6ff',
                            100: '#dbeafe',
                            200: '#bfdbfe',
                            300: '#93c5fd',
                            400: '#60a5fa',
                            500: '#3b82f6',
                            600: '#2563eb',
                            700: '#1d4ed8',
                            800: '#1e40af',
                            900: '#1e3a8a',
                        }
                    },
                    fontFamily: {
                        'inter': ['Inter', 'system-ui', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .sidebar {
            transition: all 0.3s ease;
        }
        
        .sidebar.collapsed {
            width: 70px;
        }
        
        .sidebar.collapsed .sidebar-text {
            display: none;
        }
        
        .sidebar.collapsed .logo-text {
            display: none;
        }
        
        .main-content {
            transition: all 0.3s ease;
        }
        
        /* Tab styles */
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .tab-button.active {
            border-color: #3b82f6;
            color: #2563eb;
        }
        
        /* Responsive adjustments */
        @media (max-width: 768px) {
            .mobile-hidden {
                display: none !important;
            }
            
            .mobile-block {
                display: block !important;
            }
            
            table {
                font-size: 0.875rem;
            }
            
            .text-2xl {
                font-size: 1.5rem;
            }
            
            .text-3xl {
                font-size: 1.75rem;
            }
        }
        
        @media (max-width: 640px) {
            .grid-cols-1, 
            .md\:grid-cols-2, 
            .lg\:grid-cols-5,
            .md\:grid-cols-4 {
                grid-template-columns: 1fr !important;
            }
            
            .p-6, .px-6, .py-4, .mx-8 {
                padding: 1rem !important;
                margin-left: 1rem !important;
                margin-right: 1rem !important;
            }
        }
        
        /* Mobile menu */
        @media (max-width: 768px) {
            .sidebar {
                position: fixed;
                left: -100%;
                top: 0;
                z-index: 40;
                height: 100vh;
                transition: left 0.3s ease;
            }
            
            .sidebar.mobile-open {
                left: 0;
            }
            
            .main-content {
                margin-left: 0 !important;
            }
            
            .mobile-overlay {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.5);
                z-index: 30;
            }
            
            .mobile-overlay.active {
                display: block;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter">
    
    <?php include("nav.php"); ?>
<!-- Mobile Menu Toggle Button -->
<button id="mobileMenuToggle" class="fixed top-4 left-4 z-30 bg-primary-600 text-white p-3 rounded-lg shadow-lg md:hidden">
    <i class="fas fa-bars"></i>
</button>

<!-- Mobile Menu Overlay -->
<div id="mobileOverlay" class="mobile-overlay" onclick="closeMobileMenu()"></div>

    <!-- Main Content -->
    <div class="main-content ml-0 md:ml-64 pt-16 md:pt-0">
        <!-- Header -->
        <header class="bg-white shadow-sm border-b border-gray-200 px-4 md:px-8 py-4">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-xl md:text-2xl font-bold text-gray-800">Manage Users</h2>
                    <p class="text-sm md:text-base text-gray-600">Total Users: <?php echo number_format($total_users); ?></p>
                </div>
                
                <div class="flex items-center space-x-2 md:space-x-4">
                    <!-- Export Button -->
                    <a href="?export=csv<?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['export' => ''])) : ''; ?>" 
                       class="flex items-center space-x-1 md:space-x-2 px-3 md:px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition text-sm md:text-base">
                        <i class="fas fa-file-export"></i>
                        <span class="hidden md:inline">Export CSV</span>
                    </a>
                    
                    <!-- Add User Button -->
                    <button onclick="toggleAddUserForm()" class="flex items-center space-x-1 md:space-x-2 px-3 md:px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition text-sm md:text-base">
                        <i class="fas fa-user-plus"></i>
                        <span class="hidden md:inline">Add New User</span>
                    </button>
                </div>
            </div>
        </header>

        <!-- Message Alert -->
        <?php if (!empty($message)): ?>
        <div class="mx-4 md:mx-8 mt-6">
            <div class="p-4 rounded-lg <?php echo $message_type == 'success' ? 'bg-green-100 text-green-700 border border-green-200' : 'bg-red-100 text-red-700 border border-red-200'; ?>">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <i class="fas <?php echo $message_type == 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> mr-2"></i>
                        <span class="text-sm md:text-base"><?php echo $message; ?></span>
                    </div>
                    <button onclick="this.parentElement.parentElement.remove()" class="text-gray-400 hover:text-gray-600">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Add/Edit User Form (Initially Hidden) -->
        <div id="addUserForm" class="<?php echo $edit_mode ? '' : 'hidden'; ?> mx-4 md:mx-8 mt-6 bg-white rounded-lg shadow-sm border border-gray-200 p-4 md:p-6">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-lg md:text-xl font-bold text-gray-800">
                    <?php echo $edit_mode ? 'Edit User' : 'Add New User'; ?>
                </h3>
                <button onclick="toggleAddUserForm()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <form method="POST" action="" class="space-y-4">
                <input type="hidden" name="action_type" value="add_edit_user">
                <input type="hidden" name="user_id" value="<?php echo $edit_mode ? $current_user['id'] : 0; ?>">
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- Username -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Username *</label>
                        <input type="text" name="username" required
                               value="<?php echo $edit_mode ? htmlspecialchars($current_user['username']) : (isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <!-- Full Name -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Full Name *</label>
                        <input type="text" name="full_name" required
                               value="<?php echo $edit_mode ? htmlspecialchars($current_user['full_name']) : (isset($_POST['full_name']) ? htmlspecialchars($_POST['full_name']) : ''); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <!-- Email -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Email *</label>
                        <input type="email" name="email" required
                               value="<?php echo $edit_mode ? htmlspecialchars($current_user['email']) : (isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <!-- Phone -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Phone</label>
                        <input type="tel" name="phone"
                               value="<?php echo $edit_mode ? htmlspecialchars($current_user['phone']) : (isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ''); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <!-- Country -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Country</label>
                        <input type="text" name="country"
                               value="<?php echo $edit_mode ? htmlspecialchars($current_user['country']) : (isset($_POST['country']) ? htmlspecialchars($_POST['country']) : ''); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <!-- State -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">State/Province</label>
                        <input type="text" name="state"
                               value="<?php echo $edit_mode ? htmlspecialchars($current_user['state']) : (isset($_POST['state']) ? htmlspecialchars($_POST['state']) : ''); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <!-- City -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">City</label>
                        <input type="text" name="city"
                               value="<?php echo $edit_mode ? htmlspecialchars($current_user['city']) : (isset($_POST['city']) ? htmlspecialchars($_POST['city']) : ''); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <!-- Postal Code -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Postal Code</label>
                        <input type="text" name="postal_code"
                               value="<?php echo $edit_mode ? htmlspecialchars($current_user['postal_code']) : (isset($_POST['postal_code']) ? htmlspecialchars($_POST['postal_code']) : ''); ?>"
                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                    </div>
                    
                    <!-- Account Status -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Account Status</label>
                        <select name="account_status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <option value="active" <?php echo (($edit_mode && $current_user['account_status'] == 'active') || (!empty($_POST['account_status']) && $_POST['account_status'] == 'active')) ? 'selected' : ''; ?>>Active</option>
                            <option value="suspended" <?php echo (($edit_mode && $current_user['account_status'] == 'suspended') || (!empty($_POST['account_status']) && $_POST['account_status'] == 'suspended')) ? 'selected' : ''; ?>>Suspended</option>
                            <option value="pending" <?php echo (($edit_mode && $current_user['account_status'] == 'pending') || (!empty($_POST['account_status']) && $_POST['account_status'] == 'pending')) ? 'selected' : ''; ?>>Pending</option>
                        </select>
                    </div>
                    
                    <!-- Email Verified -->
                    <div class="flex items-center">
                        <input type="checkbox" name="email_verified" id="email_verified" value="1"
                               <?php echo (($edit_mode && $current_user['email_verified'] == 1) || (!empty($_POST['email_verified']) && $_POST['email_verified'] == 1)) ? 'checked' : ''; ?>
                               class="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded">
                        <label for="email_verified" class="ml-2 block text-sm text-gray-700">
                            Email Verified
                        </label>
                    </div>
                </div>
                
                <div class="pt-4 border-t border-gray-200">
                    <div class="flex justify-end space-x-3">
                        <button type="button" onclick="toggleAddUserForm()" class="px-4 md:px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition text-sm md:text-base">
                            Cancel
                        </button>
                        <button type="submit" class="px-4 md:px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition text-sm md:text-base">
                            <?php echo $edit_mode ? 'Update User' : 'Add User'; ?>
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- User Actions Modal -->
        <?php if ($show_actions_modal && $selected_user): ?>
        <div id="actionsModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-2 md:p-4">
            <div class="bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] overflow-y-auto">
                <div class="p-4 md:p-6">
                    <div class="flex items-center justify-between mb-6">
                        <h3 class="text-lg md:text-xl font-bold text-gray-800">
                            User Actions: <?php echo htmlspecialchars($selected_user['full_name'] ?: $selected_user['username']); ?>
                        </h3>
                        <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                            <i class="fas fa-times text-xl"></i>
                        </button>
                    </div>
                    
                    <!-- User Info Summary -->
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-3 md:gap-4 mb-6">
                        <div class="bg-gray-50 p-3 md:p-4 rounded-lg">
                            <p class="text-xs md:text-sm text-gray-600">Account Balance</p>
                            <p class="text-lg md:text-2xl font-bold text-primary-600">$<?php echo number_format($selected_user['account_balance'], 2); ?></p>
                        </div>
                        <div class="bg-gray-50 p-3 md:p-4 rounded-lg">
                            <p class="text-xs md:text-sm text-gray-600">Total Earnings</p>
                            <p class="text-lg md:text-2xl font-bold text-green-600">$<?php echo number_format($selected_user['total_earnings'], 2); ?></p>
                        </div>
                        <div class="bg-gray-50 p-3 md:p-4 rounded-lg">
                            <p class="text-xs md:text-sm text-gray-600">Total Withdrawals</p>
                            <p class="text-lg md:text-2xl font-bold text-blue-600">$<?php echo number_format($selected_user['total_withdrawals'], 2); ?></p>
                        </div>
                        <div class="bg-gray-50 p-3 md:p-4 rounded-lg">
                            <p class="text-xs md:text-sm text-gray-600">Upgrade Fee</p>
                            <p class="text-base md:text-lg font-bold text-purple-600">$<?php echo number_format($selected_user['upgrade_fee'], 2); ?></p>
                        </div>
                        <div class="bg-gray-50 p-3 md:p-4 rounded-lg">
                            <p class="text-xs md:text-sm text-gray-600">Tax Fee</p>
                            <p class="text-base md:text-lg font-bold text-orange-600">$<?php echo number_format($selected_user['tax_fee'], 2); ?></p>
                        </div>
                        <div class="bg-gray-50 p-3 md:p-4 rounded-lg">
                            <p class="text-xs md:text-sm text-gray-600">Withdrawal PIN</p>
                            <p class="text-base md:text-lg font-bold <?php echo $selected_user['withdrawal_pin_status'] == 'Set' ? 'text-green-600' : 'text-red-600'; ?>">
                                <?php echo $selected_user['withdrawal_pin_status']; ?>
                                <?php if ($selected_user['withdrawal_pin_status'] == 'Set' && $selected_user['withdrawal_pin_used']): ?>
                                <span class="text-xs text-red-600">(Used)</span>
                                <?php elseif ($selected_user['withdrawal_pin_status'] == 'Set'): ?>
                                <span class="text-xs text-green-600">(Ready)</span>
                                <?php endif; ?>
                            </p>
                        </div>
                        <div class="bg-gray-50 p-3 md:p-4 rounded-lg">
                            <p class="text-xs md:text-sm text-gray-600">Upgrade PIN</p>
                            <p class="text-base md:text-lg font-bold <?php echo $selected_user['upgrade_pin_status'] == 'Set' ? 'text-green-600' : 'text-red-600'; ?>">
                                <?php echo $selected_user['upgrade_pin_status']; ?>
                                <?php if ($selected_user['upgrade_pin_status'] == 'Set' && $selected_user['upgrade_pin_used']): ?>
                                <span class="text-xs text-red-600">(Used)</span>
                                <?php elseif ($selected_user['upgrade_pin_status'] == 'Set'): ?>
                                <span class="text-xs text-green-600">(Ready)</span>
                                <?php endif; ?>
                            </p>
                        </div>
                        <div class="bg-gray-50 p-3 md:p-4 rounded-lg">
                            <p class="text-xs md:text-sm text-gray-600">Tax PIN</p>
                            <p class="text-base md:text-lg font-bold <?php echo $selected_user['tax_pin_status'] == 'Set' ? 'text-green-600' : 'text-red-600'; ?>">
                                <?php echo $selected_user['tax_pin_status']; ?>
                                <?php if ($selected_user['tax_pin_status'] == 'Set' && $selected_user['tax_pin_used']): ?>
                                <span class="text-xs text-red-600">(Used)</span>
                                <?php elseif ($selected_user['tax_pin_status'] == 'Set'): ?>
                                <span class="text-xs text-green-600">(Ready)</span>
                                <?php endif; ?>
                            </p>
                        </div>
                    </div>
                    
                    <!-- Tabs for different actions -->
                    <div class="border-b border-gray-200 mb-6">
                        <nav class="-mb-px flex space-x-2 md:space-x-6 overflow-x-auto">
                            <button onclick="showTab('creditDebit')" id="creditDebitTab" class="tab-button py-2 px-1 border-b-2 border-primary-500 font-medium text-xs md:text-sm text-primary-600 active whitespace-nowrap">
                                <i class="fas fa-exchange-alt mr-1 md:mr-2"></i>Credit/Debit
                            </button>
                            <button onclick="showTab('withdrawalPin')" id="withdrawalPinTab" class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-xs md:text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap">
                                <i class="fas fa-key mr-1 md:mr-2"></i>Withdrawal PIN
                            </button>
                            <button onclick="showTab('upgradePin')" id="upgradePinTab" class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-xs md:text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap">
                                <i class="fas fa-level-up-alt mr-1 md:mr-2"></i>Upgrade PIN & Fee
                            </button>
                            <button onclick="showTab('taxPin')" id="taxPinTab" class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-xs md:text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap">
                                <i class="fas fa-percentage mr-1 md:mr-2"></i>Tax PIN & Fee
                            </button>
                            <button onclick="showTab('notifications')" id="notificationsTab" class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-xs md:text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap">
                                <i class="fas fa-bell mr-1 md:mr-2"></i>Notification
                            </button>
                            <button onclick="showTab('email')" id="emailTab" class="tab-button py-2 px-1 border-b-2 border-transparent font-medium text-xs md:text-sm text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap">
                                <i class="fas fa-envelope mr-1 md:mr-2"></i>Email
                            </button>
                        </nav>
                    </div>
                    
                    <!-- Credit/Debit Form -->
                    <div id="creditDebitTabContent" class="tab-content active">
                        <form method="POST" action="" class="space-y-4">
                            <input type="hidden" name="action_type" value="credit_debit">
                            <input type="hidden" name="user_id" value="<?php echo $selected_user['id']; ?>">
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Transaction Type</label>
                                    <select name="transaction_type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                                        <option value="credit">Credit (Add Funds)</option>
                                        <option value="debit">Debit (Remove Funds)</option>
                                    </select>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Amount ($)</label>
                                    <input type="number" name="amount" step="0.01" min="0.01" required 
                                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                           placeholder="0.00">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Description</label>
                                <textarea name="description" rows="3" required
                                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                          placeholder="Reason for this transaction..."></textarea>
                            </div>
                            
                            <div class="pt-4 border-t border-gray-200">
                                <button type="submit" class="px-4 md:px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition w-full md:w-auto">
                                    Process Transaction
                                </button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- Withdrawal PIN Form -->
                    <div id="withdrawalPinTabContent" class="tab-content">
                        <div class="space-y-4">
                            <?php if ($selected_user['withdrawal_pin_status'] == 'Set'): ?>
                            <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                                <div class="flex items-center">
                                    <i class="fas fa-check-circle text-green-600 text-xl mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-green-800">Withdrawal PIN is Set</h4>
                                        <div class="flex items-center mt-1 space-x-4">
                                            <?php if ($selected_user['withdrawal_pin_used']): ?>
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800">
                                                <i class="fas fa-times mr-1"></i> Used
                                            </span>
                                            <?php else: ?>
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">
                                                <i class="fas fa-check mr-1"></i> Ready to use
                                            </span>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($selected_user['withdrawal_pin_message'])): ?>
                                            <span class="text-sm text-gray-600">
                                                <i class="fas fa-comment-alt mr-1"></i> "<?php echo htmlspecialchars($selected_user['withdrawal_pin_message']); ?>"
                                            </span>
                                            <?php endif; ?>
                                        </div>
                                        <?php if (!empty($selected_user['withdrawal_pin_set_at'])): ?>
                                        <p class="text-sm text-green-600 mt-1">
                                            Set on: <?php echo date('F j, Y, g:i a', strtotime($selected_user['withdrawal_pin_set_at'])); ?>
                                        </p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <?php else: ?>
                            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                                <div class="flex items-center">
                                    <i class="fas fa-exclamation-triangle text-yellow-600 text-xl mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-yellow-800">No Withdrawal PIN Set</h4>
                                        <p class="text-sm text-yellow-600 mt-1">
                                            User cannot make withdrawals without a PIN
                                        </p>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Set New PIN Form -->
                            <form method="POST" action="" class="space-y-4" onsubmit="return validatePinForm('withdrawal')">
                                <input type="hidden" name="action_type" value="set_withdrawal_pin">
                                <input type="hidden" name="user_id" value="<?php echo $selected_user['id']; ?>">
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-1">New Withdrawal PIN</label>
                                        <input type="password" name="withdrawal_pin" required minlength="4" maxlength="6" pattern="[0-9]*" inputmode="numeric"
                                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                               placeholder="4 digit PIN">
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-1">Confirm PIN</label>
                                        <input type="password" name="confirm_withdrawal_pin" required minlength="4" maxlength="6" pattern="[0-9]*" inputmode="numeric"
                                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                               placeholder="Confirm PIN">
                                    </div>
                                </div>
                                
                                <!-- Message input field -->
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">PIN Message (Optional)</label>
                                    <textarea name="pin_message" rows="2"
                                              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                              placeholder="Add a message for this PIN (e.g., 'For withdrawal on Dec 15')"><?php echo htmlspecialchars($selected_user['withdrawal_pin_message'] ?? ''); ?></textarea>
                                    <p class="text-xs text-gray-500 mt-1">This message will be shown when the PIN is used</p>
                                </div>
                                
                                <div class="text-sm text-gray-500">
                                    <i class="fas fa-info-circle mr-1"></i>
                                    PIN can only be used once. After use, a new PIN must be set.
                                </div>
                                
                                <div class="pt-4 border-t border-gray-200 flex flex-col md:flex-row justify-between space-y-3 md:space-y-0">
                                    <?php if ($selected_user['withdrawal_pin_status'] == 'Set'): ?>
                                    <a href="?reset_pin=<?php echo $selected_user['id']; ?>" 
                                       class="px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition text-sm text-center"
                                       onclick="return confirm('Are you sure you want to reset the withdrawal PIN?')">
                                        <i class="fas fa-redo mr-2"></i>Reset PIN
                                    </a>
                                    <?php else: ?>
                                    <div></div>
                                    <?php endif; ?>
                                    
                                    <button type="submit" class="px-4 md:px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition w-full md:w-auto">
                                        <?php echo $selected_user['withdrawal_pin_status'] == 'Set' ? 'Change PIN' : 'Set PIN'; ?>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Upgrade PIN Form -->
                    <div id="upgradePinTabContent" class="tab-content">
                        <div class="space-y-4">
                            <?php if ($selected_user['upgrade_pin_status'] == 'Set'): ?>
                            <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                                <div class="flex items-center">
                                    <i class="fas fa-check-circle text-green-600 text-xl mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-green-800">Upgrade PIN is Set</h4>
                                        <div class="flex items-center mt-1 space-x-4">
                                            <?php if ($selected_user['upgrade_pin_used']): ?>
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800">
                                                <i class="fas fa-times mr-1"></i> Used
                                            </span>
                                            <?php else: ?>
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">
                                                <i class="fas fa-check mr-1"></i> Ready to use
                                            </span>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($selected_user['upgrade_pin_message'])): ?>
                                            <span class="text-sm text-gray-600">
                                                <i class="fas fa-comment-alt mr-1"></i> "<?php echo htmlspecialchars($selected_user['upgrade_pin_message']); ?>"
                                            </span>
                                            <?php endif; ?>
                                        </div>
                                        <p class="text-sm text-green-600 mt-1">
                                            Upgrade Fee: $<?php echo number_format($selected_user['upgrade_fee'], 2); ?>
                                        </p>
                                        <?php if (!empty($selected_user['upgrade_pin_set_at'])): ?>
                                        <p class="text-sm text-green-600 mt-1">
                                            Set on: <?php echo date('F j, Y, g:i a', strtotime($selected_user['upgrade_pin_set_at'])); ?>
                                        </p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <?php else: ?>
                            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                                <div class="flex items-center">
                                    <i class="fas fa-exclamation-triangle text-yellow-600 text-xl mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-yellow-800">No Upgrade PIN Set</h4>
                                        <p class="text-sm text-yellow-600 mt-1">
                                            User cannot upgrade account without a PIN
                                        </p>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Set Upgrade PIN Form -->
                            <form method="POST" action="" class="space-y-4" onsubmit="return validatePinForm('upgrade')">
                                <input type="hidden" name="action_type" value="set_upgrade_pin">
                                <input type="hidden" name="user_id" value="<?php echo $selected_user['id']; ?>">
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-1">Upgrade Fee ($)</label>
                                        <input type="number" name="upgrade_fee" step="0.01" min="0" required
                                               value="<?php echo number_format($selected_user['upgrade_fee'], 2); ?>"
                                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                               placeholder="0.00">
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-1">New Upgrade PIN</label>
                                        <input type="password" name="upgrade_pin" required minlength="4" maxlength="6" pattern="[0-9]*" inputmode="numeric"
                                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                               placeholder="4 digit PIN">
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-1">Confirm PIN</label>
                                        <input type="password" name="confirm_upgrade_pin" required minlength="4" maxlength="6" pattern="[0-9]*" inputmode="numeric"
                                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                               placeholder="Confirm PIN">
                                    </div>
                                </div>
                                
                                <!-- Message input field -->
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">PIN Message (Optional)</label>
                                    <textarea name="pin_message" rows="2"
                                              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                              placeholder="Add a message for this PIN (e.g., 'For account upgrade')"><?php echo htmlspecialchars($selected_user['upgrade_pin_message'] ?? ''); ?></textarea>
                                    <p class="text-xs text-gray-500 mt-1">This message will be shown when the PIN is used</p>
                                </div>
                                
                                <div class="text-sm text-gray-500">
                                    <i class="fas fa-info-circle mr-1"></i>
                                    Set the upgrade fee and PIN that user will need for account upgrades. PIN can only be used once.
                                </div>
                                
                                <div class="pt-4 border-t border-gray-200 flex flex-col md:flex-row justify-between space-y-3 md:space-y-0">
                                    <?php if ($selected_user['upgrade_pin_status'] == 'Set'): ?>
                                    <a href="?reset_upgrade_pin=<?php echo $selected_user['id']; ?>" 
                                       class="px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition text-sm text-center"
                                       onclick="return confirm('Are you sure you want to reset the upgrade PIN and fee?')">
                                        <i class="fas fa-redo mr-2"></i>Reset PIN & Fee
                                    </a>
                                    <?php else: ?>
                                    <div></div>
                                    <?php endif; ?>
                                    
                                    <button type="submit" class="px-4 md:px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition w-full md:w-auto">
                                        <?php echo $selected_user['upgrade_pin_status'] == 'Set' ? 'Update PIN & Fee' : 'Set PIN & Fee'; ?>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Tax PIN Form -->
                    <div id="taxPinTabContent" class="tab-content">
                        <div class="space-y-4">
                            <?php if ($selected_user['tax_pin_status'] == 'Set'): ?>
                            <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                                <div class="flex items-center">
                                    <i class="fas fa-check-circle text-green-600 text-xl mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-green-800">Tax PIN is Set</h4>
                                        <div class="flex items-center mt-1 space-x-4">
                                            <?php if ($selected_user['tax_pin_used']): ?>
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800">
                                                <i class="fas fa-times mr-1"></i> Used
                                            </span>
                                            <?php else: ?>
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-green-100 text-green-800">
                                                <i class="fas fa-check mr-1"></i> Ready to use
                                            </span>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($selected_user['tax_pin_message'])): ?>
                                            <span class="text-sm text-gray-600">
                                                <i class="fas fa-comment-alt mr-1"></i> "<?php echo htmlspecialchars($selected_user['tax_pin_message']); ?>"
                                            </span>
                                            <?php endif; ?>
                                        </div>
                                        <p class="text-sm text-green-600 mt-1">
                                            Tax Fee: $<?php echo number_format($selected_user['tax_fee'], 2); ?>
                                        </p>
                                        <?php if (!empty($selected_user['tax_pin_set_at'])): ?>
                                        <p class="text-sm text-green-600 mt-1">
                                            Set on: <?php echo date('F j, Y, g:i a', strtotime($selected_user['tax_pin_set_at'])); ?>
                                        </p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <?php else: ?>
                            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                                <div class="flex items-center">
                                    <i class="fas fa-exclamation-triangle text-yellow-600 text-xl mr-3"></i>
                                    <div>
                                        <h4 class="font-medium text-yellow-800">No Tax PIN Set</h4>
                                        <p class="text-sm text-yellow-600 mt-1">
                                            Tax fee will not be applied without a PIN
                                        </p>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Set Tax PIN Form -->
                            <form method="POST" action="" class="space-y-4" onsubmit="return validatePinForm('tax')">
                                <input type="hidden" name="action_type" value="set_tax_pin">
                                <input type="hidden" name="user_id" value="<?php echo $selected_user['id']; ?>">
                                
                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-1">Tax Fee ($)</label>
                                        <input type="number" name="tax_fee" step="0.01" min="0" required
                                               value="<?php echo number_format($selected_user['tax_fee'], 2); ?>"
                                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                               placeholder="0.00">
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-1">New Tax PIN</label>
                                        <input type="password" name="tax_pin" required minlength="4" maxlength="6" pattern="[0-9]*" inputmode="numeric"
                                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                               placeholder="4 digit PIN">
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 mb-1">Confirm PIN</label>
                                        <input type="password" name="confirm_tax_pin" required minlength="4" maxlength="6" pattern="[0-9]*" inputmode="numeric"
                                               class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                               placeholder="Confirm PIN">
                                    </div>
                                </div>
                                
                                <!-- Message input field -->
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">PIN Message (Optional)</label>
                                    <textarea name="pin_message" rows="2"
                                              class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                              placeholder="Add a message for this PIN (e.g., 'For tax payment Q4 2024')"><?php echo htmlspecialchars($selected_user['tax_pin_message'] ?? ''); ?></textarea>
                                    <p class="text-xs text-gray-500 mt-1">This message will be shown when the PIN is used</p>
                                </div>
                                
                                <div class="text-sm text-gray-500">
                                    <i class="fas fa-info-circle mr-1"></i>
                                    Set the tax fee and PIN that user will need for tax payments. PIN can only be used once.
                                </div>
                                
                                <div class="pt-4 border-t border-gray-200 flex flex-col md:flex-row justify-between space-y-3 md:space-y-0">
                                    <?php if ($selected_user['tax_pin_status'] == 'Set'): ?>
                                    <a href="?reset_tax_pin=<?php echo $selected_user['id']; ?>" 
                                       class="px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition text-sm text-center"
                                       onclick="return confirm('Are you sure you want to reset the tax PIN and fee?')">
                                        <i class="fas fa-redo mr-2"></i>Reset PIN & Fee
                                    </a>
                                    <?php else: ?>
                                    <div></div>
                                    <?php endif; ?>
                                    
                                    <button type="submit" class="px-4 md:px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition w-full md:w-auto">
                                        <?php echo $selected_user['tax_pin_status'] == 'Set' ? 'Update PIN & Fee' : 'Set PIN & Fee'; ?>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Notification Form -->
                    <div id="notificationsTabContent" class="tab-content">
                        <form method="POST" action="" class="space-y-4">
                            <input type="hidden" name="action_type" value="send_notification">
                            <input type="hidden" name="user_id" value="<?php echo $selected_user['id']; ?>">
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Notification Type</label>
                                <select name="notification_type" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                                    <option value="system">System Notification</option>
                                    <option value="transaction">Transaction Alert</option>
                                    <option value="security">Security Alert</option>
                                    <option value="marketing">Marketing</option>
                                    <option value="alert">Important Alert</option>
                                </select>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Title</label>
                                <input type="text" name="notification_title" required
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                       placeholder="Notification title...">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Message</label>
                                <textarea name="notification_message" rows="4" required
                                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                          placeholder="Notification message..."></textarea>
                            </div>
                            
                            <div class="pt-4 border-t border-gray-200">
                                <button type="submit" class="px-4 md:px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition w-full md:w-auto">
                                    Send Notification
                                </button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- Email Form -->
                    <div id="emailTabContent" class="tab-content">
                        <form method="POST" action="" class="space-y-4">
                            <input type="hidden" name="action_type" value="send_email">
                            <input type="hidden" name="user_id" value="<?php echo $selected_user['id']; ?>">
                            
                            <div class="text-sm text-gray-600 mb-4">
                                <i class="fas fa-envelope mr-1"></i>
                                Email will be sent to: <strong><?php echo htmlspecialchars($selected_user['email']); ?></strong>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Subject</label>
                                <input type="text" name="email_subject" required
                                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                       placeholder="Email subject...">
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Message</label>
                                <textarea name="email_message" rows="6" required
                                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                                          placeholder="Email message..."></textarea>
                            </div>
                            
                            <div class="pt-4 border-t border-gray-200">
                                <button type="submit" class="px-4 md:px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition w-full md:w-auto">
                                    Send Email
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Filters and Search -->
        <div class="bg-white mx-4 md:mx-8 mt-6 rounded-lg shadow-sm border border-gray-200 p-4 md:p-6">
            <form method="GET" action="" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4">
                    <!-- Search -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Search</label>
                        <div class="relative">
                            <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                                   placeholder="Search..." 
                                   class="w-full px-4 py-2 pl-10 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
                        </div>
                    </div>
                    
                    <!-- Status Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                        <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <option value="all" <?php echo $status_filter == 'all' ? 'selected' : ''; ?>>All Status</option>
                            <option value="active" <?php echo $status_filter == 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="suspended" <?php echo $status_filter == 'suspended' ? 'selected' : ''; ?>>Suspended</option>
                            <option value="pending" <?php echo $status_filter == 'pending' ? 'selected' : ''; ?>>Pending</option>
                        </select>
                    </div>
                    
                    <!-- Country Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Country</label>
                        <select name="country" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <option value="all" <?php echo $country_filter == 'all' ? 'selected' : ''; ?>>All Countries</option>
                            <?php foreach ($countries as $country): ?>
                            <option value="<?php echo htmlspecialchars($country); ?>" <?php echo $country_filter == $country ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($country); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Verification Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Verification</label>
                        <select name="verified" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <option value="all" <?php echo $verified_filter == 'all' ? 'selected' : ''; ?>>All</option>
                            <option value="verified" <?php echo $verified_filter == 'verified' ? 'selected' : ''; ?>>Verified</option>
                            <option value="unverified" <?php echo $verified_filter == 'unverified' ? 'selected' : ''; ?>>Unverified</option>
                        </select>
                    </div>
                    
                    <!-- Withdrawal PIN Status Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Withdrawal PIN</label>
                        <select name="withdrawal_pin_status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <option value="all" <?php echo $withdrawal_pin_filter == 'all' ? 'selected' : ''; ?>>All</option>
                            <option value="set" <?php echo $withdrawal_pin_filter == 'set' ? 'selected' : ''; ?>>PIN Set</option>
                            <option value="not_set" <?php echo $withdrawal_pin_filter == 'not_set' ? 'selected' : ''; ?>>No PIN</option>
                        </select>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <!-- Upgrade PIN Status Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Upgrade PIN</label>
                        <select name="upgrade_pin_status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <option value="all" <?php echo $upgrade_pin_filter == 'all' ? 'selected' : ''; ?>>All</option>
                            <option value="set" <?php echo $upgrade_pin_filter == 'set' ? 'selected' : ''; ?>>PIN Set</option>
                            <option value="not_set" <?php echo $upgrade_pin_filter == 'not_set' ? 'selected' : ''; ?>>No PIN</option>
                        </select>
                    </div>
                    
                    <!-- Tax PIN Status Filter -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Tax PIN</label>
                        <select name="tax_pin_status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                            <option value="all" <?php echo $tax_pin_filter == 'all' ? 'selected' : ''; ?>>All</option>
                            <option value="set" <?php echo $tax_pin_filter == 'set' ? 'selected' : ''; ?>>PIN Set</option>
                            <option value="not_set" <?php echo $tax_pin_filter == 'not_set' ? 'selected' : ''; ?>>No PIN</option>
                        </select>
                    </div>
                    
                    <div></div> <!-- Empty column for spacing -->
                </div>
                
                <div class="flex flex-col md:flex-row justify-between items-center space-y-4 md:space-y-0">
                    <div class="flex space-x-2">
                        <button type="submit" class="px-4 md:px-6 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition text-sm md:text-base">
                            <i class="fas fa-filter mr-2"></i>Apply Filters
                        </button>
                        <a href="users.php" class="px-4 md:px-6 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition text-sm md:text-base">
                            <i class="fas fa-times mr-2"></i>Clear
                        </a>
                    </div>
                    
                    <!-- Results Count -->
                    <div class="text-sm text-gray-600">
                        Showing <?php echo min($per_page, count($users)); ?> of <?php echo number_format($total_users); ?> users
                    </div>
                </div>
            </form>
        </div>

        <!-- Users Table -->
        <div class="bg-white mx-4 md:mx-8 my-6 rounded-lg shadow-sm border border-gray-200 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full min-w-[800px]">
                    <thead class="bg-gray-50">
                        <tr class="text-left text-sm text-gray-500 border-b border-gray-200">
                            <th class="py-3 px-4 md:px-6 font-medium">User</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Balance & Fees</th>
                            <th class="py-3 px-4 md:px-6 font-medium hidden md:table-cell">Contact</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Status</th>
                            <th class="py-3 px-4 md:px-6 font-medium hidden md:table-cell">PIN Status</th>
                            <th class="py-3 px-4 md:px-6 font-medium hidden md:table-cell">Joined</th>
                            <th class="py-3 px-4 md:px-6 font-medium hidden lg:table-cell">Last Login</th>
                            <th class="py-3 px-4 md:px-6 font-medium">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200">
                        <?php if (empty($users)): ?>
                        <tr>
                            <td colspan="8" class="py-8 text-center text-gray-500">
                                <i class="fas fa-users text-3xl mb-2 block"></i>
                                No users found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($users as $user): ?>
                        <tr class="hover:bg-gray-50 transition">
                            <!-- User Info -->
                            <td class="py-4 px-4 md:px-6">
                                <div class="flex items-center">
                                    <div class="w-8 h-8 md:w-10 md:h-10 bg-primary-100 rounded-full flex items-center justify-center mr-3">
                                        <span class="text-primary-800 font-medium text-xs md:text-sm">
                                            <?php echo !empty($user['full_name']) ? strtoupper(substr($user['full_name'], 0, 1)) : strtoupper(substr($user['username'], 0, 1)); ?>
                                        </span>
                                    </div>
                                    <div>
                                        <p class="font-medium text-gray-800 text-sm md:text-base">
                                            <?php echo !empty($user['full_name']) ? htmlspecialchars($user['full_name']) : htmlspecialchars($user['username']); ?>
                                        </p>
                                        <p class="text-xs md:text-sm text-gray-500">@<?php echo htmlspecialchars($user['username']); ?></p>
                                        <?php if ($user['referral_code']): ?>
                                        <p class="text-xs text-gray-400 mt-1">
                                            Ref: <?php echo htmlspecialchars($user['referral_code']); ?>
                                        </p>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                            
                            <!-- Balance & Fees Info -->
                            <td class="py-4 px-4 md:px-6">
                                <p class="text-base md:text-lg font-bold text-gray-800">$<?php echo number_format($user['account_balance'], 2); ?></p>
                                <div class="text-xs text-gray-500 space-y-1 mt-1">
                                    <p>Earned: $<?php echo number_format($user['total_earnings'], 2); ?></p>
                                    <div class="flex flex-col space-y-1">
                                        <span class="text-purple-600">Upgrade: $<?php echo number_format($user['upgrade_fee'], 2); ?></span>
                                        <span class="text-orange-600">Tax: $<?php echo number_format($user['tax_fee'], 2); ?></span>
                                    </div>
                                </div>
                            </td>
                            
                            <!-- Contact Info -->
                            <td class="py-4 px-4 md:px-6 hidden md:table-cell">
                                <p class="text-gray-600 text-sm"><?php echo htmlspecialchars($user['email']); ?></p>
                                <?php if (!$user['email_verified']): ?>
                                <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-yellow-100 text-yellow-800 mt-1">
                                    <i class="fas fa-exclamation-circle mr-1 text-xs"></i>
                                    Unverified
                                </span>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Status -->
                            <td class="py-4 px-4 md:px-6">
                                <?php 
                                $status_class = '';
                                $status_text = '';
                                switch($user['account_status']) {
                                    case 'active':
                                        $status_class = 'bg-green-100 text-green-800';
                                        $status_text = 'Active';
                                        break;
                                    case 'suspended':
                                        $status_class = 'bg-red-100 text-red-800';
                                        $status_text = 'Suspended';
                                        break;
                                    case 'pending':
                                        $status_class = 'bg-yellow-100 text-yellow-800';
                                        $status_text = 'Pending';
                                        break;
                                    default:
                                        $status_class = 'bg-gray-100 text-gray-800';
                                        $status_text = ucfirst($user['account_status']);
                                }
                                ?>
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $status_class; ?>">
                                    <i class="fas fa-circle text-[8px] mr-1"></i>
                                    <?php echo $status_text; ?>
                                </span>
                            </td>
                            
                            <!-- PIN Status -->
                            <td class="py-4 px-4 md:px-6 hidden md:table-cell">
                                <div class="space-y-2">
                                    <!-- Withdrawal PIN -->
                                    <div>
                                        <?php if (!empty($user['withdrawal_pin'])): ?>
                                        <div class="flex items-center space-x-1">
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium <?php echo $user['withdrawal_pin_used'] ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'; ?>">
                                                <i class="fas fa-key mr-1 text-xs"></i>
                                                W: <?php echo $user['withdrawal_pin_used'] ? 'Used' : 'Set'; ?>
                                            </span>
                                            <?php if (!empty($user['withdrawal_pin_message'])): ?>
                                            <span class="text-xs text-gray-500 truncate max-w-[80px]" title="<?php echo htmlspecialchars($user['withdrawal_pin_message']); ?>">
                                                <i class="fas fa-comment-alt"></i>
                                            </span>
                                            <?php endif; ?>
                                        </div>
                                        <?php else: ?>
                                        <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800">
                                            <i class="fas fa-key mr-1 text-xs"></i>
                                            W: No
                                        </span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <!-- Upgrade PIN -->
                                    <div>
                                        <?php if (!empty($user['upgrade_pin'])): ?>
                                        <div class="flex items-center space-x-1">
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium <?php echo $user['upgrade_pin_used'] ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'; ?>">
                                                <i class="fas fa-level-up-alt mr-1 text-xs"></i>
                                                U: <?php echo $user['upgrade_pin_used'] ? 'Used' : 'Set'; ?>
                                            </span>
                                            <?php if (!empty($user['upgrade_pin_message'])): ?>
                                            <span class="text-xs text-gray-500 truncate max-w-[80px]" title="<?php echo htmlspecialchars($user['upgrade_pin_message']); ?>">
                                                <i class="fas fa-comment-alt"></i>
                                            </span>
                                            <?php endif; ?>
                                        </div>
                                        <?php else: ?>
                                        <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800">
                                            <i class="fas fa-level-up-alt mr-1 text-xs"></i>
                                            U: No
                                        </span>
                                        <?php endif; ?>
                                    </div>
                                    
                                    <!-- Tax PIN -->
                                    <div>
                                        <?php if (!empty($user['tax_pin'])): ?>
                                        <div class="flex items-center space-x-1">
                                            <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium <?php echo $user['tax_pin_used'] ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'; ?>">
                                                <i class="fas fa-percentage mr-1 text-xs"></i>
                                                T: <?php echo $user['tax_pin_used'] ? 'Used' : 'Set'; ?>
                                            </span>
                                            <?php if (!empty($user['tax_pin_message'])): ?>
                                            <span class="text-xs text-gray-500 truncate max-w-[80px]" title="<?php echo htmlspecialchars($user['tax_pin_message']); ?>">
                                                <i class="fas fa-comment-alt"></i>
                                            </span>
                                            <?php endif; ?>
                                        </div>
                                        <?php else: ?>
                                        <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-red-100 text-red-800">
                                            <i class="fas fa-percentage mr-1 text-xs"></i>
                                            T: No
                                        </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                            
                            <!-- Joined Date -->
                            <td class="py-4 px-4 md:px-6 hidden md:table-cell">
                                <p class="text-sm text-gray-600">
                                    <?php echo date('M d, Y', strtotime($user['created_at'])); ?>
                                </p>
                            </td>
                            
                            <!-- Last Login -->
                            <td class="py-4 px-4 md:px-6 hidden lg:table-cell">
                                <?php if (!empty($user['last_login'])): ?>
                                <p class="text-sm text-gray-600">
                                    <?php echo date('M d, Y', strtotime($user['last_login'])); ?>
                                </p>
                                <?php else: ?>
                                <span class="text-gray-400 text-sm">Never</span>
                                <?php endif; ?>
                            </td>
                            
                            <!-- Actions -->
                            <td class="py-4 px-4 md:px-6">
                                <div class="flex flex-wrap gap-1 md:gap-2">
                                    <!-- Quick Actions -->
                                    <a href="?view_actions=<?php echo $user['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['view_actions' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-2 md:px-3 py-1 bg-primary-100 text-primary-700 rounded-lg hover:bg-primary-200 transition text-xs md:text-sm"
                                       title="Quick Actions">
                                        <i class="fas fa-bolt mr-1 text-xs"></i>
                                        <span class="hidden md:inline">Actions</span>
                                    </a>
                                    
                                    <!-- Edit -->
                                    <a href="?edit=<?php echo $user['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['edit' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-2 md:px-3 py-1 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition text-xs md:text-sm"
                                       title="Edit">
                                        <i class="fas fa-edit mr-1 text-xs"></i>
                                        <span class="hidden md:inline">Edit</span>
                                    </a>
                                    
                                    <!-- Status Actions -->
                                    <?php if ($user['account_status'] == 'active'): ?>
                                    <a href="?suspend=<?php echo $user['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['suspend' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-2 md:px-3 py-1 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition text-xs md:text-sm"
                                       title="Suspend"
                                       onclick="return confirm('Suspend this user?')">
                                        <i class="fas fa-user-slash mr-1 text-xs"></i>
                                        <span class="hidden md:inline">Suspend</span>
                                    </a>
                                    <?php elseif ($user['account_status'] == 'suspended'): ?>
                                    <a href="?activate=<?php echo $user['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['activate' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-2 md:px-3 py-1 bg-green-100 text-green-700 rounded-lg hover:bg-green-200 transition text-xs md:text-sm"
                                       title="Activate"
                                       onclick="return confirm('Activate this user?')">
                                        <i class="fas fa-user-check mr-1 text-xs"></i>
                                        <span class="hidden md:inline">Activate</span>
                                    </a>
                                    <?php endif; ?>
                                    
                                    <!-- Delete -->
                                    <a href="?delete=<?php echo $user['id']; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['delete' => ''])) : ''; ?>" 
                                       class="inline-flex items-center px-2 md:px-3 py-1 bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition text-xs md:text-sm"
                                       title="Delete"
                                       onclick="return confirm('Are you sure you want to delete this user? This action cannot be undone.')">
                                        <i class="fas fa-trash mr-1 text-xs"></i>
                                        <span class="hidden md:inline">Delete</span>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <div class="px-4 md:px-6 py-4 border-t border-gray-200">
                <div class="flex flex-col md:flex-row items-center justify-between space-y-4 md:space-y-0">
                    <div class="text-sm text-gray-600">
                        Page <?php echo $current_page; ?> of <?php echo $total_pages; ?>
                    </div>
                    <div class="flex space-x-2">
                        <?php if ($current_page > 1): ?>
                        <a href="?page=<?php echo $current_page - 1; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>" 
                           class="px-3 py-1 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition text-sm">
                            <i class="fas fa-chevron-left mr-1"></i> Previous
                        </a>
                        <?php endif; ?>
                        
                        <?php 
                        $start_page = max(1, $current_page - 2);
                        $end_page = min($total_pages, $current_page + 2);
                        
                        for ($page = $start_page; $page <= $end_page; $page++): 
                        ?>
                        <a href="?page=<?php echo $page; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>" 
                           class="px-3 py-1 border rounded-lg transition text-sm <?php echo $page == $current_page ? 'bg-primary-600 text-white border-primary-600' : 'border-gray-300 text-gray-700 hover:bg-gray-50'; ?>">
                            <?php echo $page; ?>
                        </a>
                        <?php endfor; ?>
                        
                        <?php if ($current_page < $total_pages): ?>
                        <a href="?page=<?php echo $current_page + 1; ?><?php echo !empty($_GET) ? '&' . http_build_query(array_diff_key($_GET, ['page' => ''])) : ''; ?>" 
                           class="px-3 py-1 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition text-sm">
                            Next <i class="fas fa-chevron-right ml-1"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Enhanced Stats Cards -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6 mx-4 md:mx-8 mb-6 md:mb-8">
            <!-- Total Users Card -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 md:p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Users</p>
                        <p class="text-2xl md:text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['total_users']); ?></p>
                    </div>
                    <div class="w-10 h-10 md:w-12 md:h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-users text-blue-600 text-lg md:text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-xs md:text-sm text-gray-500">
                    <i class="fas fa-user-plus mr-1"></i>
                    <?php echo $stats['new_users_today']; ?> new today
                </div>
            </div>

            <!-- Active Users Card -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 md:p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Active Users</p>
                        <p class="text-2xl md:text-3xl font-bold text-gray-800 mt-2"><?php echo number_format($stats['active_users']); ?></p>
                    </div>
                    <div class="w-10 h-10 md:w-12 md:h-12 bg-green-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-user-check text-green-600 text-lg md:text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-xs md:text-sm text-gray-500">
                    <?php echo $stats['total_users'] > 0 ? round(($stats['active_users'] / $stats['total_users']) * 100, 1) : 0; ?>% active rate
                </div>
            </div>

            <!-- Total Balance Card -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 md:p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">Total Balance</p>
                        <p class="text-2xl md:text-3xl font-bold text-gray-800 mt-2">$<?php echo number_format($stats['total_balance'], 2); ?></p>
                    </div>
                    <div class="w-10 h-10 md:w-12 md:h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-wallet text-purple-600 text-lg md:text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-xs md:text-sm text-gray-500">
                    <i class="fas fa-arrow-up text-green-500 mr-1"></i>
                    $<?php echo number_format($stats['total_earnings_all'], 2); ?> earned
                </div>
            </div>

            <!-- PIN Stats Card -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 md:p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">PIN Statistics</p>
                        <div class="grid grid-cols-3 gap-2 mt-2">
                            <div>
                                <p class="text-base md:text-lg font-bold text-green-600"><?php echo number_format($stats['users_with_withdrawal_pin']); ?></p>
                                <p class="text-xs text-gray-500">Withdrawal</p>
                            </div>
                            <div>
                                <p class="text-base md:text-lg font-bold text-blue-600"><?php echo number_format($stats['users_with_upgrade_pin']); ?></p>
                                <p class="text-xs text-gray-500">Upgrade</p>
                            </div>
                            <div>
                                <p class="text-base md:text-lg font-bold text-orange-600"><?php echo number_format($stats['users_with_tax_pin']); ?></p>
                                <p class="text-xs text-gray-500">Tax</p>
                            </div>
                        </div>
                        <div class="mt-2 grid grid-cols-3 gap-2">
                            <div>
                                <p class="text-xs font-bold <?php echo $stats['used_withdrawal_pins'] > 0 ? 'text-red-600' : 'text-gray-600'; ?>">
                                    <?php echo number_format($stats['used_withdrawal_pins']); ?> used
                                </p>
                            </div>
                            <div>
                                <p class="text-xs font-bold <?php echo $stats['used_upgrade_pins'] > 0 ? 'text-red-600' : 'text-gray-600'; ?>">
                                    <?php echo number_format($stats['used_upgrade_pins']); ?> used
                                </p>
                            </div>
                            <div>
                                <p class="text-xs font-bold <?php echo $stats['used_tax_pins'] > 0 ? 'text-red-600' : 'text-gray-600'; ?>">
                                    <?php echo number_format($stats['used_tax_pins']); ?> used
                                </p>
                            </div>
                        </div>
                    </div>
                    <div class="w-10 h-10 md:w-12 md:h-12 bg-amber-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-key text-amber-600 text-lg md:text-xl"></i>
                    </div>
                </div>
                <div class="mt-4 text-xs md:text-sm text-gray-500">
                    <i class="fas fa-chart-pie mr-1"></i>
                    Total Fees: $<?php echo number_format($stats['total_upgrade_fees'] + $stats['total_tax_fees'], 2); ?>
                </div>
            </div>
        </div>
    </div>

<script>
    // Toggle add user form
    function toggleAddUserForm() {
        const form = document.getElementById('addUserForm');
        form.classList.toggle('hidden');
        
        if (!form.classList.contains('hidden')) {
            form.scrollIntoView({ behavior: 'smooth' });
        } else {
            const url = new URL(window.location);
            url.searchParams.delete('edit');
            window.history.replaceState({}, '', url);
        }
    }

    // If in edit mode, show form on page load
    <?php if ($edit_mode): ?>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('addUserForm');
        if (form) {
            form.classList.remove('hidden');
            form.scrollIntoView({ behavior: 'smooth' });
        }
    });
    <?php endif; ?>

    // Modal functions
    function closeModal() {
        const modal = document.getElementById('actionsModal');
        if (modal) {
            modal.remove();
            // Remove from URL
            const url = new URL(window.location);
            url.searchParams.delete('view_actions');
            window.history.replaceState({}, '', url);
        }
    }

    // Tab switching for modal
    function showTab(tabName) {
        // Hide all tab contents
        const tabContents = document.querySelectorAll('.tab-content');
        tabContents.forEach(content => {
            content.classList.remove('active');
        });
        
        // Remove active from all tabs
        const tabs = document.querySelectorAll('.tab-button');
        tabs.forEach(tab => {
            tab.classList.remove('active', 'border-primary-500', 'text-primary-600');
            tab.classList.add('border-transparent', 'text-gray-500');
        });
        
        // Show selected tab content
        const selectedContent = document.getElementById(tabName + 'TabContent');
        if (selectedContent) {
            selectedContent.classList.add('active');
        }
        
        // Activate selected tab
        const selectedTab = document.getElementById(tabName + 'Tab');
        if (selectedTab) {
            selectedTab.classList.remove('border-transparent', 'text-gray-500');
            selectedTab.classList.add('active', 'border-primary-500', 'text-primary-600');
        }
    }

    // Initialize first tab as active
    <?php if ($show_actions_modal): ?>
    document.addEventListener('DOMContentLoaded', function() {
        showTab('creditDebit');
    });
    <?php endif; ?>

    // Close modal on escape key
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeModal();
        }
    });

    // Close modal when clicking outside
    document.addEventListener('click', function(event) {
        const modal = document.getElementById('actionsModal');
        if (modal && event.target === modal) {
            closeModal();
        }
    });

    // Validate PIN form
    function validatePinForm(type) {
        const pinField = type === 'withdrawal' ? 'withdrawal_pin' : 
                       type === 'upgrade' ? 'upgrade_pin' : 'tax_pin';
        const confirmField = type === 'withdrawal' ? 'confirm_withdrawal_pin' : 
                           type === 'upgrade' ? 'confirm_upgrade_pin' : 'confirm_tax_pin';
        
        const pinInput = document.querySelector(`input[name="${pinField}"]`);
        const confirmInput = document.querySelector(`input[name="${confirmField}"]`);
        
        if (!pinInput || !confirmInput) {
            alert('PIN fields not found!');
            return false;
        }
        
        const pin = pinInput.value;
        const confirmPin = confirmInput.value;
        
        if (pin !== confirmPin) {
            alert('PINs do not match!');
            pinInput.focus();
            return false;
        }
        
        if (pin.length < 4 || pin.length > 6) {
            alert('PIN must be 4-6 digits!');
            pinInput.focus();
            return false;
        }
        
        if (!/^\d+$/.test(pin)) {
            alert('PIN must contain only numbers!');
            pinInput.focus();
            return false;
        }
        
        let message = '';
        switch(type) {
            case 'withdrawal':
                message = 'Are you sure you want to set/change the withdrawal PIN? This PIN can only be used once. The user will need a new PIN after use.';
                break;
            case 'upgrade':
                const upgradeFee = document.querySelector('input[name="upgrade_fee"]').value;
                message = `Are you sure you want to set the upgrade PIN and fee? \nUpgrade Fee: $${upgradeFee}\nThis PIN can only be used once. The user will need a new PIN after use.`;
                break;
            case 'tax':
                const taxFee = document.querySelector('input[name="tax_fee"]').value;
                message = `Are you sure you want to set the tax PIN and fee? \nTax Fee: $${taxFee}\nThis PIN can only be used once. The user will need a new PIN after use.`;
                break;
        }
        
        return confirm(message);
    }

    // Copy to clipboard
    function copyToClipboard(text) {
        navigator.clipboard.writeText(text).then(function() {
            alert('Copied to clipboard!');
        }).catch(function(err) {
            console.error('Could not copy text: ', err);
        });
    }

    // Auto-focus PIN input when PIN tab is clicked
    document.addEventListener('DOMContentLoaded', function() {
        const pinTabs = ['withdrawalPinTab', 'upgradePinTab', 'taxPinTab'];
        
        pinTabs.forEach(tabId => {
            const tab = document.getElementById(tabId);
            if (tab) {
                tab.addEventListener('click', function() {
                    setTimeout(function() {
                        let pinInput;
                        switch(tabId) {
                            case 'withdrawalPinTab':
                                pinInput = document.querySelector('input[name="withdrawal_pin"]');
                                break;
                            case 'upgradePinTab':
                                pinInput = document.querySelector('input[name="upgrade_pin"]');
                                break;
                            case 'taxPinTab':
                                pinInput = document.querySelector('input[name="tax_pin"]');
                                break;
                        }
                        if (pinInput) {
                            pinInput.focus();
                        }
                    }, 100);
                });
            }
        });
    });

    // Validate PIN input to accept only numbers
    document.addEventListener('DOMContentLoaded', function() {
        const pinInputs = document.querySelectorAll('input[pattern="[0-9]*"]');
        pinInputs.forEach(input => {
            input.addEventListener('input', function(e) {
                this.value = this.value.replace(/[^0-9]/g, '');
            });
            
            input.addEventListener('keypress', function(e) {
                const charCode = e.which ? e.which : e.keyCode;
                if (charCode < 48 || charCode > 57) {
                    e.preventDefault();
                }
            });
        });
    });

    // Main mobile menu functionality
    document.addEventListener('DOMContentLoaded', function() {
        const mobileMenuToggle = document.getElementById('mobileMenuToggle');
        const mobileOverlay = document.getElementById('mobileOverlay');
        const sidebar = document.querySelector('.sidebar');
        
        function openMobileMenu() {
            if (sidebar) sidebar.classList.add('mobile-open');
            if (mobileOverlay) mobileOverlay.classList.add('active');
            document.body.style.overflow = 'hidden';
        }
        
        function closeMobileMenu() {
            if (sidebar) sidebar.classList.remove('mobile-open');
            if (mobileOverlay) mobileOverlay.classList.remove('active');
            document.body.style.overflow = '';
        }
        
        // Toggle mobile menu
        if (mobileMenuToggle) {
            mobileMenuToggle.addEventListener('click', function(event) {
                event.stopPropagation();
                if (sidebar && sidebar.classList.contains('mobile-open')) {
                    closeMobileMenu();
                } else {
                    openMobileMenu();
                }
            });
        }
        
        // Close mobile menu when overlay is clicked
        if (mobileOverlay) {
            mobileOverlay.addEventListener('click', closeMobileMenu);
        }
        
        // Close mobile menu when clicking on a sidebar link
        const sidebarLinks = document.querySelectorAll('.sidebar a');
        sidebarLinks.forEach(link => {
            link.addEventListener('click', function() {
                if (window.innerWidth <= 768) {
                    closeMobileMenu();
                }
            });
        });
        
        // Close mobile menu on escape key
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closeMobileMenu();
            }
        });
        
        // Handle window resize
        window.addEventListener('resize', function() {
            if (window.innerWidth > 768) {
                closeMobileMenu();
            }
        });
        
        // Close sidebar when clicking anywhere on mobile (except excluded elements)
        document.addEventListener('click', function(event) {
            // Only on mobile
            if (window.innerWidth > 768) return;
            
            // If sidebar is not open, do nothing
            if (!sidebar || !sidebar.classList.contains('mobile-open')) return;
            
            // Check if click is on excluded elements
            const clickedElement = event.target;
            
            // Check if clicked on mobile menu toggle
            if (mobileMenuToggle && mobileMenuToggle.contains(clickedElement)) return;
            
            // Check if clicked inside sidebar
            if (sidebar && sidebar.contains(clickedElement)) return;
            
            // Check if clicked on modal (if exists)
            const actionsModal = document.getElementById('actionsModal');
            if (actionsModal && actionsModal.contains(clickedElement)) return;
            
            // Check if clicked on modal backdrop/overlay
            if (clickedElement.classList.contains('mobile-overlay')) return;
            
            // Check if clicked on add user form (if visible)
            const addUserForm = document.getElementById('addUserForm');
            if (addUserForm && !addUserForm.classList.contains('hidden') && 
                addUserForm.contains(clickedElement)) return;
            
            // If none of the above, close the sidebar
            closeMobileMenu();
        });
    });
</script>
    
    
</body>
</html>