<?php

if (!defined('ABSPATH')) exit;

class VS_Wallet {
    public static function init() {
        new self();
    }

    public function __construct() {
        add_action('wp_ajax_vs_handle_withdraw_ajax', [$this, 'handle_withdraw_ajax']);
        add_action('woocommerce_order_status_processing',[$this, 'add_order_to_wallet']);

        add_action('woocommerce_order_status_completed',[$this, 'add_order_to_wallet']);
    }
public function add_order_to_wallet($order_id) {

    $order = wc_get_order($order_id);

    if (!$order) {
        return;
    }

    $status = $order->get_status();

    /**
     * Prevent duplicate processing per status
     */
    $meta_key = '_vs_wallet_processed_' . $status;

    if (get_post_meta($order_id, $meta_key, true)) {
        return;
    }

    foreach ($order->get_items() as $item) {

        $product_id = $item->get_product_id();

        $vendor_id = get_post_field(
            'post_author',
            $product_id
        );

        if (!$vendor_id) {
            continue;
        }

        $total = (float) $item->get_total();
        $commission = $this->calculate_commission($total);
        $earning = $total - $commission;

        $wallet_total = (float) get_user_meta(
            $vendor_id,
            '_vs_wallet_total',
            true
        );

        $wallet_pending = (float) get_user_meta(
            $vendor_id,
            '_vs_wallet_pending',
            true
        );

        $wallet_available = (float) get_user_meta(
            $vendor_id,
            '_vs_wallet_available',
            true
        );
        if ($status === 'processing') {
            update_user_meta(
                $vendor_id,
                '_vs_wallet_total',
                $wallet_total + $earning
            );

            update_user_meta(
                $vendor_id,
                '_vs_wallet_pending',
                $wallet_pending + $earning
            );
        }
        if ($status === 'completed') {
            if (get_post_meta($order_id, '_vs_wallet_processed_processing', true)) {

                update_user_meta(
                    $vendor_id,
                    '_vs_wallet_pending',
                    max(0, $wallet_pending - $earning)
                );
            } else {

                update_user_meta(
                    $vendor_id,
                    '_vs_wallet_total',
                    $wallet_total + $earning
                );
            }

            update_user_meta(
                $vendor_id,
                '_vs_wallet_available',
                $wallet_available + $earning
            );
        }
    }

    update_post_meta($order_id, $meta_key, 1);
}
/**
 * =====================================
 * GET WALLET SETTINGS
 * =====================================
 */
public function get_wallet_settings() {

    $settings = get_option('vs_settings');

    $wallet = isset($settings['wallet']) ? $settings['wallet'] : [];

    return [
        'min_withdrawal' => isset($wallet['min_withdrawal'])
            ? (float) $wallet['min_withdrawal']
            : 50,

        'max_withdrawal' => isset($wallet['max_withdrawal'])
            ? (float) $wallet['max_withdrawal']
            : 0, // 0 = unlimited
    ];
}
   /**
 * =====================================
 * GET COMMISSION RATE
 * =====================================
 */
public function get_commission_rate() {

    return (float) get_option(
        'woocommerce_vs_commission_rate',
        10
    );
}

/**
 * =====================================
 * GET COMMISSION TYPE
 * =====================================
 */
public function get_commission_type() {

    return (string) get_option(
        'woocommerce_vs_commission_type',
        'percentage'
    );
}    /**
     * =====================================
     * CALCULATE COMMISSION
     * =====================================
     */
    public function calculate_commission($amount) {

        $rate = $this->get_commission_rate();

        $type = $this->get_commission_type();

        /**
         * Percentage
         */
        if ($type === 'percentage') {

            return ($amount * $rate) / 100;
        }

        /**
         * Fixed
         */
        if ($type === 'fixed') {

            return min($rate, $amount);
        }

        /**
         * Hybrid
         */
        if ($type === 'hybrid') {

            $percentage = ($amount * $rate) / 100;

            return $percentage + 2;
        }

        return 0;
    }
/**
 * =====================================
 * SYNC WALLET FROM EXISTING ORDERS
 * =====================================
 */
public function sync_wallet_from_orders($vendor_id) {

    $args = [
        'status' => ['processing', 'completed'],
        'limit'  => -1,
    ];

    $orders = wc_get_orders($args);

    $total = 0;
    $pending = 0;
    $available = 0;

    foreach ($orders as $order) {

        $status = $order->get_status();

        foreach ($order->get_items() as $item) {

            $product_id = $item->get_product_id();

            $author_id = (int) get_post_field(
                'post_author',
                $product_id
            );

            if ($author_id !== (int) $vendor_id) {
                continue;
            }

            $item_total = (float) $item->get_total();

            $commission = $this->calculate_commission($item_total);

            $earning = $item_total - $commission;

            /**
             * Total
             */
            $total += $earning;

            /**
             * Processing -> Pending
             */
            if ($status === 'processing') {
                $pending += $earning;
            }

            /**
             * Completed -> Available
             */
            if ($status === 'completed') {
                $available += $earning;
            }
        }
    }

    $withdrawn = (float) get_user_meta(
        $vendor_id,
        '_vs_wallet_withdrawn',
        true
    );

    /**
     * Remove withdrawn from available
     */
    $available = max(0, $available - $withdrawn);

    update_user_meta($vendor_id, '_vs_wallet_total', $total);

    update_user_meta($vendor_id, '_vs_wallet_pending', $pending);

    update_user_meta($vendor_id, '_vs_wallet_available', $available);

    return $total;
}
/**
 * =====================================
 * GET WALLET DATA
 * =====================================
 */
public function get_wallet($vendor_id) {

    $total_meta = get_user_meta($vendor_id, '_vs_wallet_total', true);
    $pending_meta = get_user_meta($vendor_id, '_vs_wallet_pending', true);

    // If total or pending has never been set, run a full sync
    if ($total_meta === '' || $pending_meta === '') {
        $this->sync_wallet_from_orders($vendor_id);
        $total = (float) get_user_meta($vendor_id, '_vs_wallet_total', true);
        $pending = (float) get_user_meta($vendor_id, '_vs_wallet_pending', true);
    } else {
        $total = (float) $total_meta;
        $pending = (float) $pending_meta;
    }

    $available = (float) get_user_meta(
        $vendor_id,
        '_vs_wallet_available',
        true
    );

    $withdrawn = (float) get_user_meta(
        $vendor_id,
        '_vs_wallet_withdrawn',
        true
    );



   $commission_rate = $this->get_commission_rate();
$commission_type = $this->get_commission_type();
$gross_total = $total;

$commission_amount = 0;

if ($commission_type === 'percentage') {

    $commission_amount =
        ($gross_total * $commission_rate) / (100 - $commission_rate);

} elseif ($commission_type === 'fixed') {

    /**
     * Approximation for fixed commission
     */
    $commission_amount = 0;

} elseif ($commission_type === 'hybrid') {

    $commission_amount = 0;
}

    return [
        'total'             => $total,
        'pending'           => $pending,
        'available'         => $available,
        'withdrawn'         => $withdrawn,
        'net_earnings'      => $available + $pending,
        'commission_rate'   => $commission_rate,
        'commission_type'   => $commission_type,
        'commission_amount' => $commission_amount,
        'commission_amount' => $total - ($available + $pending + $withdrawn), // Approximation or calculated from items
    ];
}

    /**
 * =====================================
 * AJAX WITHDRAW HANDLER
 * =====================================
 */
public function handle_withdraw_ajax() {
    global $wpdb;

    if (!is_user_logged_in()) {
        wp_send_json_error(['message' => __('You must be logged in.', 'vendor-space')]);
    }

    if (!isset($_POST['vs_withdraw_nonce']) || !wp_verify_nonce($_POST['vs_withdraw_nonce'], 'vs_withdraw_request')) {
        wp_send_json_error(['message' => __('Security check failed.', 'vendor-space')]);
    }

    $vendor_id = get_current_user_id();
    $amount = isset($_POST['withdraw_amount']) ? (float) $_POST['withdraw_amount'] : 0;
    $iban = isset($_POST['vendor_iban']) ? sanitize_text_field($_POST['vendor_iban']) : '';

    if (empty($iban)) {
        wp_send_json_error(['message' => __('IBAN is required.', 'vendor-space')]);
    }

    // Save IBAN
    update_user_meta($vendor_id, 'vendor_iban', $iban);

    $settings = $this->get_wallet_settings();
    $wallet = $this->get_wallet($vendor_id);

    // Validation
    if ($amount < $settings['min_withdrawal']) {
        wp_send_json_error(['message' => sprintf(__('Minimum withdraw amount is %s', 'vendor-space'), $settings['min_withdrawal'])]);
    }

    if ($settings['max_withdrawal'] > 0 && $amount > $settings['max_withdrawal']) {
        wp_send_json_error(['message' => sprintf(__('Maximum withdraw per request is %s', 'vendor-space'), $settings['max_withdrawal'])]);
    }

    $pending_withdrawals = $wpdb->get_var($wpdb->prepare(
        "SELECT SUM(amount) FROM {$wpdb->prefix}vs_withdrawals WHERE vendor_id = %d AND status = 'pending'",
        $vendor_id
    ));

    if (($amount + (float)$pending_withdrawals) > $wallet['available']) {
        wp_send_json_error(['message' => __('Insufficient balance. You already have pending withdrawal requests.', 'vendor-space')]);
    }

    // Insert Request
    $table = $wpdb->prefix . 'vs_withdrawals';
    $result = $wpdb->insert(
        $table,
        [
            'vendor_id'  => $vendor_id,
            'amount'     => $amount,
            'status'     => 'pending',
            'created_at' => current_time('mysql')
        ],
        ['%d', '%f', '%s', '%s']
    );

    if ($result === false) {
        wp_send_json_error(['message' => __('Database error. Please try again.', 'vendor-space')]);
    }

    // Send Notification
    if (class_exists('VS_Notification')) {
        VS_Notification::send_withdrawal_requested($vendor_id, $amount);
    }

    wp_send_json_success(['message' => __('Withdraw request submitted successfully. It will be processed after admin approval.', 'vendor-space')]);
}

/**
 * =====================================
 * CREATE WITHDRAW REQUEST
 * =====================================
 */
public function handle_withdraw_request() {
    global $wpdb;

    if (!is_user_logged_in()) {
        return;
    }

    if (!isset($_POST['vs_withdraw_nonce'])) {
        return;
    }

    if (
        !wp_verify_nonce(
            $_POST['vs_withdraw_nonce'],
            'vs_withdraw_request'
        )
    ) {
        return;
    }

    $vendor_id = get_current_user_id();

    $wallet = $this->get_wallet($vendor_id);

    $amount = isset($_POST['withdraw_amount'])
        ? (float) $_POST['withdraw_amount']
        : 0;

    /**
     * Minimum withdraw
     */
   $settings = $this->get_wallet_settings();

/**
 * MIN withdrawal
 */
if ($amount < $settings['min_withdrawal']) {

    wc_add_notice(
        sprintf(
            __('Minimum withdraw amount is %s', 'vendor-space'),
            $settings['min_withdrawal']
        ),
        'error'
    );

    return;
}

/**
 * MAX withdrawal
 */
if (
    $settings['max_withdrawal'] > 0 &&
    $amount > $settings['max_withdrawal']
) {

    wc_add_notice(
        sprintf(
            __('Maximum withdraw per request is %s', 'vendor-space'),
            $settings['max_withdrawal']
        ),
        'error'
    );

    return;
}

    /**
     * Cannot exceed available balance (including pending requests)
     */
    $pending_withdrawals = $wpdb->get_var($wpdb->prepare(
        "SELECT SUM(amount) FROM {$wpdb->prefix}vs_withdrawals WHERE vendor_id = %d AND status = 'pending'",
        $vendor_id
    ));

    if (($amount + (float)$pending_withdrawals) > $wallet['available']) {

        wc_add_notice(
            __('Insufficient balance. You already have pending withdrawal requests.', 'vendor-space'),
            'error'
        );

        return;
    }
    $table = $wpdb->prefix . 'vs_withdrawals';

    $result = $wpdb->insert(
        $table,
        [
            'vendor_id'  => $vendor_id,
            'amount'     => $amount,
            'status'     => 'pending',
            'created_at' => current_time('mysql')
        ],
        [
            '%d',
            '%s',
            '%s',
            '%s'
        ]
    );

    if ($result === false) {
        wc_add_notice(
            'DB Error: ' . $wpdb->last_error,
            'error'
        );
        return;
    }

    // Send Notification
    if (class_exists('VS_Notification')) {
        VS_Notification::send_withdrawal_requested($vendor_id, $amount);
    }

    wc_add_notice(
        __('Withdraw request submitted successfully. It will be processed after admin approval.', 'vendor-space'),
        'success'
    );
}
    /**
     * =====================================
     * RENDER WALLET STATS
     * =====================================
     */


    public function render_wallet_stats() {

        if (!is_user_logged_in()) {
            return '<p>Please login first.</p>';
        }

        $vendor_id = get_current_user_id();

        $wallet = $this->get_wallet($vendor_id);

        $currency = function_exists('get_woocommerce_currency_symbol')
            ? get_woocommerce_currency_symbol()
            : '$';

        ob_start();
        ?>

<div class="vs-tab" id="tab-wallet" style="display:none;">
      <?php

$is_admin = current_user_can('administrator');

$currency = get_woocommerce_currency_symbol();

/**
 * ADMIN GLOBAL STATS
 */
if ($is_admin) {

    global $wpdb;

    $all_totals = $wpdb->get_var("
        SELECT SUM(meta_value)
        FROM {$wpdb->usermeta}
        WHERE meta_key = '_vs_wallet_total'
    ");

    $all_pending = $wpdb->get_var("
        SELECT SUM(meta_value)
        FROM {$wpdb->usermeta}
        WHERE meta_key = '_vs_wallet_pending'
    ");

    $all_available = $wpdb->get_var("
        SELECT SUM(meta_value)
        FROM {$wpdb->usermeta}
        WHERE meta_key = '_vs_wallet_available'
    ");

    $wallet['total'] = (float) $all_totals;
    $wallet['pending'] = (float) $all_pending;
    $wallet['available'] = (float) $all_available;

    $wallet['commission_amount'] = $this->calculate_commission(
        $wallet['total']
    );

    $wallet['net_earnings'] =
        $wallet['total'] - $wallet['commission_amount'];
}

?>

<div class="vs-wallet-dashboard">

    <div class="vs-wallet-header">

        <div class="vs-wallet-heading">

            <h2>
                <?php
                echo $is_admin
                    ? 'Platform Wallet Overview'
                    : 'Wallet Overview';
                ?>
            </h2>

            <p>
                <?php
                echo $is_admin
                    ? 'Global financial statistics for all vendors.'
                    : 'Track your vendor earnings and balances.';
                ?>
            </p>

        </div>

        <?php if($is_admin): ?>

            <div class="vs-wallet-admin-badge">
                <i class="fas fa-shield-alt"></i>
                Administrator Mode
            </div>

        <?php endif; ?>

    </div>

    <!-- ================================================= -->
    <!-- STATS CARDS -->
    <!-- ================================================= -->

    <div class="vs-wallet-stats-grid">

        <!-- TOTAL -->
        <div class="vs-wallet-card vs-wallet-card-primary">

            <div class="vs-wallet-card-top">

                <div>
                    <div class="vs-wallet-card-label">
                        Total Earnings
                    </div>

                    <div class="vs-wallet-card-value">
                        <?php echo $currency; ?>
                        <?php echo number_format($wallet['total'], 2); ?>
                    </div>
                </div>

                <div class="vs-wallet-card-icon">
                    <i class="fas fa-wallet"></i>
                </div>

            </div>

            <div class="vs-wallet-card-meta">
                Gross platform revenue
            </div>

        </div>

        <!-- NET -->
        <div class="vs-wallet-card vs-wallet-card-success">

            <div class="vs-wallet-card-top">

                <div>
                    <div class="vs-wallet-card-label">
                        Net Earnings
                    </div>

                    <div class="vs-wallet-card-value">
                        <?php echo $currency; ?>
                        <?php echo number_format($wallet['net_earnings'], 2); ?>
                    </div>
                </div>

                <div class="vs-wallet-card-icon">
                    <i class="fas fa-chart-line"></i>
                </div>

            </div>

            <div class="vs-wallet-card-meta">
                Earnings after commission
            </div>

            

        </div>
<div class="vs-wallet-card vs-wallet-card-warning">

    <div class="vs-wallet-card-top">

        <div>
            <div class="vs-wallet-card-label">
                Platform Commission
            </div>

            <div class="vs-wallet-card-value">
                <?php echo $currency; ?>
                <?php echo number_format($wallet['commission_amount'], 2); ?>
            </div>
        </div>

        <div class="vs-wallet-card-icon">
            <i class="fas fa-percentage"></i>
        </div>

    </div>

    <div class="vs-wallet-card-meta">

        <?php if ($wallet['commission_type'] === 'percentage') : ?>

            Commission: <?php echo esc_html($wallet['commission_rate']); ?>%

        <?php elseif ($wallet['commission_type'] === 'fixed') : ?>

            Fixed fee: <?php echo $currency . esc_html($wallet['commission_rate']); ?>

        <?php elseif ($wallet['commission_type'] === 'hybrid') : ?>

            <?php echo esc_html($wallet['commission_rate']); ?>% + Fixed fee

        <?php endif; ?>

    </div>

</div>
        <!-- COMMISSION -->
        <?php if($is_admin): ?>

        <div class="vs-wallet-card vs-wallet-card-danger">

            <div class="vs-wallet-card-top">

                <div>
                    <div class="vs-wallet-card-label">
                        Platform Commission
                    </div>

                    <div class="vs-wallet-card-value">
                        <?php echo $currency; ?>
                        <?php echo number_format($wallet['commission_amount'], 2); ?>
                    </div>
                </div>

                <div class="vs-wallet-card-icon">
                    <i class="fas fa-percent"></i>
                </div>

            </div>

            <div class="vs-wallet-card-meta">
                Commission collected by platform
            </div>

        </div>

        <?php endif; ?>

        <!-- PENDING -->
        <div class="vs-wallet-card vs-wallet-card-warning">

            <div class="vs-wallet-card-top">

                <div>
                    <div class="vs-wallet-card-label">
                        Pending Balance
                    </div>

                    <div class="vs-wallet-card-value">
                        <?php echo $currency; ?>
                        <?php echo number_format($wallet['pending'], 2); ?>
                    </div>
                </div>

                <div class="vs-wallet-card-icon">
                    <i class="fas fa-clock"></i>
                </div>

            </div>

            <div class="vs-wallet-card-meta">
                Orders still processing
            </div>

        </div>

        <!-- AVAILABLE -->
        <div class="vs-wallet-card vs-wallet-card-primary">

            <div class="vs-wallet-card-top">

                <div>
                    <div class="vs-wallet-card-label">
                        Available Balance
                    </div>

                    <div class="vs-wallet-card-value">
                        <?php echo $currency; ?>
                        <?php echo number_format($wallet['available'], 2); ?>
                    </div>
                </div>

                <div class="vs-wallet-card-icon">
                    <i class="fas fa-money-bill-wave"></i>
                </div>

            </div>

            <div class="vs-wallet-card-meta">
                Ready for withdrawal
            </div>

        </div>

    </div>

</div>
<div class="vs-wallet-withdraw-box">

    <div class="vs-wallet-withdraw-header">

        <h3>Request Withdraw</h3>

      <?php 
      $settings = $this->get_wallet_settings(); 
      $can_withdraw = $wallet['available'] >= $settings['min_withdrawal'];
      ?>

<p>
    Withdraw limits:
    <strong>
        <?php echo esc_html($currency . $settings['min_withdrawal']); ?>
        -
        <?php echo $settings['max_withdrawal'] > 0
            ? esc_html($currency . $settings['max_withdrawal'])
            : 'No limit'; ?>
    </strong>
</p>
    </div>

    <form id="vs-withdraw-request-form" class="vs-wallet-withdraw-form">

        <?php wp_nonce_field(
            'vs_withdraw_request',
            'vs_withdraw_nonce'
        ); ?>

        <div class="vs-wallet-form-group">
            <label><?php _e('IBAN / Bank Account', 'vendor-space'); ?></label>
            <?php $current_iban = get_user_meta(get_current_user_id(), 'vendor_iban', true); ?>
            <input type="text" name="vendor_iban" value="<?php echo esc_attr($current_iban); ?>" placeholder="E.g. SA00 0000 0000 0000 0000 0000" required <?php if (!$can_withdraw) echo 'disabled'; ?>>
        </div>

        <div class="vs-wallet-form-group">

            <label>
                Withdraw Amount
            </label>

           <input
    type="number"
    step="0.01"
    id="vs-withdraw-amount"
    min="<?php echo esc_attr($settings['min_withdrawal']); ?>"
    <?php if($settings['max_withdrawal'] > 0): ?>
        max="<?php echo esc_attr($settings['max_withdrawal']); ?>"
    <?php endif; ?>
    name="withdraw_amount"
    required
    <?php if (!$can_withdraw) echo 'disabled'; ?>
>

        </div>

        <button
            type="submit"
            id="vs-withdraw-submit-btn"
            class="vs-wallet-withdraw-btn"
            <?php if (!$can_withdraw) echo 'disabled style="background: #94a3b8; cursor: not-allowed; box-shadow: none; transform: none;"'; ?>
        >
            <span class="vs-btn-text"><?php _e('Request Withdraw', 'vendor-space'); ?></span>
            <span class="vs-btn-loader" style="display:none;"><i class="fas fa-spinner fa-spin"></i></span>
        </button>

    </form>

    <?php if (!$can_withdraw): ?>
        <div class="vs-wallet-withdraw-error" style="margin-top: 20px; padding: 15px; background: #fef2f2; border: 1px solid #fee2e2; border-radius: 12px; color: #dc2626; font-weight: 600; display: flex; align-items: center; gap: 10px;">
            <i class="fas fa-exclamation-triangle"></i>
            <?php _e('You cannot withdraw because your balance is less than the minimum withdrawal amount.', 'vendor-space'); ?>
        </div>
    <?php endif; ?>

</div>

        <style>
            /* =========================================================
   WITHDRAW BOX
   ========================================================= */

.vs-wallet-withdraw-box{

    margin-top:30px;

    background:#fff;

    border-radius:24px;

    padding:28px;

    border:1px solid rgba(226,232,240,.8);

    box-shadow:
        0 1px 2px rgba(15,23,42,.03),
        0 10px 30px rgba(15,23,42,.05);
}

.vs-wallet-withdraw-header{
    margin-bottom:24px;
}

.vs-wallet-withdraw-header h3{

    margin:0 0 8px;

    font-size:24px;
    font-weight:800;

    color:#0f172a;
}

.vs-wallet-withdraw-header p{

    margin:0;

    color:#64748b;

    font-size:14px;
}

/* =========================================================
   FORM
   ========================================================= */

.vs-wallet-withdraw-form{
    display:flex;
    flex-direction:column;
    gap:16px;
    flex-wrap:wrap;
}

.vs-wallet-form-group{
    flex:1;
    width:50%;
}

.vs-wallet-form-group label{

    display:block;

    margin-bottom:10px;

    font-size:14px;
    font-weight:700;

    color:#334155;
}

.vs-wallet-form-group input{

    width:100%;

    height:24px;

    border-radius:16px;

    border:1px solid #dbe3ef;

    padding:0 10px;

    font-size:15px;

    background:#fff;

    transition:
        border-color .2s ease,
        box-shadow .2s ease;
}

.vs-wallet-form-group input:focus{

    outline:none;

    border-color:#2563eb;

    box-shadow:
        0 0 0 4px rgba(37,99,235,.12);
}

/* =========================================================
   BUTTON
   ========================================================= */

.vs-wallet-withdraw-btn{

    height:54px;

    padding:0 26px;

    border:none;

    border-radius:16px;

    background:#2563eb;

    color:#fff;

    font-size:15px;
    font-weight:700;

    cursor:pointer;

    transition:
        transform .2s ease,
        background .2s ease,
        box-shadow .2s ease;

    box-shadow:
        0 10px 20px rgba(37,99,235,.18);
}

.vs-wallet-withdraw-btn:hover{

    background:#1d4ed8;

    transform:translateY(-2px);

    box-shadow:
        0 14px 30px rgba(37,99,235,.25);
}

.vs-wallet-withdraw-btn:active{
    transform:translateY(0);
}

@media(max-width:768px){

    .vs-wallet-withdraw-form{
        flex-direction:column;
        align-items:stretch;
    }

    .vs-wallet-withdraw-btn{
        width:100%;
    }
}
/* =========================================================
   VS WALLET — ULTRA PROFESSIONAL UI
   ========================================================= */

.vs-wallet-dashboard{

    --vs-primary:#2563eb;
    --vs-success:#16a34a;
    --vs-danger:#dc2626;
    --vs-warning:#d97706;
    --vs-dark:#0f172a;
    --vs-muted:#64748b;
    --vs-border:#e2e8f0;
    --vs-bg:#f8fafc;

    font-family: Inter, sans-serif;
    padding: 24px;
    background: var(--vs-bg);
    border-radius: 26px;
}

/* =========================================================
   HEADER
   ========================================================= */

.vs-wallet-header{
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-bottom:30px;
    gap:20px;
    flex-wrap:wrap;
}

.vs-wallet-heading h2{
    margin:0;
    font-size:30px;
    font-weight:800;
    color:var(--vs-dark);
    letter-spacing:-0.03em;
}

.vs-wallet-heading p{
    margin:8px 0 0;
    color:var(--vs-muted);
    font-size:15px;
}

/* =========================================================
   STATS GRID
   ========================================================= */

.vs-wallet-stats-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(250px,1fr));
    gap:22px;
    margin-bottom:30px;
}

/* =========================================================
   CARD
   ========================================================= */

.vs-wallet-card{

    position:relative;
    overflow:hidden;

    background:#fff;
    border-radius:24px;
    padding:24px;

    border:1px solid rgba(226,232,240,.7);

    box-shadow:
        0 1px 2px rgba(15,23,42,.03),
        0 10px 30px rgba(15,23,42,.06);

    transition:
        transform .25s ease,
        box-shadow .25s ease,
        border-color .25s ease;
}

.vs-wallet-card:hover{

    transform:translateY(-4px);

    border-color:rgba(37,99,235,.18);

    box-shadow:
        0 8px 25px rgba(37,99,235,.08),
        0 20px 40px rgba(15,23,42,.08);
}

/* =========================================================
   CARD TOP
   ========================================================= */

.vs-wallet-card-top{
    display:flex;
    justify-content:space-between;
    align-items:flex-start;
    margin-bottom:20px;
}

.vs-wallet-card-label{
    color:var(--vs-muted);
    font-size:14px;
    font-weight:600;
    margin-bottom:8px;
}

.vs-wallet-card-value{
    font-size:34px;
    font-weight:800;
    color:var(--vs-dark);
    line-height:1;
    letter-spacing:-0.04em;
}

/* =========================================================
   ICON
   ========================================================= */

.vs-wallet-card-icon{

    width:58px;
    height:58px;

    display:flex;
    align-items:center;
    justify-content:center;

    border-radius:18px;

    font-size:22px;
    flex-shrink:0;
}

/* =========================================================
   COLORS
   ========================================================= */

.vs-wallet-card-primary .vs-wallet-card-icon{
    background:rgba(37,99,235,.12);
    color:var(--vs-primary);
}

.vs-wallet-card-success .vs-wallet-card-icon{
    background:rgba(22,163,74,.12);
    color:var(--vs-success);
}

.vs-wallet-card-danger .vs-wallet-card-icon{
    background:rgba(220,38,38,.12);
    color:var(--vs-danger);
}

.vs-wallet-card-warning .vs-wallet-card-icon{
    background:rgba(217,119,6,.12);
    color:var(--vs-warning);
}

/* =========================================================
   SMALL META
   ========================================================= */

.vs-wallet-card-meta{
    margin-top:18px;
    font-size:13px;
    color:var(--vs-muted);
    display:flex;
    align-items:center;
    gap:6px;
}

/* =========================================================
   TABLE WRAPPER
   ========================================================= */

.vs-wallet-table-wrapper{

    background:#fff;

    border-radius:24px;

    overflow:hidden;

    border:1px solid rgba(226,232,240,.7);

    box-shadow:
        0 1px 2px rgba(15,23,42,.03),
        0 10px 30px rgba(15,23,42,.05);
}

/* =========================================================
   TABLE
   ========================================================= */

.vs-wallet-table{
    width:100%;
    border-collapse:collapse;
}

.vs-wallet-table thead{
    background:#f8fafc;
}

.vs-wallet-table thead th{

    padding:18px 22px;

    text-align:left;

    font-size:13px;
    font-weight:700;

    text-transform:uppercase;
    letter-spacing:.04em;

    color:#475569;
}

.vs-wallet-table tbody tr{
    transition:background .2s ease;
}

.vs-wallet-table tbody tr:hover{
    background:#f8fafc;
}

.vs-wallet-table tbody td{

    padding:20px 22px;

    border-top:1px solid #f1f5f9;

    font-size:15px;
    font-weight:600;

    color:#0f172a;
}

/* =========================================================
   STATUS COLORS
   ========================================================= */

.vs-text-success{
    color:var(--vs-success) !important;
}

.vs-text-danger{
    color:var(--vs-danger) !important;
}

.vs-text-warning{
    color:var(--vs-warning) !important;
}

.vs-text-primary{
    color:var(--vs-primary) !important;
}

/* =========================================================
   ADMIN BADGE
   ========================================================= */

.vs-wallet-admin-badge{

    display:inline-flex;
    align-items:center;
    gap:8px;

    padding:10px 16px;

    background:rgba(37,99,235,.08);

    color:var(--vs-primary);

    border-radius:999px;

    font-size:13px;
    font-weight:700;
}

/* =========================================================
   RESPONSIVE
   ========================================================= */

@media(max-width:768px){

    .vs-wallet-dashboard{
        padding:16px;
    }

    .vs-wallet-card{
        padding:20px;
    }

    .vs-wallet-card-value{
        font-size:28px;
    }

    .vs-wallet-table{
        min-width:700px;
    }
}
/* ===========================
   WITHDRAW BOX - PRO STYLE
=========================== */

.vs-wallet-withdraw-box {
    background: #ffffff;
    border-radius: 18px;
    padding: 24px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.06);
    border: 1px solid #eef0f3;
    width:60%;
    margin-top: 25px;
    transition: all 0.3s ease;
}

.vs-wallet-withdraw-box:hover {
    transform: translateY(-2px);
    box-shadow: 0 14px 40px rgba(0,0,0,0.08);
}

/* Header */
.vs-wallet-withdraw-header h3 {
    font-size: 20px;
    font-weight: 700;
    margin-bottom: 10px;
    color: #111827;
}

.vs-wallet-withdraw-header p {
    font-size: 14px;
    color: #6b7280;
    margin-top: 8px;
}

/* Form */
.vs-wallet-withdraw-form {
    margin-top: 20px;
}

/* Inputs */
.vs-wallet-form-group {
    margin-bottom: 18px;
}

.vs-wallet-form-group label {
    display: block;
    font-weight: 600;
    margin-bottom: 8px;
    font-size: 14px;
    color: #374151;
}

.vs-wallet-form-group input {
    width: 100%;
    padding: 12px 14px;
    border-radius: 12px;
    border: 1px solid #e5e7eb;
    font-size: 14px;
    outline: none;
    transition: all 0.25s ease;
    background: #fafafa;
}

.vs-wallet-form-group input:focus {
    border-color: #6366f1;
    background: #fff;
    box-shadow: 0 0 0 4px rgba(99,102,241,0.1);
}

/* Button */
.vs-wallet-withdraw-btn {
    width: 100%;
    padding: 14px;
    border: none;
    border-radius: 12px;
    background: linear-gradient(135deg, #6366f1, #4f46e5);
    color: #fff;
    font-weight: 600;
    font-size: 15px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    box-shadow: 0 10px 20px rgba(99,102,241,0.25);
}

.vs-wallet-withdraw-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 14px 30px rgba(99,102,241,0.35);
}

.vs-wallet-withdraw-btn:active {
    transform: scale(0.98);
}

/* Disabled */
.vs-wallet-withdraw-btn:disabled {
    background: #94a3b8 !important;
    cursor: not-allowed;
    box-shadow: none;
}

/* Error box */
.vs-wallet-withdraw-error {
    margin-top: 20px;
    padding: 14px;
    background: #fef2f2;
    border: 1px solid #fecaca;
    border-radius: 12px;
    color: #dc2626;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 10px;
}

/* Limits text */
.vs-wallet-withdraw-header strong {
    color: #111827;
}

/* Responsive */
@media (max-width: 768px) {
    .vs-wallet-withdraw-box {
        padding: 18px;
    }

    .vs-wallet-withdraw-btn {
        font-size: 14px;
    }
}
        </style>

        <script>
        jQuery(document).ready(function($) {
            $('#vs-withdraw-request-form').on('submit', function(e) {
                e.preventDefault();

                const $form = $(this);
                const $btn = $('#vs-withdraw-submit-btn');
                const $loader = $btn.find('.vs-btn-loader');
                const $text = $btn.find('.vs-btn-text');

                // Confirmation
                if (!confirm('<?php echo esc_js(__('Are you sure you want to submit this withdrawal request?', 'vendor-space')); ?>')) {
                    return;
                }

                $btn.prop('disabled', true).css('opacity', '0.7');
                $loader.show();
                $text.hide();

                $.ajax({
                    url: '<?php echo admin_url('admin-ajax.php'); ?>',
                    type: 'POST',
                    data: $form.serialize() + '&action=vs_handle_withdraw_ajax',
                    success: function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: '<?php echo esc_js(__('Success!', 'vendor-space')); ?>',
                                text: response.data.message,
                                confirmButtonColor: '#3085d6',
                            }).then(() => {
                                window.location.reload();
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: '<?php echo esc_js(__('Error!', 'vendor-space')); ?>',
                                text: response.data.message || '<?php echo esc_js(__('Something went wrong.', 'vendor-space')); ?>',
                                confirmButtonColor: '#d33',
                            });
                        }
                    },
                    error: function() {
                        Swal.fire({
                            icon: 'error',
                            title: '<?php echo esc_js(__('Error!', 'vendor-space')); ?>',
                            text: '<?php echo esc_js(__('Network error. Please try again.', 'vendor-space')); ?>',
                        });
                    },
                    complete: function() {
                        $btn.prop('disabled', false).css('opacity', '1');
                        $loader.hide();
                        $text.show();
                    }
                });
            });
        });
        </script>
</div>
        
        <?php

        return ob_get_clean();
    }
}