<?php
session_start();

// 1. DATABASE CONNECTION
$servername = "localhost";
$username   = "axiomvest_dbs";
$password   = "Mademen.2017";
$dbname     = "axiomvest_dbs";

$conn = mysqli_connect($servername, $username, $password, $dbname);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// =========================================================
// 2. SECURITY CHECK
// =========================================================

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

$current_user_id = $_SESSION['id'];
$admin_check_sql = "SELECT ADMIN FROM user WHERE id = '$current_user_id' LIMIT 1";
$admin_check_result = mysqli_query($conn, $admin_check_sql);
$admin_row = mysqli_fetch_assoc($admin_check_result);

if (!$admin_row || $admin_row['ADMIN'] != '1') {
    header("Location: index.php"); 
    exit(); 
}

// =========================================================
// 3. HANDLE UPDATES & ACTIONS
// =========================================================
$msg = "";

// --- A. VERIFY DEPOSIT ---
if (isset($_POST['verify_deposit_btn'])) {
    $dep_id = mysqli_real_escape_string($conn, $_POST['deposit_id']);
    $dep_email = mysqli_real_escape_string($conn, $_POST['deposit_email']);
    $dep_amount = mysqli_real_escape_string($conn, $_POST['deposit_amount']);

    // 1. Update Deposit Status to Completed
    $update_dep = "UPDATE deposit SET status = 'Completed' WHERE id = '$dep_id'";
    
    if (mysqli_query($conn, $update_dep)) {
        // 2. Add Money to User's Balance
        $update_user = "UPDATE user SET avialable_balance = avialable_balance + '$dep_amount' WHERE email = '$dep_email'";
        
        if (mysqli_query($conn, $update_user)) {
            $msg = "<div class='alert alert-success'>Deposit #$dep_id verified! <b>$$dep_amount</b> added to user ($dep_email).</div>";
        } else {
            $msg = "<div class='alert alert-warning'>Deposit verified, but failed to add balance. Check email.</div>";
        }
    } else {
        $msg = "<div class='alert alert-danger'>Error verifying deposit: " . mysqli_error($conn) . "</div>";
    }
}

// --- B. DELETE DEPOSIT ---
if (isset($_POST['delete_deposit_btn'])) {
    $dep_id = mysqli_real_escape_string($conn, $_POST['deposit_id']);
    $del_sql = "DELETE FROM deposit WHERE id = '$dep_id'";
    if (mysqli_query($conn, $del_sql)) {
        $msg = "<div class='alert alert-danger'>Deposit #$dep_id deleted.</div>";
    }
}

// --- C. APPROVE WITHDRAWAL (NEW) ---
if (isset($_POST['approve_withdraw_btn'])) {
    $with_id = mysqli_real_escape_string($conn, $_POST['withdraw_id']);
    $with_email = mysqli_real_escape_string($conn, $_POST['withdraw_email']);
    
    $update_with = "UPDATE withdrawal SET status = 'Completed' WHERE id = '$with_id'";
    
    if (mysqli_query($conn, $update_with)) {
        $msg = "<div class='alert alert-success'>Withdrawal #$with_id marked as Completed (Sent) for $with_email.</div>";
    } else {
        $msg = "<div class='alert alert-danger'>Error updating withdrawal: " . mysqli_error($conn) . "</div>";
    }
}

// --- D. DELETE WITHDRAWAL (NEW) ---
if (isset($_POST['delete_withdraw_btn'])) {
    $with_id = mysqli_real_escape_string($conn, $_POST['withdraw_id']);
    $del_sql = "DELETE FROM withdrawal WHERE id = '$with_id'";
    if (mysqli_query($conn, $del_sql)) {
        $msg = "<div class='alert alert-danger'>Withdrawal request #$with_id deleted.</div>";
    }
}

// --- E. MANUAL BALANCE UPDATE ---
if (isset($_POST['update_balance_btn'])) {
    $target_user_id = mysqli_real_escape_string($conn, $_POST['target_user_id']);
    $new_balance    = mysqli_real_escape_string($conn, $_POST['new_amount']);

    $update_sql = "UPDATE user SET avialable_balance = '$new_balance' WHERE id = '$target_user_id'";
    if (mysqli_query($conn, $update_sql)) {
        $msg = "<div class='alert alert-success'>User ID #$target_user_id Balance updated to $new_balance!</div>";
    }
}

// --- F. MANUAL EARNINGS UPDATE ---
if (isset($_POST['update_earnings_btn'])) {
    $target_user_id = mysqli_real_escape_string($conn, $_POST['target_user_id']);
    $new_earnings   = mysqli_real_escape_string($conn, $_POST['new_earnings']);
    $update_sql = "UPDATE user SET earnings = '$new_earnings' WHERE id = '$target_user_id'";
    if (mysqli_query($conn, $update_sql)) {
        $msg = "<div class='alert alert-success'>User ID #$target_user_id Earnings updated to $new_earnings!</div>";
    }
}

// --- G. UPDATE USER DETAILS (COMPREHENSIVE) ---
if (isset($_POST['update_user_details_btn'])) {
    $user_id = mysqli_real_escape_string($conn, $_POST['user_id']);
    $full_name = mysqli_real_escape_string($conn, $_POST['full_name']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);
    $country = mysqli_real_escape_string($conn, $_POST['country']);
    $status = mysqli_real_escape_string($conn, $_POST['status']);
    $role = mysqli_real_escape_string($conn, $_POST['role']);
    $verification_status = mysqli_real_escape_string($conn, $_POST['verification_status']);
    
    // New fields for detailed user information
    $gender = mysqli_real_escape_string($conn, $_POST['gender']);
    $date_of_birth = mysqli_real_escape_string($conn, $_POST['date_of_birth']);
    $address = mysqli_real_escape_string($conn, $_POST['address']);
    $city = mysqli_real_escape_string($conn, $_POST['city']);
    $state = mysqli_real_escape_string($conn, $_POST['state']);
    $zip_code = mysqli_real_escape_string($conn, $_POST['zip_code']);
    $account_type = mysqli_real_escape_string($conn, $_POST['account_type']);
    $trading_experience = mysqli_real_escape_string($conn, $_POST['trading_experience']);
    $investment_goal = mysqli_real_escape_string($conn, $_POST['investment_goal']);
    $risk_tolerance = mysqli_real_escape_string($conn, $_POST['risk_tolerance']);
    $preferred_currency = mysqli_real_escape_string($conn, $_POST['preferred_currency']);
    $notification_preference = mysqli_real_escape_string($conn, $_POST['notification_preference']);
    $two_factor_auth = isset($_POST['two_factor_auth']) ? '1' : '0';
    $account_manager = mysqli_real_escape_string($conn, $_POST['account_manager']);
    $last_login = mysqli_real_escape_string($conn, $_POST['last_login']);
    $ip_address = mysqli_real_escape_string($conn, $_POST['ip_address']);
    
    $update_sql = "UPDATE user SET 
        full_name = '$full_name',
        email = '$email',
        phone_number = '$phone',
        country = '$country',
        status = '$status',
        role = '$role',
        verification_status = '$verification_status',
        gender = '$gender',
        date_of_birth = '$date_of_birth',
        address = '$address',
        city = '$city',
        state = '$state',
        zip_code = '$zip_code',
        account_type = '$account_type',
        trading_experience = '$trading_experience',
        investment_goal = '$investment_goal',
        risk_tolerance = '$risk_tolerance',
        preferred_currency = '$preferred_currency',
        notification_preference = '$notification_preference',
        two_factor_auth = '$two_factor_auth',
        account_manager = '$account_manager',
        last_login = '$last_login',
        ip_address = '$ip_address'
        WHERE id = '$user_id'";
    
    if (mysqli_query($conn, $update_sql)) {
        $msg = "<div class='alert alert-success'>User #$user_id details updated successfully!</div>";
    } else {
        $msg = "<div class='alert alert-danger'>Error updating user details: " . mysqli_error($conn) . "</div>";
    }
}

// --- H. VERIFY USER (QUICK ACTION) ---
if (isset($_POST['verify_user_btn'])) {
    $user_id = mysqli_real_escape_string($conn, $_POST['user_id']);
    $verify_sql = "UPDATE user SET verification_status = 'verified' WHERE id = '$user_id'";
    if (mysqli_query($conn, $verify_sql)) {
        $msg = "<div class='alert alert-success'>User #$user_id has been verified!</div>";
    } else {
        $msg = "<div class='alert alert-danger'>Error verifying user: " . mysqli_error($conn) . "</div>";
    }
}

// --- I. SUSPEND USER (QUICK ACTION) ---
if (isset($_POST['suspend_user_btn'])) {
    $user_id = mysqli_real_escape_string($conn, $_POST['user_id']);
    $suspend_sql = "UPDATE user SET status = 'Suspended' WHERE id = '$user_id'";
    if (mysqli_query($conn, $suspend_sql)) {
        $msg = "<div class='alert alert-warning'>User #$user_id has been suspended!</div>";
    } else {
        $msg = "<div class='alert alert-danger'>Error suspending user: " . mysqli_error($conn) . "</div>";
    }
}

// --- J. ACTIVATE USER (QUICK ACTION) ---
if (isset($_POST['activate_user_btn'])) {
    $user_id = mysqli_real_escape_string($conn, $_POST['user_id']);
    $activate_sql = "UPDATE user SET status = 'Active' WHERE id = '$user_id'";
    if (mysqli_query($conn, $activate_sql)) {
        $msg = "<div class='alert alert-success'>User #$user_id has been activated!</div>";
    } else {
        $msg = "<div class='alert alert-danger'>Error activating user: " . mysqli_error($conn) . "</div>";
    }
}

// =========================================================
// 4. FETCH DATA
// =========================================================

// Fetch Pending Deposits
$dep_sql = "SELECT * FROM deposit WHERE status = 'Pending' ORDER BY created_at DESC";
$dep_result = mysqli_query($conn, $dep_sql);

// Fetch Pending Withdrawals
$with_sql = "SELECT * FROM withdrawal WHERE status = 'Pending' ORDER BY id DESC";
$with_result = mysqli_query($conn, $with_sql);

// Fetch Users
$user_sql = "SELECT * FROM user ORDER BY id DESC";
$user_result = mysqli_query($conn, $user_sql);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - Manage Funds</title>
    <link href="https://unpkg.com/ionicons@4.5.10-0/dist/css/ionicons.min.css" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', sans-serif; background-color: #020617; color: #e2e8f0; padding: 20px; }
        .container { max-width: 1400px; margin: 0 auto; }
        
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; border-bottom: 1px solid #1e293b; padding-bottom: 20px; }
        .header h1 { color: #fff; font-size: 1.5rem; }
        .btn-back { background: #334155; color: white; padding: 10px 20px; text-decoration: none; border-radius: 8px; }
        
        .section-title { color: #94a3b8; font-size: 1.1rem; margin-bottom: 15px; margin-top: 30px; border-left: 4px solid #38bdf8; padding-left: 10px; }

        /* User Dropdown Styles */
        .user-dropdown { position: relative; display: inline-block; }
        .user-dropdown-btn { 
            background: #0f172a; 
            color: #38bdf8; 
            border: 1px solid #334155; 
            padding: 5px 12px; 
            border-radius: 6px; 
            cursor: pointer; 
            font-size: 0.85rem; 
            transition: all 0.3s;
        }
        .user-dropdown-btn:hover { background: #1e293b; }
        .user-dropdown-content { 
            display: none; 
            position: absolute; 
            background: #0f172a; 
            min-width: 500px; 
            border: 1px solid #334155; 
            border-radius: 8px; 
            padding: 20px; 
            z-index: 100; 
            box-shadow: 0 10px 25px rgba(0,0,0,0.3);
            top: 100%;
            left: 0;
            margin-top: 5px;
        }
        .user-dropdown.active .user-dropdown-content { display: block; }
        
        .user-details-grid { 
            display: grid; 
            grid-template-columns: repeat(2, 1fr); 
            gap: 12px; 
            margin-bottom: 15px;
        }
        .detail-item { display: flex; flex-direction: column; }
        .detail-label { color: #94a3b8; font-size: 0.8rem; margin-bottom: 3px; }
        .detail-value { color: #f1f5f9; font-size: 0.85rem; word-break: break-word; }
        
        .status-badge { 
            display: inline-block; 
            padding: 3px 8px; 
            border-radius: 12px; 
            font-size: 0.75rem; 
            font-weight: 600;
        }
        .status-active { background: rgba(34, 197, 94, 0.2); color: #4ade80; }
        .status-unverified { background: rgba(234, 179, 8, 0.2); color: #fde047; }
        .status-suspended { background: rgba(239, 68, 68, 0.2); color: #f87171; }
        .status-inactive { background: rgba(148, 163, 184, 0.2); color: #94a3b8; }
        
        .verification-badge { 
            display: inline-block; 
            padding: 3px 8px; 
            border-radius: 12px; 
            font-size: 0.75rem; 
            font-weight: 600;
        }
        .verified { background: rgba(34, 197, 94, 0.2); color: #4ade80; }
        .pending { background: rgba(234, 179, 8, 0.2); color: #fde047; }
        .unverified { background: rgba(239, 68, 68, 0.2); color: #f87171; }
        
        .role-badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        .role-admin { background: rgba(168, 85, 247, 0.2); color: #c084fc; }
        .role-user { background: rgba(59, 130, 246, 0.2); color: #93c5fd; }
        .role-vip { background: rgba(234, 179, 8, 0.2); color: #fde047; }
        
        .dropdown-edit-form { margin-top: 15px; border-top: 1px solid #334155; padding-top: 15px; }
        .form-group { margin-bottom: 10px; }
        .form-label { display: block; color: #94a3b8; font-size: 0.8rem; margin-bottom: 3px; }
        .form-input { 
            width: 100%; 
            background: #1e293b; 
            border: 1px solid #475569; 
            color: white; 
            padding: 6px 8px; 
            border-radius: 4px; 
            font-size: 0.85rem;
        }
        .form-select { 
            width: 100%; 
            background: #1e293b; 
            border: 1px solid #475569; 
            color: white; 
            padding: 6px 8px; 
            border-radius: 4px; 
            font-size: 0.85rem;
        }
        .form-checkbox {
            width: auto;
            margin-right: 5px;
        }
        .dropdown-btn { 
            background: #38bdf8; 
            color: white; 
            border: none; 
            padding: 6px 12px; 
            border-radius: 4px; 
            cursor: pointer; 
            font-size: 0.85rem;
            margin-top: 10px;
        }
        .dropdown-btn:hover { background: #0ea5e9; }
        
        /* Quick Action Buttons */
        .quick-actions { display: flex; gap: 5px; margin-top: 10px; }
        .quick-action-btn { 
            padding: 4px 8px; 
            border-radius: 4px; 
            border: none; 
            cursor: pointer; 
            font-size: 0.75rem; 
            display: flex; 
            align-items: center; 
            gap: 3px;
        }
        .verify-btn { background: rgba(34, 197, 94, 0.2); color: #4ade80; border: 1px solid #4ade80; }
        .verify-btn:hover { background: rgba(34, 197, 94, 0.4); }
        .suspend-btn { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid #f87171; }
        .suspend-btn:hover { background: rgba(239, 68, 68, 0.4); }
        .activate-btn { background: rgba(59, 130, 246, 0.2); color: #93c5fd; border: 1px solid #93c5fd; }
        .activate-btn:hover { background: rgba(59, 130, 246, 0.4); }
        
        /* Table Styles */
        .table-wrapper { background: #1e293b; border-radius: 12px; padding: 20px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); overflow-x: auto; margin-bottom: 40px; }
        table { width: 100%; border-collapse: collapse; }
        th { text-align: left; padding: 15px; background: #0f172a; color: #94a3b8; font-size: 0.85rem; text-transform: uppercase; }
        td { padding: 15px; border-bottom: 1px solid #334155; vertical-align: middle; }
        tr:last-child td { border-bottom: none; }
        tr:hover { background: #334155; }

        /* Buttons & Inputs */
        .input-dark { background: #020617; border: 1px solid #475569; color: white; padding: 8px; border-radius: 6px; width: 100px; }
        .btn-update { border: none; padding: 8px 15px; border-radius: 6px; cursor: pointer; font-weight: 600; color: #000; }
        .btn-green { background: #22c55e; }
        .btn-green:hover { background: #16a34a; }
        .btn-blue { background: #38bdf8; }
        .btn-blue:hover { background: #0ea5e9; }
        .btn-red { background: #ef4444; color: white; }
        
        /* Alerts */
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; }
        .alert-success { background: rgba(34, 197, 94, 0.2); border: 1px solid #22c55e; color: #4ade80; }
        .alert-danger { background: rgba(239, 68, 68, 0.2); border: 1px solid #ef4444; color: #f87171; }
        .alert-warning { background: rgba(234, 179, 8, 0.2); border: 1px solid #eab308; color: #fde047; }
        
        /* ID Image Preview */
        .id-images { display: flex; gap: 10px; margin-top: 10px; }
        .id-image-container { flex: 1; }
        .id-image-label { display: block; color: #94a3b8; font-size: 0.75rem; margin-bottom: 3px; }
        .id-image { width: 100%; height: 80px; object-fit: cover; border-radius: 6px; border: 1px solid #334155; background: #1e293b; }
        .no-image { display: flex; align-items: center; justify-content: center; color: #64748b; font-size: 0.75rem; }
        
        /* Form Layout */
        .form-section { margin-bottom: 15px; }
        .form-section-title { color: #38bdf8; font-size: 0.9rem; margin-bottom: 8px; border-bottom: 1px solid #334155; padding-bottom: 5px; }
        .form-row { display: flex; gap: 10px; margin-bottom: 8px; }
        .form-row .form-group { flex: 1; }

        /* Responsive */
        @media screen and (max-width: 900px) {
            .table-wrapper { background: transparent; padding: 0; box-shadow: none; }
            table, thead, tbody, th, td, tr { display: block; }
            thead tr { position: absolute; top: -9999px; left: -9999px; }
            tr { background: #1e293b; border-radius: 12px; margin-bottom: 15px; padding: 15px; border: 1px solid #334155; }
            td { border: none; border-bottom: 1px solid #334155; position: relative; padding-left: 0; padding-right: 0; display: flex; justify-content: space-between; align-items: center; text-align: right; }
            td:before { content: attr(data-label); float: left; font-weight: bold; color: #94a3b8; font-size: 0.75rem; margin-right: 15px; }
            
            .user-dropdown-content { 
                position: fixed; 
                top: 50%; 
                left: 50%; 
                transform: translate(-50%, -50%); 
                width: 95%; 
                max-width: 500px; 
                max-height: 80vh; 
                overflow-y: auto;
            }
            .user-details-grid { grid-template-columns: 1fr; }
            .form-row { flex-direction: column; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h1>Admin Dashboard</h1>
        <a href="index.php" class="btn-back"><i class="ion-arrow-return-left"></i> Dashboard</a>
    </div>

    <?php echo $msg; ?>

    <!-- ============================================ -->
    <!-- SECTION 1: ALL USERS WITH DROPDOWN DETAILS -->
    <!-- ============================================ -->
    <h3 class="section-title">User Database</h3>
    <div class="table-wrapper">
        <table>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>User Details</th>
                    <th>Balance</th>
                    <th>Update</th>
                    <th>Earnings</th>
                    <th>Update</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if (mysqli_num_rows($user_result) > 0) {
                    while($row = mysqli_fetch_assoc($user_result)) {
                        $uid = $row['id'];
                        $full_name = $row['full_name'] ?? 'N/A';
                        $email = $row['email'] ?? 'N/A';
                        $phone = $row['phone_number'] ?? 'N/A';
                        $country = $row['country'] ?? 'N/A';
                        $status = $row['status'] ?? 'Active';
                        $role = $row['role'] ?? 'user';
                        $verification_status = $row['verification_status'] ?? 'unverified';
                        $id_front = $row['id_front'] ?? '';
                        $id_back = $row['id_back'] ?? '';
                        $balance = $row['avialable_balance'] ?? '0.00';
                        $earnings = $row['earnings'] ?? '0.00';
                        $date = $row['date'] ?? 'N/A';
                        $isAdmin = ($row['ADMIN'] == '1') ? '<span style="color:#eab308;">(Admin)</span>' : '';
                        
                        // Additional user fields
                        $gender = $row['gender'] ?? '';
                        $date_of_birth = $row['date_of_birth'] ?? '';
                        $address = $row['address'] ?? '';
                        $city = $row['city'] ?? '';
                        $state = $row['state'] ?? '';
                        $zip_code = $row['zip_code'] ?? '';
                        $account_type = $row['account_type'] ?? '';
                        $trading_experience = $row['trading_experience'] ?? '';
                        $investment_goal = $row['investment_goal'] ?? '';
                        $risk_tolerance = $row['risk_tolerance'] ?? '';
                        $preferred_currency = $row['preferred_currency'] ?? '';
                        $notification_preference = $row['notification_preference'] ?? '';
                        $two_factor_auth = $row['two_factor_auth'] ?? '0';
                        $account_manager = $row['account_manager'] ?? '';
                        $last_login = $row['last_login'] ?? '';
                        $ip_address = $row['ip_address'] ?? '';
                        
                        // Status badges
                        $status_class = '';
                        if ($status == 'Active') $status_class = 'status-active';
                        elseif ($status == 'Suspended') $status_class = 'status-suspended';
                        elseif ($status == 'Inactive') $status_class = 'status-inactive';
                        else $status_class = 'status-unverified';
                        
                        // Verification badges
                        $verification_class = '';
                        if ($verification_status == 'verified') $verification_class = 'verified';
                        elseif ($verification_status == 'pending') $verification_class = 'pending';
                        else $verification_class = 'unverified';
                        
                        // Role badges
                        $role_class = '';
                        if ($role == 'admin') $role_class = 'role-admin';
                        elseif ($role == 'vip') $role_class = 'role-vip';
                        else $role_class = 'role-user';
                        ?>
                        <tr>
                            <td data-label="ID">#<?php echo $uid; ?></td>
                            <td data-label="User">
                                <strong><?php echo htmlspecialchars($full_name); ?></strong> <?php echo $isAdmin; ?><br>
                                <small style="color:#94a3b8;"><?php echo htmlspecialchars($email); ?></small><br>
                                <span class="status-badge <?php echo $status_class; ?>"><?php echo $status; ?></span>
                                <span class="verification-badge <?php echo $verification_class; ?>"><?php echo $verification_status; ?></span>
                                <span class="role-badge <?php echo $role_class; ?>"><?php echo $role; ?></span>
                                
                                <!-- Quick Action Buttons -->
                                <div class="quick-actions">
                                    <?php if ($verification_status != 'verified'): ?>
                                        <form method="POST" style="display:inline;">
                                            <input type="hidden" name="user_id" value="<?php echo $uid; ?>">
                                            <button type="submit" name="verify_user_btn" class="quick-action-btn verify-btn" title="Verify User">
                                                <i class="ion-checkmark-circle"></i> Verify
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    
                                    <?php if ($status != 'Suspended'): ?>
                                        <form method="POST" style="display:inline;">
                                            <input type="hidden" name="user_id" value="<?php echo $uid; ?>">
                                            <button type="submit" name="suspend_user_btn" class="quick-action-btn suspend-btn" title="Suspend User">
                                                <i class="ion-close-circle"></i> Suspend
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <form method="POST" style="display:inline;">
                                            <input type="hidden" name="user_id" value="<?php echo $uid; ?>">
                                            <button type="submit" name="activate_user_btn" class="quick-action-btn activate-btn" title="Activate User">
                                                <i class="ion-checkmark-circle"></i> Activate
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td data-label="Balance" style="color:#4ade80; font-weight:bold;">$<?php echo number_format($balance, 2); ?></td>
                            <td data-label="Update Balance">
                                <form method="POST" style="display:flex; gap:5px; justify-content:flex-end;">
                                    <input type="hidden" name="target_user_id" value="<?php echo $uid; ?>">
                                    <input type="number" step="0.01" name="new_amount" class="input-dark" value="<?php echo $balance; ?>" required>
                                    <button type="submit" name="update_balance_btn" class="btn-update btn-green">Save</button>
                                </form>
                            </td>
                            <td data-label="Earnings" style="color:#38bdf8; font-weight:bold;">$<?php echo number_format($earnings, 2); ?></td>
                            <td data-label="Update Earnings">
                                <form method="POST" style="display:flex; gap:5px; justify-content:flex-end;">
                                    <input type="hidden" name="target_user_id" value="<?php echo $uid; ?>">
                                    <input type="number" step="0.01" name="new_earnings" class="input-dark" value="<?php echo $earnings; ?>" required>
                                    <button type="submit" name="update_earnings_btn" class="btn-update btn-blue">Save</button>
                                </form>
                            </td>
                            <td data-label="Actions">
                                <div class="user-dropdown" id="dropdown-<?php echo $uid; ?>">
                                    <button class="user-dropdown-btn" onclick="toggleDropdown(<?php echo $uid; ?>)">
                                        <i class="ion-ios-list"></i> View/Edit Details
                                    </button>
                                    <div class="user-dropdown-content">
                                        <!-- User Details Grid -->
                                        <div class="user-details-grid">
                                            <div class="detail-item">
                                                <span class="detail-label">ID:</span>
                                                <span class="detail-value">#<?php echo $uid; ?></span>
                                            </div>
                                            <div class="detail-item">
                                                <span class="detail-label">Full Name:</span>
                                                <span class="detail-value"><?php echo htmlspecialchars($full_name); ?></span>
                                            </div>
                                            <div class="detail-item">
                                                <span class="detail-label">Email:</span>
                                                <span class="detail-value"><?php echo htmlspecialchars($email); ?></span>
                                            </div>
                                            <div class="detail-item">
                                                <span class="detail-label">Phone:</span>
                                                <span class="detail-value"><?php echo htmlspecialchars($phone); ?></span>
                                            </div>
                                            <div class="detail-item">
                                                <span class="detail-label">Country:</span>
                                                <span class="detail-value"><?php echo htmlspecialchars($country); ?></span>
                                            </div>
                                            <div class="detail-item">
                                                <span class="detail-label">Status:</span>
                                                <span class="detail-value">
                                                    <span class="status-badge <?php echo $status_class; ?>"><?php echo $status; ?></span>
                                                </span>
                                            </div>
                                            <div class="detail-item">
                                                <span class="detail-label">Role:</span>
                                                <span class="detail-value">
                                                    <span class="role-badge <?php echo $role_class; ?>"><?php echo $role; ?></span>
                                                </span>
                                            </div>
                                            <div class="detail-item">
                                                <span class="detail-label">Verification:</span>
                                                <span class="detail-value">
                                                    <span class="verification-badge <?php echo $verification_class; ?>"><?php echo $verification_status; ?></span>
                                                </span>
                                            </div>
                                            <div class="detail-item">
                                                <span class="detail-label">Balance:</span>
                                                <span class="detail-value" style="color:#4ade80;">$<?php echo number_format($balance, 2); ?></span>
                                            </div>
                                            <div class="detail-item">
                                                <span class="detail-label">Earnings:</span>
                                                <span class="detail-value" style="color:#38bdf8;">$<?php echo number_format($earnings, 2); ?></span>
                                            </div>
                                            <div class="detail-item">
                                                <span class="detail-label">Joined Date:</span>
                                                <span class="detail-value"><?php echo date('M d, Y', strtotime($date)); ?></span>
                                            </div>
                                        </div>
                                        
                                        <!-- ID Images -->
                                        <div class="id-images">
                                            <div class="id-image-container">
                                                <span class="id-image-label">ID Front:</span>
                                                <?php if (!empty($id_front)): ?>
                                                    <img src="../<?php echo htmlspecialchars($id_front); ?>" alt="ID Front" class="id-image" onclick="openImageModal(this.src)">
                                                <?php else: ?>
                                                    <div class="id-image no-image">No Image</div>
                                                <?php endif; ?>
                                            </div>
                                            <div class="id-image-container">
                                                <span class="id-image-label">ID Back:</span>
                                                <?php if (!empty($id_back)): ?>
                                                    <img src="../<?php echo htmlspecialchars($id_back); ?>" alt="ID Back" class="id-image" onclick="openImageModal(this.src)">
                                                <?php else: ?>
                                                    <div class="id-image no-image">No Image</div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        
                                        <!-- Edit Form -->
                                        <div class="dropdown-edit-form">
                                            <form method="POST">
                                                <input type="hidden" name="user_id" value="<?php echo $uid; ?>">
                                                
                                                <div class="form-section">
                                                    <div class="form-section-title">Basic Information</div>
                                                    <div class="form-row">
                                                        <div class="form-group">
                                                            <label class="form-label">Full Name *</label>
                                                            <input type="text" name="full_name" class="form-input" value="<?php echo htmlspecialchars($full_name); ?>" required>
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="form-label">Email *</label>
                                                            <input type="email" name="email" class="form-input" value="<?php echo htmlspecialchars($email); ?>" required>
                                                        </div>
                                                    </div>
                                                    <div class="form-row">
                                                        <div class="form-group">
                                                            <label class="form-label">Phone</label>
                                                            <input type="text" name="phone" class="form-input" value="<?php echo htmlspecialchars($phone); ?>">
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="form-label">Country</label>
                                                            <input type="text" name="country" class="form-input" value="<?php echo htmlspecialchars($country); ?>">
                                                        </div>
                                                    </div>
                                                    <div class="form-row">
                                                        <div class="form-group">
                                                            <label class="form-label">Status</label>
                                                            <select name="status" class="form-select">
                                                                <option value="Active" <?php echo $status == 'Active' ? 'selected' : ''; ?>>Active</option>
                                                                <option value="Inactive" <?php echo $status == 'Inactive' ? 'selected' : ''; ?>>Inactive</option>
                                                                <option value="Suspended" <?php echo $status == 'Suspended' ? 'selected' : ''; ?>>Suspended</option>
                                                                <option value="Unverified" <?php echo $status == 'Unverified' ? 'selected' : ''; ?>>Unverified</option>
                                                            </select>
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="form-label">Role</label>
                                                            <select name="role" class="form-select">
                                                                <option value="user" <?php echo $role == 'user' ? 'selected' : ''; ?>>User</option>
                                                                <option value="vip" <?php echo $role == 'vip' ? 'selected' : ''; ?>>VIP</option>
                                                                <option value="admin" <?php echo $role == 'admin' ? 'selected' : ''; ?>>Admin</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="form-row">
                                                        <div class="form-group">
                                                            <label class="form-label">Verification Status</label>
                                                            <select name="verification_status" class="form-select">
                                                                <option value="unverified" <?php echo $verification_status == 'unverified' ? 'selected' : ''; ?>>Unverified</option>
                                                                <option value="pending" <?php echo $verification_status == 'pending' ? 'selected' : ''; ?>>Pending</option>
                                                                <option value="verified" <?php echo $verification_status == 'verified' ? 'selected' : ''; ?>>Verified</option>
                                                            </select>
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="form-label">Gender</label>
                                                            <select name="gender" class="form-select">
                                                                <option value="">Select</option>
                                                                <option value="Male" <?php echo $gender == 'Male' ? 'selected' : ''; ?>>Male</option>
                                                                <option value="Female" <?php echo $gender == 'Female' ? 'selected' : ''; ?>>Female</option>
                                                                <option value="Other" <?php echo $gender == 'Other' ? 'selected' : ''; ?>>Other</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="form-section">
                                                    <div class="form-section-title">Personal Details</div>
                                                    <div class="form-row">
                                                        <div class="form-group">
                                                            <label class="form-label">Date of Birth</label>
                                                            <input type="date" name="date_of_birth" class="form-input" value="<?php echo htmlspecialchars($date_of_birth); ?>">
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="form-label">Address</label>
                                                            <input type="text" name="address" class="form-input" value="<?php echo htmlspecialchars($address); ?>">
                                                        </div>
                                                    </div>
                                                    <div class="form-row">
                                                        <div class="form-group">
                                                            <label class="form-label">City</label>
                                                            <input type="text" name="city" class="form-input" value="<?php echo htmlspecialchars($city); ?>">
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="form-label">State/Province</label>
                                                            <input type="text" name="state" class="form-input" value="<?php echo htmlspecialchars($state); ?>">
                                                        </div>
                                                    </div>
                                                    <div class="form-row">
                                                        <div class="form-group">
                                                            <label class="form-label">Zip Code</label>
                                                            <input type="text" name="zip_code" class="form-input" value="<?php echo htmlspecialchars($zip_code); ?>">
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="form-label">Account Type</label>
                                                            <select name="account_type" class="form-select">
                                                                <option value="">Select</option>
                                                                <option value="personal" <?php echo $account_type == 'personal' ? 'selected' : ''; ?>>Personal</option>
                                                                <option value="business" <?php echo $account_type == 'business' ? 'selected' : ''; ?>>Business</option>
                                                                <option value="corporate" <?php echo $account_type == 'corporate' ? 'selected' : ''; ?>>Corporate</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="form-section">
                                                    <div class="form-section-title">Trading Preferences</div>
                                                    <div class="form-row">
                                                        <div class="form-group">
                                                            <label class="form-label">Trading Experience</label>
                                                            <select name="trading_experience" class="form-select">
                                                                <option value="">Select</option>
                                                                <option value="beginner" <?php echo $trading_experience == 'beginner' ? 'selected' : ''; ?>>Beginner</option>
                                                                <option value="intermediate" <?php echo $trading_experience == 'intermediate' ? 'selected' : ''; ?>>Intermediate</option>
                                                                <option value="advanced" <?php echo $trading_experience == 'advanced' ? 'selected' : ''; ?>>Advanced</option>
                                                                <option value="expert" <?php echo $trading_experience == 'expert' ? 'selected' : ''; ?>>Expert</option>
                                                            </select>
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="form-label">Investment Goal</label>
                                                            <select name="investment_goal" class="form-select">
                                                                <option value="">Select</option>
                                                                <option value="short_term" <?php echo $investment_goal == 'short_term' ? 'selected' : ''; ?>>Short Term</option>
                                                                <option value="long_term" <?php echo $investment_goal == 'long_term' ? 'selected' : ''; ?>>Long Term</option>
                                                                <option value="retirement" <?php echo $investment_goal == 'retirement' ? 'selected' : ''; ?>>Retirement</option>
                                                                <option value="wealth_building" <?php echo $investment_goal == 'wealth_building' ? 'selected' : ''; ?>>Wealth Building</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="form-row">
                                                        <div class="form-group">
                                                            <label class="form-label">Risk Tolerance</label>
                                                            <select name="risk_tolerance" class="form-select">
                                                                <option value="">Select</option>
                                                                <option value="low" <?php echo $risk_tolerance == 'low' ? 'selected' : ''; ?>>Low</option>
                                                                <option value="medium" <?php echo $risk_tolerance == 'medium' ? 'selected' : ''; ?>>Medium</option>
                                                                <option value="high" <?php echo $risk_tolerance == 'high' ? 'selected' : ''; ?>>High</option>
                                                            </select>
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="form-label">Preferred Currency</label>
                                                            <select name="preferred_currency" class="form-select">
                                                                <option value="">Select</option>
                                                                <option value="USD" <?php echo $preferred_currency == 'USD' ? 'selected' : ''; ?>>USD</option>
                                                                <option value="EUR" <?php echo $preferred_currency == 'EUR' ? 'selected' : ''; ?>>EUR</option>
                                                                <option value="GBP" <?php echo $preferred_currency == 'GBP' ? 'selected' : ''; ?>>GBP</option>
                                                                <option value="CAD" <?php echo $preferred_currency == 'CAD' ? 'selected' : ''; ?>>CAD</option>
                                                                <option value="AUD" <?php echo $preferred_currency == 'AUD' ? 'selected' : ''; ?>>AUD</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <div class="form-section">
                                                    <div class="form-section-title">Account Settings</div>
                                                    <div class="form-row">
                                                        <div class="form-group">
                                                            <label class="form-label">Notification Preference</label>
                                                            <select name="notification_preference" class="form-select">
                                                                <option value="">Select</option>
                                                                <option value="email" <?php echo $notification_preference == 'email' ? 'selected' : ''; ?>>Email Only</option>
                                                                <option value="sms" <?php echo $notification_preference == 'sms' ? 'selected' : ''; ?>>SMS Only</option>
                                                                <option value="both" <?php echo $notification_preference == 'both' ? 'selected' : ''; ?>>Both Email & SMS</option>
                                                                <option value="none" <?php echo $notification_preference == 'none' ? 'selected' : ''; ?>>None</option>
                                                            </select>
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="form-label">Two-Factor Auth</label><br>
                                                            <input type="checkbox" name="two_factor_auth" class="form-checkbox" value="1" <?php echo $two_factor_auth == '1' ? 'checked' : ''; ?>>
                                                            <span style="color:#94a3b8; font-size:0.8rem;">Enable 2FA</span>
                                                        </div>
                                                    </div>
                                                    <div class="form-row">
                                                        <div class="form-group">
                                                            <label class="form-label">Account Manager</label>
                                                            <input type="text" name="account_manager" class="form-input" value="<?php echo htmlspecialchars($account_manager); ?>">
                                                        </div>
                                                        <div class="form-group">
                                                            <label class="form-label">Last Login</label>
                                                            <input type="datetime-local" name="last_login" class="form-input" value="<?php echo htmlspecialchars($last_login); ?>">
                                                        </div>
                                                    </div>
                                                    <div class="form-row">
                                                        <div class="form-group">
                                                            <label class="form-label">IP Address</label>
                                                            <input type="text" name="ip_address" class="form-input" value="<?php echo htmlspecialchars($ip_address); ?>">
                                                        </div>
                                                    </div>
                                                </div>
                                                
                                                <button type="submit" name="update_user_details_btn" class="dropdown-btn" style="width:100%;">
                                                    <i class="ion-ios-save"></i> Update All Details
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <?php
                    }
                } else {
                    echo "<tr><td colspan='7' style='text-align:center; padding:20px; color:#94a3b8;'>No users found.</td></tr>";
                }
                ?>
            </tbody>
        </table>
    </div>

    <!-- ============================================ -->
    <!-- SECTION 2: PENDING DEPOSITS -->
    <!-- ============================================ -->
    <h3 class="section-title">Pending Deposits</h3>
    <div class="table-wrapper">
        <table>
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Email</th>
                    <th>Method</th>
                    <th>Amount</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if (mysqli_num_rows($dep_result) > 0) {
                    while($row = mysqli_fetch_assoc($dep_result)) {
                        $depId = $row['id'];
                        $depEmail = $row['email'];
                        $depAmt = $row['amount'];
                        $depMethod = $row['payment_option'];
                        $depDate = $row['created_at'];
                        ?>
                        <tr>
                            <td data-label="Date"><?php echo date("M d, Y", strtotime($depDate)); ?></td>
                            <td data-label="Email"><?php echo htmlspecialchars($depEmail); ?></td>
                            <td data-label="Method" style="text-transform:uppercase; color:#eab308;"><?php echo $depMethod; ?></td>
                            <td data-label="Amount" style="color:#4ade80; font-weight:bold;">$<?php echo number_format($depAmt, 2); ?></td>
                            <td data-label="Action">
                                <form method="POST" style="display:inline-flex; gap:5px;">
                                    <input type="hidden" name="deposit_id" value="<?php echo $depId; ?>">
                                    <input type="hidden" name="deposit_email" value="<?php echo $depEmail; ?>">
                                    <input type="hidden" name="deposit_amount" value="<?php echo $depAmt; ?>">
                                    
                                    <button type="submit" name="verify_deposit_btn" class="btn-update btn-green" onclick="return confirm('Verify Deposit?');">
                                        <i class="ion-checkmark-circle"></i> Verify
                                    </button>
                                    <button type="submit" name="delete_deposit_btn" class="btn-update btn-red" onclick="return confirm('Delete Deposit?');">
                                        <i class="ion-trash-a"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php
                    }
                } else {
                    echo "<tr><td colspan='5' style='text-align:center; padding:20px; color:#94a3b8;'>No pending deposits.</td></tr>";
                }
                ?>
            </tbody>
        </table>
    </div>

    <!-- ============================================ -->
    <!-- SECTION 3: PENDING WITHDRAWALS -->
    <!-- ============================================ -->
    <h3 class="section-title">Pending Withdrawals</h3>
    <div class="table-wrapper">
        <table>
            <thead>
                <tr>
                    <th>User</th>
                    <th>Amount</th>
                    <th>Method</th>
                    <th>Wallet / Details</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                if ($with_result && mysqli_num_rows($with_result) > 0) {
                    while($row = mysqli_fetch_assoc($with_result)) {
                        $wId = $row['id'];
                        $wEmail = $row['email'];
                        $wAmt = $row['amount'];
                        $wMethod = isset($row['payment_mode']) ? $row['payment_mode'] : (isset($row['method']) ? $row['method'] : 'Crypto');
                        $wWallet = isset($row['wallet_address']) ? $row['wallet_address'] : (isset($row['details']) ? $row['details'] : 'N/A');
                        ?>
                        <tr>
                            <td data-label="User">
                                <?php echo htmlspecialchars($wEmail); ?>
                            </td>
                            <td data-label="Amount" style="color:#ef4444; font-weight:bold;">
                                $<?php echo number_format($wAmt, 2); ?>
                            </td>
                            <td data-label="Method"><?php echo htmlspecialchars($wMethod); ?></td>
                            <td data-label="Details" style="font-family:monospace; color:#38bdf8; font-size:0.9em; max-width:200px; word-wrap:break-word;">
                                <?php echo htmlspecialchars($wWallet); ?>
                            </td>
                            <td data-label="Action">
                                <form method="POST" style="display:inline-flex; gap:5px;">
                                    <input type="hidden" name="withdraw_id" value="<?php echo $wId; ?>">
                                    <input type="hidden" name="withdraw_email" value="<?php echo $wEmail; ?>">
                                    
                                    <button type="submit" name="approve_withdraw_btn" class="btn-update btn-green" onclick="return confirm('Mark as Paid/Completed?');">
                                        <i class="ion-checkmark-circle"></i> Approve
                                    </button>
                                    
                                    <button type="submit" name="delete_withdraw_btn" class="btn-update btn-red" onclick="return confirm('Delete this request?');">
                                        <i class="ion-trash-a"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php
                    }
                } else {
                    echo "<tr><td colspan='5' style='text-align:center; padding:20px; color:#94a3b8;'>No pending withdrawals found.</td></tr>";
                }
                ?>
            </tbody>
        </table>
    </div>

</div>

<script>
// Toggle dropdown functionality
function toggleDropdown(userId) {
    var dropdown = document.getElementById('dropdown-' + userId);
    dropdown.classList.toggle('active');
}

// Close dropdowns when clicking outside
document.addEventListener('click', function(event) {
    if (!event.target.matches('.user-dropdown-btn')) {
        var dropdowns = document.getElementsByClassName('user-dropdown');
        for (var i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('active')) {
                openDropdown.classList.remove('active');
            }
        }
    }
});

// Image modal function
function openImageModal(src) {
    if (!src || src.includes('No Image')) return;
    
    var modal = document.createElement('div');
    modal.style.position = 'fixed';
    modal.style.top = '0';
    modal.style.left = '0';
    modal.style.width = '100%';
    modal.style.height = '100%';
    modal.style.backgroundColor = 'rgba(0,0,0,0.9)';
    modal.style.display = 'flex';
    modal.style.alignItems = 'center';
    modal.style.justifyContent = 'center';
    modal.style.zIndex = '1000';
    
    var img = document.createElement('img');
    img.src = src;
    img.style.maxWidth = '90%';
    img.style.maxHeight = '90%';
    img.style.objectFit = 'contain';
    
    var closeBtn = document.createElement('button');
    closeBtn.innerHTML = '×';
    closeBtn.style.position = 'absolute';
    closeBtn.style.top = '20px';
    closeBtn.style.right = '30px';
    closeBtn.style.fontSize = '40px';
    closeBtn.style.color = 'white';
    closeBtn.style.background = 'transparent';
    closeBtn.style.border = 'none';
    closeBtn.style.cursor = 'pointer';
    closeBtn.style.zIndex = '1001';
    
    modal.appendChild(img);
    modal.appendChild(closeBtn);
    document.body.appendChild(modal);
    
    closeBtn.onclick = function() {
        document.body.removeChild(modal);
    };
    
    modal.onclick = function(e) {
        if (e.target === modal) {
            document.body.removeChild(modal);
        }
    };
}
</script>
 <!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/696421659fb0c8197f6ebc18/1jeni4tt8';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>