<?php
add_action('admin_menu', 'vs_register_withdrawal_menu');

function vs_register_withdrawal_menu() {
    add_menu_page(
        __('Withdrawal Requests', 'vs-plugin'),
        __('Vendor Withdrawals', 'vs-plugin'),
        'manage_options',
        'vs-withdrawals',
        'vs_render_admin_page',
        'dashicons-money-alt',
        6
    );
}

function vs_render_admin_page() {

    global $wpdb;
    $table_name = $wpdb->prefix . 'vs_withdrawals';

    if (isset($_GET['action']) && $_GET['action'] == 'paid' && isset($_GET['id'])) {

        check_admin_referer('pay_withdrawal_' . $_GET['id']);

        $withdrawal_id = intval($_GET['id']);
        $withdrawal = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE id = %d", $withdrawal_id));

        if ($withdrawal && $withdrawal->status === 'pending') {
            $vendor_id = $withdrawal->vendor_id;
            $amount = (float) $withdrawal->amount;

            // Get current balance
            $available = (float) get_user_meta($vendor_id, '_vs_wallet_available', true);
            $withdrawn = (float) get_user_meta($vendor_id, '_vs_wallet_withdrawn', true);

            if ($amount > $available) {

    echo '<div class="error"><p>' .
         __('Insufficient vendor balance.', 'vs-plugin') .
         '</p></div>';

    return;
}

update_user_meta(
    $vendor_id,
    '_vs_wallet_available',
    max(0, $available - $amount)
);

            update_user_meta(
                $vendor_id,
                '_vs_wallet_withdrawn',
                $withdrawn + $amount
            );

            // Update database status
            $wpdb->update(
                $table_name,
                ['status' => 'paid'],
                ['id' => $withdrawal_id]
            );

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

            echo '<div class="updated"><p>' . __('Payment recorded and vendor balance updated.', 'vs-plugin') . '</p></div>';
        }
    }

    $status_filter = isset($_GET['status_filter']) ? sanitize_text_field($_GET['status_filter']) : '';

    $query = "SELECT * FROM $table_name";
    if (!empty($status_filter)) {
        $query .= $wpdb->prepare(" WHERE status = %s", $status_filter);
    }
    $query .= " ORDER BY created_at DESC";
    
    $requests = $wpdb->get_results($query);

    echo '<div class="wrap"><h1>' . __('Withdrawal Management (IBAN)', 'vs-plugin') . '</h1>';

    // Filter Form
    echo '<form method="get" style="margin-bottom: 20px; background: #fff; padding: 15px; border: 1px solid #ccd0d4; border-radius: 4px;">';
    echo '<input type="hidden" name="page" value="vs-withdrawals">';
    echo '<label for="status_filter" style="margin-right: 10px; font-weight: 600;">' . __('Filter by Status:', 'vs-plugin') . '</label>';
    echo '<select name="status_filter" id="status_filter" style="margin-right: 10px;">';
    echo '<option value="">' . __('All Statuses', 'vs-plugin') . '</option>';
    echo '<option value="pending" ' . selected($status_filter, 'pending', false) . '>' . __('Pending', 'vs-plugin') . '</option>';
    echo '<option value="paid" ' . selected($status_filter, 'paid', false) . '>' . __('Paid', 'vs-plugin') . '</option>';
    echo '</select>';
    echo '<button type="submit" class="button">' . __('Filter', 'vs-plugin') . '</button>';
    if (!empty($status_filter)) {
        echo ' <a href="' . admin_url('admin.php?page=vs-withdrawals') . '" class="button button-secondary">' . __('Clear', 'vs-plugin') . '</a>';
    }
    echo '</form>';

    echo '<table class="wp-list-table widefat fixed striped">';

    echo '<thead>
            <tr>
                <th>ID</th>
                <th>' . __('Vendor', 'vs-plugin') . '</th>
                <th>IBAN</th>
                <th>' . __('Amount', 'vs-plugin') . '</th>
                <th>' . __('Status', 'vs-plugin') . '</th>
                <th>' . __('Date', 'vs-plugin') . '</th>
                <th>' . __('Action', 'vs-plugin') . '</th>
            </tr>
          </thead>';

    echo '<tbody>';

    foreach ($requests as $req) {

        $vendor = get_userdata($req->vendor_id);
        $iban = get_user_meta($req->vendor_id, 'vendor_iban', true);

        $pay_url = wp_nonce_url(
            admin_url('admin.php?page=vs-withdrawals&action=paid&id=' . $req->id),
            'pay_withdrawal_' . $req->id
        );

        echo '<tr>';
        echo "<td>{$req->id}</td>";
        echo "<td>" . ($vendor ? $vendor->display_name : __('Unknown', 'vs-plugin')) . "</td>";
        echo "<td><code>{$iban}</code></td>";
        echo "<td>{$req->amount} $</td>";
        echo "<td>" . strtoupper($req->status) . "</td>";
        echo "<td>{$req->created_at}</td>";

        echo "<td>";

        if ($req->status == 'pending') {

            echo "<a href='{$pay_url}' class='button button-primary'>" .
                 __('Mark as Paid', 'vs-plugin') .
                 "</a>";

        } else {

            echo "<span style='color:green;'>✔ " . __('Paid', 'vs-plugin') . "</span>";
        }

        echo "</td>";
        echo '</tr>';
    }

    echo '</tbody></table></div>';
}