<?php
if (!defined('ABSPATH')) exit;

/**
 * Add "Applications" sub-tab inside Vendors tab
 */
add_action('stakmv_auctions_render_tab_vendors', 'stakmv_render_vendor_applications_section', 5);

function stakmv_render_vendor_applications_section() {

    if (!current_user_can('manage_woocommerce')) {
        return;
    }

    ?>
    <hr>
    <h2>Vendor Applications</h2>
    <p>Users who have applied to become vendors.</p>

    <?php stakmv_render_vendor_applications_table(); ?>
    <?php
}
function stakmv_render_vendor_applications_table() {

    // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Admin application listing requires vendor-application meta lookup.
    $users = get_users([
        'meta_key' => '_stakmv_vendor_application',
    ]);
    // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key

    if (empty($users)) {
        echo '<p>No vendor applications found.</p>';
        return;
    }
    ?>

    <table class="widefat striped">
        <thead>
            <tr>
                <th>User</th>
                <th>Email</th>
                <th>Status</th>
                <th>Applied</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>

        <?php foreach ($users as $user):
            $app = get_user_meta($user->ID, '_stakmv_vendor_application', true);
            if (!$app) continue;
        ?>
            <tr>
                <td><?php echo esc_html($user->user_login); ?></td>
                <td><?php echo esc_html($user->user_email); ?></td>
                <td><?php echo esc_html($app['status']); ?></td>
                <td><?php echo !empty($app['applied_at'])
    ? esc_html($app['applied_at'])
    : '—';
 ?></td>
                <td>
                    <?php if ($app['status'] === 'pending'): ?>
                        <a class="button button-primary"
                           href="<?php echo esc_url( wp_nonce_url(
                               admin_url('admin-post.php?action=stakmv_approve_vendor&user_id=' . $user->ID),
                               'stakmv_approve_vendor_' . $user->ID
                           ) ); ?>">
                           Approve
                        </a>

                        <a class="button"
                           href="<?php echo esc_url( wp_nonce_url(
                               admin_url('admin-post.php?action=stakmv_reject_vendor&user_id=' . $user->ID),
                               'stakmv_reject_vendor_' . $user->ID
                           ) ); ?>">
                           Reject
                        </a>
                    <?php else: ?>
                        —
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>

        </tbody>
    </table>
    <?php
}

/**
 * ================================
 * Escrow admin (Free baseline)
 * - Render pending escrows table under the Vendors tab
 * - Allow admins to Approve or Refund escrows manually
 * ================================
 */

add_action('stakmv_auctions_render_tab_vendors', 'stakmv_render_escrow_section', 15);

function stakmv_render_escrow_section() {

    if (!current_user_can('manage_woocommerce')) {
        return;
    }

    // Process approve/refund actions submitted by admin
    if (isset($_POST['stakmv_approve_escrow']) || isset($_POST['stakmv_refund_escrow'])) {

        $order_id = isset($_POST['escrow_order_id']) ? intval($_POST['escrow_order_id']) : 0;

        if ($order_id <= 0) {
            echo '<div class="notice notice-error"><p>Invalid escrow id.</p></div>';
            return;
        }

        if (isset($_POST['stakmv_approve_escrow'])) {
            if (!check_admin_referer('stakmv_approve_escrow_' . $order_id, 'stakmv_approve_escrow_nonce')) {
                wp_die('Security check failed');
            }

            $result = stakmv_approve_escrow($order_id);
            if (is_wp_error($result)) {
                echo '<div class="notice notice-error"><p>' . esc_html($result->get_error_message()) . '</p></div>';
            } else {
                echo '<div class="notice notice-success"><p>Escrow approved and vendor credited (if wallet is active).</p></div>';
                // Redirect to avoid resubmission
                wp_safe_redirect(add_query_arg('tab', 'vendors', admin_url('admin.php?page=stakmv-auctions')));
                exit;
            }
        }

        if (isset($_POST['stakmv_refund_escrow'])) {
            if (!check_admin_referer('stakmv_refund_escrow_' . $order_id, 'stakmv_refund_escrow_nonce')) {
                wp_die('Security check failed');
            }

            $result = stakmv_refund_escrow($order_id);
            if (is_wp_error($result)) {
                echo '<div class="notice notice-error"><p>' . esc_html($result->get_error_message()) . '</p></div>';
            } else {
                echo '<div class="notice notice-success"><p>Escrow marked as refunded.</p></div>';
                wp_safe_redirect(add_query_arg('tab', 'vendors', admin_url('admin.php?page=stakmv-auctions')));
                exit;
            }
        }
    }

    // Render pending escrows table
    $orders = stakmv_get_pending_escrows();

    ?>
    <hr>
    <h2>Pending Escrows</h2>
    <p>Escrows from auction orders awaiting manual approval.</p>

    <?php if (empty($orders)) : ?>

        <p>No pending escrows found.</p>

    <?php else : ?>

        <form method="post">
            <table class="widefat striped">
                <thead>
                    <tr>
                        <th>Order</th>
                        <th>Auction</th>
                        <th>Vendor</th>
                        <th>Amount</th>
                        <th>Created</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $order) :
                        $order_id   = $order->get_id();
                        $auction_id = $order->get_meta('_stakmv_auction_id');
                        $vendor_id  = get_post_meta($order_id, '_stakmv_escrow_vendor', true);
                        $amount     = get_post_meta($order_id, '_stakmv_escrow_amount', true);
                        $created    = get_post_meta($order_id, '_stakmv_escrow_created_at', true);
                    ?>
                        <tr>
                            <td><a href="<?php echo esc_url(admin_url('post.php?post=' . $order_id . '&action=edit')); ?>"><?php echo esc_html('#' . $order_id); ?></a></td>
                            <td>
                                <?php if ($auction_id) : ?>
                                    <a href="<?php echo esc_url(get_permalink($auction_id)); ?>"><?php echo esc_html(get_the_title($auction_id)); ?></a>
                                <?php else : ?>
                                    —
                                <?php endif; ?>
                            </td>
                            <td><?php echo esc_html($vendor_id ? get_the_author_meta('display_name', $vendor_id) : '—'); ?></td>
                            <td><?php echo wp_kses_post( wc_price($amount) ); ?></td>
                            <td><?php echo esc_html($created); ?></td>
                            <td>
                                <input type="hidden" name="escrow_order_id" value="<?php echo esc_attr($order_id); ?>">
                                <?php wp_nonce_field('stakmv_approve_escrow_' . $order_id, 'stakmv_approve_escrow_nonce'); ?>
                                <?php wp_nonce_field('stakmv_refund_escrow_' . $order_id, 'stakmv_refund_escrow_nonce'); ?>

                                <button type="submit" name="stakmv_approve_escrow" class="button button-primary wcmv-mr-8">
                                    Approve & Credit Vendor
                                </button>

                                <button type="submit" name="stakmv_refund_escrow" class="button">
                                    Mark as Refunded
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </form>

    <?php endif;
}
