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

function stakmv_admin_management_url($sub = 'vendors') {
    return add_query_arg(
        array(
            'page'                          => 'stakmv-auctions',
            'tab'                           => 'management',
            'sub'                           => sanitize_key((string) $sub),
            'stakmv_management_sub_nonce'   => wp_create_nonce('stakmv_management_sub'),
        ),
        admin_url('admin.php')
    );
}

/**
 * Admin Management Tab (FREE)
 * Provides the free plugin's admin management capabilities inside wp-admin.
 * Sub-tabs: Vendors, Users, Products, Escrows, Disputes
 */

/**
 * Handle actions (vendors/users/products/escrows/disputes)
 */
add_action('admin_init', function () {

    $page = sanitize_key((string) filter_input(INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
    if ('stakmv-auctions' !== $page) {
        return;
    }
    if (!current_user_can('manage_woocommerce')) {
        return;
    }

    // Vendors
    if (isset($_POST['stakmv_admin_vendor_action']) && check_admin_referer('stakmv_admin_management', 'stakmv_admin_management_nonce')) {
        $raw     = sanitize_text_field(wp_unslash($_POST['stakmv_admin_vendor_action']));
        $parts   = explode(':', $raw);
        $action  = sanitize_key($parts[0] ?? '');
        $user_id = isset($parts[1]) ? intval($parts[1]) : (isset($_POST['user_id']) ? intval($_POST['user_id']) : 0);
        if ($user_id > 0) {
            if ($action === 'revoke') {
                $user = new WP_User($user_id);
                if ($user instanceof WP_User) {
                    $user->remove_role('stakmv_vendor');
                    update_user_meta($user_id, '_stakmv_vendor_application', array(
                        'status'     => 'revoked',
                        'revoked_at' => current_time('mysql'),
                    ));
                }
            } elseif ($action === 'suspend') {
                update_user_meta($user_id, 'stakmv_vendor_suspended', 'yes');
            } elseif ($action === 'unsuspend') {
                update_user_meta($user_id, 'stakmv_vendor_suspended', 'no');
            }
        }
        wp_safe_redirect(stakmv_admin_management_url('vendors'));
        exit;
    }

    // Users
    if (isset($_POST['stakmv_admin_user_action']) && check_admin_referer('stakmv_admin_management', 'stakmv_admin_management_nonce')) {
        $raw     = sanitize_text_field(wp_unslash($_POST['stakmv_admin_user_action']));
        $parts   = explode(':', $raw);
        $action  = sanitize_key($parts[0] ?? '');
        $user_id = isset($parts[1]) ? intval($parts[1]) : (isset($_POST['user_id']) ? intval($_POST['user_id']) : 0);
        if ($user_id > 0) {
            if ($action === 'make_vendor') {
                $user = new WP_User((int) $user_id);
                if ($user instanceof WP_User && $user->ID) {
                    // Grant vendor role without replacing existing roles (prevents admin lockout).
                    stakmv_grant_vendor_role($user_id);
                }
                update_user_meta($user_id, '_stakmv_vendor_application', array(
                    'status'      => 'approved',
                    'approved_at' => current_time('mysql'),
                    'auto'        => 'manual_admin',
                ));
            } elseif ($action === 'suspend') {
                update_user_meta($user_id, 'stakmv_user_suspended', 'yes');
            } elseif ($action === 'unsuspend') {
                update_user_meta($user_id, 'stakmv_user_suspended', 'no');
            }
        }
        wp_safe_redirect(stakmv_admin_management_url('users'));
        exit;
    }

    // Products
    if (isset($_POST['stakmv_admin_listing_action']) && check_admin_referer('stakmv_admin_management', 'stakmv_admin_management_nonce')) {
        $raw     = sanitize_text_field(wp_unslash($_POST['stakmv_admin_listing_action']));
        $parts   = explode(':', $raw);
        $action  = sanitize_key($parts[0] ?? '');
        $post_id = isset($parts[1]) ? intval($parts[1]) : (isset($_POST['post_id']) ? intval($_POST['post_id']) : 0);
        if ($post_id > 0 && get_post_type($post_id) === 'product') {
            if ($action === 'delete') {
                wp_trash_post($post_id);
            } elseif ($action === 'extend') {
                $hours = isset($_POST['extend_hours']) ? max(1, intval($_POST['extend_hours'])) : 24;
                $raw   = get_post_meta($post_id, '_stakmv_auction_end_time', true);
                $end   = is_numeric($raw) ? intval($raw) : ($raw ? strtotime($raw) : time());
                $new   = $end + ($hours * HOUR_IN_SECONDS);
                update_post_meta($post_id, '_stakmv_auction_end_time', gmdate('Y-m-d H:i:s', $new));
                update_post_meta($post_id, '_stakmv_auction_status', 'active');
            } elseif ($action === 'relist') {
                $days = function_exists('stakmv_get_relist_duration_days') ? stakmv_get_relist_duration_days() : 7;
                $new  = time() + ($days * DAY_IN_SECONDS);
                update_post_meta($post_id, '_stakmv_auction_end_time', gmdate('Y-m-d H:i:s', $new));
                update_post_meta($post_id, '_stakmv_auction_status', 'active');
                delete_post_meta($post_id, '_stakmv_auction_extensions_used');
            }
        }
        wp_safe_redirect(stakmv_admin_management_url('products'));
        exit;
    }

    // Escrows
    if (isset($_POST['stakmv_admin_escrow_action']) && check_admin_referer('stakmv_admin_management', 'stakmv_admin_management_nonce')) {
        $raw      = sanitize_text_field(wp_unslash($_POST['stakmv_admin_escrow_action']));
        $parts    = explode(':', $raw);
        $action   = sanitize_key($parts[0] ?? '');
        $order_id = isset($parts[1]) ? intval($parts[1]) : (isset($_POST['escrow_order_id']) ? intval($_POST['escrow_order_id']) : 0);
        if ($order_id > 0) {
            if ($action === 'approve' && function_exists('stakmv_approve_escrow')) {
                stakmv_approve_escrow($order_id);
            } elseif ($action === 'refund' && function_exists('stakmv_refund_escrow')) {
                stakmv_refund_escrow($order_id);
            }
        }
        wp_safe_redirect(stakmv_admin_management_url('escrows'));
        exit;
    }

    // Disputes/tickets can be added by extensions; the free plugin does not process them.
});

/**
 * Render Management tab with sub-tabs
 */
add_action('stakmv_auctions_render_tab_management', function () {

    if (!current_user_can('manage_woocommerce')) {
        echo '<p>Insufficient permissions.</p>';
        return;
    }

    $has_disputes_tab = false !== has_action('stakmv_admin_management_disputes');
    $valid_subs = array('vendors', 'users', 'products', 'escrows');
    if ($has_disputes_tab) {
        $valid_subs[] = 'disputes';
    }

    $sub = 'vendors';
    $sub_nonce = filter_input(INPUT_GET, 'stakmv_management_sub_nonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    if ($sub_nonce && wp_verify_nonce(sanitize_text_field((string) $sub_nonce), 'stakmv_management_sub')) {
        $sub_raw = filter_input(INPUT_GET, 'sub', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        $sub = sanitize_key((string) ($sub_raw ?: 'vendors'));
    }
    if (!in_array($sub, $valid_subs, true)) {
        $sub = 'vendors';
    }

    ?>
    <h2>Management</h2>

    <h3 class="nav-tab-wrapper wcmv-mt-12">
        <a href="<?php echo esc_url(stakmv_admin_management_url('vendors')); ?>" class="nav-tab <?php echo $sub==='vendors'?'nav-tab-active':''; ?>">Vendors</a>
        <a href="<?php echo esc_url(stakmv_admin_management_url('users')); ?>" class="nav-tab <?php echo $sub==='users'?'nav-tab-active':''; ?>">Users</a>
        <a href="<?php echo esc_url(stakmv_admin_management_url('products')); ?>" class="nav-tab <?php echo $sub==='products'?'nav-tab-active':''; ?>">Products</a>
        <a href="<?php echo esc_url(stakmv_admin_management_url('escrows')); ?>" class="nav-tab <?php echo $sub==='escrows'?'nav-tab-active':''; ?>">Escrows</a>
        <?php if ($has_disputes_tab) : ?>
            <a href="<?php echo esc_url(stakmv_admin_management_url('disputes')); ?>" class="nav-tab <?php echo $sub==='disputes'?'nav-tab-active':''; ?>">Disputes</a>
        <?php endif; ?>
    </h3>

    <form method="post" class="wcmv-mt-12">
        <?php wp_nonce_field('stakmv_admin_management', 'stakmv_admin_management_nonce'); ?>

        <?php if ($sub === 'vendors') : ?>

            <?php $vendors = get_users(array('role__in'=>array('stakmv_vendor'))); ?>
            <?php if (empty($vendors)) : ?>
                <p>No vendors found.</p>
            <?php else : ?>
                <table class="widefat striped">
                    <thead><tr><th>User</th><th>Email</th><th>Status</th><th class="wcmv-text-right">Actions</th></tr></thead>
                    <tbody>
                    <?php foreach ($vendors as $v) :
                        $suspended = get_user_meta($v->ID, 'stakmv_vendor_suspended', true) === 'yes';
                    ?>
                        <tr>
                            <td><?php echo esc_html($v->display_name); ?></td>
                            <td><?php echo esc_html($v->user_email); ?></td>
                            <td><?php echo $suspended ? 'Suspended' : 'Active'; ?></td>
                            <td class="wcmv-text-right">
                                <button class="button" name="stakmv_admin_vendor_action" value="<?php echo esc_attr(($suspended ? 'unsuspend':'suspend') . ':' . (int) $v->ID); ?>">
                                    <?php echo $suspended ? 'Unsuspend' : 'Suspend'; ?>
                                </button>
                                <button class="button wcmv-js-confirm" data-confirm="Revoke vendor role?" name="stakmv_admin_vendor_action" value="<?php echo esc_attr('revoke:' . (int) $v->ID); ?>">Revoke</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>

        <?php elseif ($sub === 'users') : ?>

            <?php
            $users = get_users(array(
                'number'      => 20,
                'orderby'     => 'registered',
                'order'       => 'DESC',
                'role__not_in'=> array('administrator'),
            ));
            ?>
            <table class="widefat striped">
                <thead><tr><th>User</th><th>Email</th><th>Roles</th><th class="wcmv-text-right">Actions</th></tr></thead>
                <tbody>
                <?php foreach ($users as $u) :
                    if (in_array('administrator', (array) $u->roles, true)) {
                        continue;
                    }
                    $is_vendor = in_array('stakmv_vendor',(array)$u->roles,true);
                    $suspended = get_user_meta($u->ID, 'stakmv_user_suspended', true) === 'yes';
                ?>
                    <tr>
                        <td><?php echo esc_html($u->display_name); ?></td>
                        <td><?php echo esc_html($u->user_email); ?></td>
                        <td><?php echo esc_html(implode(', ', (array) $u->roles)); ?></td>
                        <td class="wcmv-text-right">
                            <?php if (!$is_vendor) : ?>
                                <button class="button button-primary" name="stakmv_admin_user_action" value="<?php echo esc_attr('make_vendor:' . (int) $u->ID); ?>">Make Vendor</button>
                            <?php endif; ?>
                            <button class="button" name="stakmv_admin_user_action" value="<?php echo esc_attr(($suspended?'unsuspend':'suspend') . ':' . (int) $u->ID); ?>">
                                <?php echo $suspended ? 'Unsuspend' : 'Suspend'; ?>
                            </button>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>

        <?php elseif ($sub === 'products') : ?>

            <?php
            // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Admin listings tab intentionally filters auction products by meta.
            $args = array(
                'post_type'      => 'product',
                'posts_per_page' => 20,
                'orderby'        => 'date',
                'order'          => 'DESC',
                'meta_query'     => array(
                    array(
                        'key'     => '_stakmv_auction_start_price',
                        'compare' => 'EXISTS',
                    ),
                ),
            );
            // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_query
            $listings = get_posts($args);
            ?>
            <?php if (empty($listings)) : ?>
                <p>No products found.</p>
            <?php else : ?>
                <table class="widefat striped">
                    <thead><tr><th>Title</th><th>Vendor</th><th>Status</th><th>Ends</th><th class="wcmv-text-right">Actions</th></tr></thead>
                    <tbody>
                    <?php foreach ($listings as $post) :
                        $vendor_id = (int) get_post_field('post_author', $post->ID);
                        $status = get_post_meta($post->ID, '_stakmv_auction_status', true) ?: 'active';
                        $end_raw = get_post_meta($post->ID, '_stakmv_auction_end_time', true);
                        $end_disp = $end_raw ? date_i18n('d M Y H:i', is_numeric($end_raw) ? (int) $end_raw : strtotime($end_raw)) : '—';
                    ?>
                        <tr>
                            <td><a href="<?php echo esc_url(get_permalink($post->ID)); ?>"><?php echo esc_html(get_the_title($post->ID)); ?></a></td>
                            <td><?php echo esc_html(get_the_author_meta('display_name', $vendor_id)); ?></td>
                            <td><?php echo esc_html(ucfirst($status)); ?></td>
                            <td><?php echo esc_html($end_disp); ?></td>
                            <td class="wcmv-text-right">
                                <input type="number" name="extend_hours" min="1" value="24" class="wcmv-w-80">
                                <button class="button" name="stakmv_admin_listing_action" value="<?php echo esc_attr('extend:' . (int) $post->ID); ?>">Extend</button>
                                <?php if ($status !== 'active') : ?>
                                    <button class="button" name="stakmv_admin_listing_action" value="<?php echo esc_attr('relist:' . (int) $post->ID); ?>">Relist</button>
                                <?php endif; ?>
                                <button class="button wcmv-js-confirm" data-confirm="Move to trash?" name="stakmv_admin_listing_action" value="<?php echo esc_attr('delete:' . (int) $post->ID); ?>">Delete</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>

        <?php elseif ($sub === 'escrows') : ?>

            <?php if (!function_exists('stakmv_get_pending_escrows')) : ?>
                <p>Escrow module not available.</p>
            <?php else : ?>
                <?php $orders = stakmv_get_pending_escrows(); ?>
                <?php if (empty($orders)) : ?>
                    <p>No pending escrows.</p>
                <?php else : ?>
                    <table class="widefat striped">
                        <thead><tr><th>Order</th><th>Auction</th><th>Vendor</th><th>Amount</th><th>Created</th><th class="wcmv-text-right">Actions</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 echo $auction_id ? esc_html( get_the_title($auction_id) ) : '—'; ?></td>
                                <td><?php echo $vendor_id ? esc_html( get_the_author_meta('display_name', $vendor_id) ) : '—'; ?></td>
                                <td><?php echo function_exists('wc_price') ? wp_kses_post(wc_price($amount)) : esc_html(number_format_i18n((float)$amount,2)); ?></td>
                                <td><?php echo esc_html($created ?: ''); ?></td>
                                <td class="wcmv-text-right">
                                    <button class="button button-primary" name="stakmv_admin_escrow_action" value="<?php echo esc_attr('approve:' . (int) $order_id); ?>">Approve & Credit</button>
                                    <button class="button" name="stakmv_admin_escrow_action" value="<?php echo esc_attr('refund:' . (int) $order_id); ?>">Refund</button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            <?php endif; ?>

        <?php elseif ($sub === 'disputes' && $has_disputes_tab) : ?>

            <?php do_action('stakmv_admin_management_disputes'); ?>

        <?php endif; ?>
    </form>
    <?php
});
