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

/**
 * Required for frontend media uploads
 */
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/image.php';

add_action('init', 'stakmv_save_listing');

function stakmv_listing_fail($message, $is_ajax = false) {
    $request_key = isset($GLOBALS['stakmv_listing_request_key']) ? (string) $GLOBALS['stakmv_listing_request_key'] : '';
    if ($request_key !== '') {
        delete_transient($request_key);
    }

    $created_new_listing = !empty($GLOBALS['stakmv_listing_new_created']);
    $new_listing_id = isset($GLOBALS['stakmv_listing_new_product_id']) ? (int) $GLOBALS['stakmv_listing_new_product_id'] : 0;
    if ($created_new_listing && $new_listing_id > 0) {
        wp_trash_post($new_listing_id);
        $GLOBALS['stakmv_listing_new_product_id'] = 0;
    }

    if ($is_ajax) {
        wp_send_json_error(array('message' => $message));
    }
    wp_die(esc_html((string) $message));
}

function stakmv_listing_finish($redirect_url, $is_ajax = false) {
    if ($is_ajax) {
        wp_send_json_success(array('redirect' => $redirect_url));
    }
    wp_safe_redirect($redirect_url);
    exit;
}

/**
 * Sanitize listing payload before passing it to action hooks.
 *
 * @param mixed $value Raw value.
 * @return mixed
 */
function stakmv_sanitize_listing_hook_payload($value) {
    if (is_array($value)) {
        $sanitized = array();
        foreach ($value as $key => $child) {
            $clean_key = is_string($key) ? sanitize_key($key) : $key;
            $sanitized[$clean_key] = stakmv_sanitize_listing_hook_payload($child);
        }
        return $sanitized;
    }

    if (is_bool($value) || is_int($value) || is_float($value) || is_null($value)) {
        return $value;
    }

    return sanitize_text_field((string) $value);
}

function stakmv_save_listing() {
    $GLOBALS['stakmv_listing_request_key'] = '';
    $GLOBALS['stakmv_listing_new_created'] = false;
    $GLOBALS['stakmv_listing_new_product_id'] = 0;

    // Only handle create-listing form POSTs.
    $request_method = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $nonce_raw = filter_input(INPUT_POST, 'stakmv_nonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    if ($request_method !== 'POST' || !$nonce_raw) {
        return;
    }

    $action_raw = filter_input(INPUT_POST, 'action', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $is_ajax = wp_doing_ajax() && sanitize_key((string) $action_raw) === 'stakmv_save_listing';

    if (
        !wp_verify_nonce(
            sanitize_text_field((string) $nonce_raw),
            'stakmv_create_listing'
        )
    ) {
        stakmv_listing_fail('Security check failed', $is_ajax);
    }

    // Nonce is verified before reading the full submitted payload or uploaded files.
    // phpcs:disable WordPress.Security.NonceVerification.Missing -- stakmv_nonce is verified above before reading $_POST.
    $post_data = isset($_POST) && is_array($_POST)
        ? map_deep(wp_unslash($_POST), 'sanitize_text_field')
        : array();
    // phpcs:enable WordPress.Security.NonceVerification.Missing

    if (!is_user_logged_in()) {
        stakmv_listing_fail('You must be logged in', $is_ajax);
    }

    $user_id = get_current_user_id();
    $can_manage_listings = false;
    if (current_user_can('manage_woocommerce') || current_user_can('edit_products')) {
        $can_manage_listings = true;
    } elseif (function_exists('stakmv_is_vendor') && stakmv_is_vendor($user_id)) {
        $can_manage_listings = true;
    }
    if (!$can_manage_listings) {
        stakmv_listing_fail('Insufficient permissions', $is_ajax);
    }

    $edit_id = isset($post_data['edit_id']) ? (int) $post_data['edit_id'] : 0;
    $max_images = 12;
    $is_delete_submit = array_key_exists('stakmv_delete_listing', $post_data);
    $is_create_submit = array_key_exists('stakmv_create_listing', $post_data) || !$is_delete_submit;
    $request_token = isset($post_data['stakmv_request_token']) ? sanitize_key((string) $post_data['stakmv_request_token']) : '';
    $request_key = '';

    // Guard against rapid multi-tap duplicate creates on mobile.
    if ($is_create_submit && $edit_id === 0) {
        if ($request_token === '') {
            $request_token = wp_generate_password(20, false, false);
        }

        $request_key = 'stakmv_create_req_' . $user_id . '_' . $request_token;
        $GLOBALS['stakmv_listing_request_key'] = $request_key;
        $request_state = get_transient($request_key);

        if (is_array($request_state)) {
            $request_status = isset($request_state['status']) ? sanitize_key((string) $request_state['status']) : '';
            $request_time = isset($request_state['created_at']) ? (int) $request_state['created_at'] : 0;
            $request_age = ($request_time > 0) ? (time() - $request_time) : PHP_INT_MAX;
            $recent_window = 60; // Seconds: suppress accidental double-submit, but avoid stale cached-form redirects.

            $existing_product_id = isset($request_state['product_id']) ? (int) $request_state['product_id'] : 0;
            if ($existing_product_id > 0 && $request_age <= $recent_window) {
                stakmv_listing_finish(add_query_arg('updated', 1, get_permalink($existing_product_id)), $is_ajax);
            }

            if ($request_status === 'processing' && $request_age <= $recent_window) {
                $pending_redirect = add_query_arg('stakmv_create_pending', 1, stakmv_get_create_listing_url());
                stakmv_listing_finish($pending_redirect, $is_ajax);
            }
        }

        set_transient(
            $request_key,
            array(
                'status'     => 'processing',
                'product_id' => 0,
                'created_at' => time(),
            ),
            5 * MINUTE_IN_SECONDS
        );
    }

    // =============================
    // LOAD OR CREATE PRODUCT
    // =============================
    if ($edit_id) {

        $product = wc_get_product($edit_id);

        if (!$product || (int) get_post_field('post_author', $edit_id) !== $user_id) {
            stakmv_listing_fail('Unauthorized edit', $is_ajax);
        }

        // Use real bid count to avoid stale lock meta blocking valid edits.
        $bid_count = 0;
        if (function_exists('stakmv_get_bid_count')) {
            $bid_count = (int) stakmv_get_bid_count($edit_id);
        } else {
            $bid_count = (int) get_post_meta($edit_id, '_stakmv_auction_bid_count', true);
        }
        $has_bids_lock = ($bid_count > 0);

        // Handle delete request (edit mode only).
        if ($is_delete_submit) {
            if ($has_bids_lock) {
                stakmv_listing_fail('This listing has bids and cannot be deleted.', $is_ajax);
            }

            wp_trash_post($edit_id);
            do_action('stakmv_listing_deleted', $edit_id, $user_id);
            $delete_redirect = add_query_arg(
                array(
                    'tab'     => 'inventory',
                    'inv_tab' => 'listings',
                    'deleted' => 1,
                    'ts'      => time(),
                ),
                stakmv_get_vendor_dashboard_url()
            );

            stakmv_listing_finish(
                $delete_redirect,
                $is_ajax
            );
        }

    } else {

        $product = new WC_Product_Simple();
        $product->set_status('publish');
        $product->set_catalog_visibility('visible');
        $product->set_manage_stock(false);
        $product->set_props(['author' => $user_id]);
        $has_bids_lock = false;
    }

    // If bids already exist, listing content is locked.
    if ($has_bids_lock) {
        $sanitized_payload = stakmv_sanitize_listing_hook_payload($post_data);
        do_action('stakmv_listing_save_locked', $edit_id, $sanitized_payload, $user_id);
        do_action('stakmv_listing_saved', $edit_id, $sanitized_payload, $user_id, $edit_id);

        stakmv_listing_finish(
            add_query_arg('updated', 1, get_permalink($edit_id)),
            $is_ajax
        );
    }

    // =============================
    // BASIC DATA
    // =============================
    // phpcs:disable WordPress.Security.NonceVerification.Missing -- stakmv_nonce is verified above before reading $_POST.
    $description_raw = isset($_POST['description'])
        ? wp_kses_post(wp_unslash((string) $_POST['description']))
        : '';
    // phpcs:enable WordPress.Security.NonceVerification.Missing
    $product->set_name(sanitize_text_field($post_data['title'] ?? ''));
    $product->set_description($description_raw);

    $quantity_is_provided = array_key_exists('quantity', $post_data);
    $quantity_value = $quantity_is_provided ? max(1, absint((string) $post_data['quantity'])) : 0;
    if (!$quantity_is_provided && $edit_id > 0) {
        $existing_quantity = $product->get_stock_quantity();
        if ($existing_quantity !== null && (int) $existing_quantity > 0) {
            $quantity_is_provided = true;
            $quantity_value = max(1, (int) $existing_quantity);
        }
    }
    if ($quantity_is_provided) {
        $product->set_manage_stock(true);
        $product->set_stock_quantity($quantity_value);
        $product->set_stock_status($quantity_value > 0 ? 'instock' : 'outofstock');
    }


$product_id = $product->save();
$GLOBALS['stakmv_listing_new_created'] = ($edit_id === 0);
$GLOBALS['stakmv_listing_new_product_id'] = (int) $product_id;

// Persist custom product type immediately so any later failure never leaves
// a newly-created listing as WooCommerce "simple".
wp_set_object_terms($product_id, 'auction', 'product_type');
// =============================
// PRICING & AUCTION META
// =============================
$auctions_enabled = function_exists('stakmv_auctions_enabled')
    ? stakmv_auctions_enabled()
    : (stakmv_get_option('enable_auctions', 'yes') === 'yes');

$listing_type = sanitize_text_field($post_data['listing_type'] ?? '');
if ($listing_type === '' && $edit_id) {
    $listing_type = sanitize_text_field((string) get_post_meta($edit_id, '_stakmv_auction_listing_type', true));
}
if (!in_array($listing_type, array('auction_only', 'buy_now_only', 'auction_buy_now'), true)) {
    $listing_type = 'auction_only';
}

if (!$auctions_enabled) {
    if ($edit_id > 0) {
        $existing_listing_type = sanitize_text_field((string) get_post_meta($edit_id, '_stakmv_auction_listing_type', true));
        $existing_is_auction = in_array($existing_listing_type, array('auction_only', 'auction_buy_now'), true);
        if (!$existing_is_auction) {
            $listing_type = 'buy_now_only';
        }
    } else {
        // New listings must stay buy-now only while auctions are disabled.
        $listing_type = 'buy_now_only';
    }
}

$buy_now = '';
$existing_buy_now = $edit_id ? get_post_meta($edit_id, '_stakmv_auction_buy_now_price', true) : '';
$is_buy_now_capable = in_array($listing_type, array('buy_now_only', 'auction_buy_now'), true);
$is_stakmv_auction_capable = in_array($listing_type, array('auction_only', 'auction_buy_now'), true);

// Start price
if (isset($post_data['start_price']) && !$has_bids_lock) {
    $start_price = wc_format_decimal($post_data['start_price']);
    update_post_meta($product_id, '_stakmv_auction_start_price', $start_price);
    update_post_meta($product_id, '_regular_price', $start_price);
    update_post_meta($product_id, '_price', $start_price);
}

// Buy Now: mode-aware persistence to avoid accidental emptying on edit.
if (!$is_buy_now_capable) {
    delete_post_meta($product_id, '_stakmv_auction_buy_now_price');
} else {
    $buy_now_raw = array_key_exists('buy_now_price', $post_data)
        ? trim((string) $post_data['buy_now_price'])
        : '';

    if ($buy_now_raw !== '') {
        $buy_now = wc_format_decimal($buy_now_raw);
        update_post_meta($product_id, '_stakmv_auction_buy_now_price', $buy_now);
    } elseif ($edit_id && $existing_buy_now !== '') {
        // Preserve existing value when edit submit posts an empty buy-now field.
        $buy_now = wc_format_decimal($existing_buy_now);
        update_post_meta($product_id, '_stakmv_auction_buy_now_price', $buy_now);
    } else {
        delete_post_meta($product_id, '_stakmv_auction_buy_now_price');
    }

    if ($listing_type === 'buy_now_only' && $buy_now !== '') {
        update_post_meta($product_id, '_regular_price', $buy_now);
        update_post_meta($product_id, '_price', $buy_now);
    }
}

// Free core does not own offers feature; Pro handles this meta via hooks.
delete_post_meta($product_id, '_stakmv_auction_accept_offers');

if ($listing_type === 'auction_buy_now' && !empty($buy_now)) {
    update_post_meta($product_id, '_price', $buy_now);
}

// Auction end time: allow clearing when field is empty.
if (array_key_exists('end_date', $post_data)) {
    $end_date_raw = trim((string) $post_data['end_date']);
    if ($end_date_raw === '') {
        delete_post_meta($product_id, '_stakmv_auction_end_time');
    } else {
        update_post_meta(
            $product_id,
            '_stakmv_auction_end_time',
            strtotime(sanitize_text_field($end_date_raw))
        );
    }
}
// =============================
// SALE MODE (USED BY BIDDING UI)
// =============================

$mode_map = [
    'auction_only'     => 'auction',
    'buy_now_only'     => 'buy_now',
    'auction_buy_now'  => 'both',
];

update_post_meta(
    $product_id,
    '_stakmv_auction_listing_type',
    $listing_type
);

update_post_meta(
    $product_id,
    '_stakmv_auction_sale_mode',
    $mode_map[$listing_type] ?? 'auction'
);

// =============================
// SHIPPING DATA
// =============================

$shipping_mode = sanitize_key((string) ($post_data['shipping_mode'] ?? ''));
if (!in_array($shipping_mode, array('calculated', 'flat', 'free', 'pickup_only'), true)) {
    stakmv_listing_fail('Please select a shipping type.', $is_ajax);
}
update_post_meta($product_id, '_stakmv_auction_shipping_mode', $shipping_mode);

$shipping_scope = sanitize_key((string) ($post_data['shipping_scope'] ?? 'international'));
if (!in_array($shipping_scope, array('international', 'domestic', 'selected'), true)) {
    $shipping_scope = 'international';
}

$shipping_allowed_countries = array();
$country_map = function_exists('WC') && WC()->countries ? WC()->countries->get_countries() : array();
$valid_country_codes = array_fill_keys(array_keys($country_map), true);

if (isset($post_data['shipping_countries']) && is_array($post_data['shipping_countries'])) {
    foreach ($post_data['shipping_countries'] as $country_code) {
        $country_code = strtoupper(sanitize_text_field((string) $country_code));
        if ($country_code !== '' && isset($valid_country_codes[$country_code])) {
            $shipping_allowed_countries[] = $country_code;
        }
    }
    $shipping_allowed_countries = array_values(array_unique($shipping_allowed_countries));
}

if ($shipping_mode === 'pickup_only') {
    delete_post_meta($product_id, '_stakmv_auction_shipping_scope');
    delete_post_meta($product_id, '_stakmv_auction_shipping_countries');
    delete_post_meta($product_id, '_stakmv_auction_shipping_excluded_countries');
} else {
    if ($shipping_scope === 'selected' && empty($shipping_allowed_countries)) {
        stakmv_listing_fail('Please select at least one allowed country.', $is_ajax);
    }
    update_post_meta($product_id, '_stakmv_auction_shipping_scope', $shipping_scope);
    update_post_meta($product_id, '_stakmv_auction_shipping_countries', $shipping_allowed_countries);
    delete_post_meta($product_id, '_stakmv_auction_shipping_excluded_countries');
}

// Persist physical dimensions directly via meta so we do not accidentally
// overwrite pricing props by re-saving a stale WC_Product object later.
update_post_meta($product_id, '_weight', wc_format_decimal($post_data['weight'] ?? ''));
update_post_meta($product_id, '_length', wc_format_decimal($post_data['length'] ?? ''));
update_post_meta($product_id, '_width', wc_format_decimal($post_data['width'] ?? ''));
update_post_meta($product_id, '_height', wc_format_decimal($post_data['height'] ?? ''));

// Save preferred shipping carriers (multi-select).
$carrier_options = array('USPS', 'UPS', 'FedEx', 'DHL');
$selected_carriers = array();
if (isset($post_data['shipping_carriers']) && is_array($post_data['shipping_carriers'])) {
    $raw_carriers = array_map('sanitize_text_field', $post_data['shipping_carriers']);
    foreach ($raw_carriers as $carrier) {
        if (in_array($carrier, $carrier_options, true)) {
            $selected_carriers[] = $carrier;
        }
    }
    $selected_carriers = array_values(array_unique($selected_carriers));
} else {
    $single_carrier = sanitize_text_field($post_data['shipping_carrier'] ?? '');
    if (in_array($single_carrier, $carrier_options, true)) {
        $selected_carriers[] = $single_carrier;
    }
}

if ($shipping_mode === 'calculated') {
    if (empty($selected_carriers)) {
        $selected_carriers = $carrier_options; // Default to all carriers.
    }
    update_post_meta($product_id, '_stakmv_auction_shipping_carriers', $selected_carriers);
    // Keep a primary carrier value for product display and rate fallback.
    update_post_meta($product_id, '_stakmv_auction_shipping_carrier', $selected_carriers[0]);
} elseif ($shipping_mode === 'pickup_only') {
    delete_post_meta($product_id, '_stakmv_auction_shipping_carriers');
    update_post_meta($product_id, '_stakmv_auction_shipping_carrier', 'Pickup Only');
} elseif ($shipping_mode === 'free') {
    delete_post_meta($product_id, '_stakmv_auction_shipping_carriers');
    update_post_meta($product_id, '_stakmv_auction_shipping_carrier', 'Free Shipping');
} else {
    delete_post_meta($product_id, '_stakmv_auction_shipping_carriers');
    update_post_meta($product_id, '_stakmv_auction_shipping_carrier', '');
}

// =============================
// SAVE CATEGORY
// =============================
if (!empty($post_data['product_cat'])) {
    $parent_category_id = (int) $post_data['product_cat'];
    $subcategory_id = isset($post_data['product_subcat']) ? (int) $post_data['product_subcat'] : 0;
    $category_terms = array();

    if ($subcategory_id > 0) {
        $subcategory_term = get_term($subcategory_id, 'product_cat');
        if ($subcategory_term instanceof WP_Term && (int) $subcategory_term->parent === $parent_category_id) {
            $category_terms[] = $parent_category_id;
            $category_terms[] = $subcategory_id;
        } else {
            $category_terms[] = $parent_category_id;
        }
    } else {
        $category_terms[] = $parent_category_id;
    }

    wp_set_object_terms($product_id, array_values(array_unique(array_map('intval', $category_terms))), 'product_cat');
}
// =============================
// SAVE CUSTOM META
// =============================
update_post_meta(
    $product_id,
    '_stakmv_auction_condition',
    sanitize_text_field($post_data['condition'] ?? '')
);

update_post_meta(
    $product_id,
    '_stakmv_auction_location',
    sanitize_text_field($post_data['location'] ?? '')
);

$handling_time_days = isset($post_data['handling_time_days']) ? (int) $post_data['handling_time_days'] : 0;
if ($handling_time_days < 0) {
    $handling_time_days = 0;
}
if ($handling_time_days > 30) {
    $handling_time_days = 30;
}
update_post_meta($product_id, '_stakmv_auction_handling_time_days', $handling_time_days);

$returns_policy = sanitize_key((string) ($post_data['returns_policy'] ?? 'no_returns'));
if (in_array($returns_policy, array('returns_14_days', 'returns_30_days'), true)) {
    $returns_policy = 'returns_accepted'; // Normalize older return-period payloads.
}
if (!in_array($returns_policy, array('no_returns', 'returns_accepted'), true)) {
    $returns_policy = 'no_returns';
}
update_post_meta($product_id, '_stakmv_auction_returns_policy', $returns_policy);

$returns_days = isset($post_data['returns_days']) ? (int) $post_data['returns_days'] : 0;
if ($returns_days < 1) {
    $returns_days = 1;
}
if ($returns_days > 60) {
    $returns_days = 60;
}

$return_shipping_paid_by = sanitize_key((string) ($post_data['return_shipping_paid_by'] ?? 'buyer'));
if (!in_array($return_shipping_paid_by, array('buyer', 'seller'), true)) {
    $return_shipping_paid_by = 'buyer';
}

if ($returns_policy === 'returns_accepted') {
    update_post_meta($product_id, '_stakmv_auction_returns_days', $returns_days);
    update_post_meta($product_id, '_stakmv_auction_return_shipping_paid_by', $return_shipping_paid_by);
} else {
    delete_post_meta($product_id, '_stakmv_auction_returns_days');
    delete_post_meta($product_id, '_stakmv_auction_return_shipping_paid_by');
}

$shipping_cost_raw = array_key_exists('shipping_cost', $post_data)
    ? trim((string) $post_data['shipping_cost'])
    : '';

if ($shipping_mode === 'flat') {
    if ($shipping_cost_raw === '') {
        stakmv_listing_fail('Flat shipping cost is required for flat rate.', $is_ajax);
    }

    $shipping_cost_value = wc_format_decimal($shipping_cost_raw);
    if ($shipping_cost_value === '' || (float) $shipping_cost_value <= 0) {
        stakmv_listing_fail('Flat shipping cost must be greater than 0.', $is_ajax);
    }

    update_post_meta($product_id, '_stakmv_auction_shipping_cost', $shipping_cost_value);
} else {
    delete_post_meta($product_id, '_stakmv_auction_shipping_cost');
}

$faq_questions = isset($post_data['faq_question']) && is_array($post_data['faq_question']) ? $post_data['faq_question'] : array();
$faq_answers = isset($post_data['faq_answer']) && is_array($post_data['faq_answer']) ? $post_data['faq_answer'] : array();
$faq_rows = array();
$faq_count = max(count($faq_questions), count($faq_answers));
for ($i = 0; $i < $faq_count; $i++) {
    $faq_q = sanitize_text_field((string) ($faq_questions[$i] ?? ''));
    $faq_a = sanitize_textarea_field((string) ($faq_answers[$i] ?? ''));
    if ($faq_q === '' && $faq_a === '') {
        continue;
    }
    $faq_rows[] = array(
        'q' => $faq_q,
        'a' => $faq_a,
    );
}
if (!empty($faq_rows)) {
    update_post_meta($product_id, '_stakmv_listing_faqs', $faq_rows);
} else {
    delete_post_meta($product_id, '_stakmv_listing_faqs');
}


    // =============================
    // PRODUCT TYPE
    // =============================
    wp_set_object_terms($product_id, 'auction', 'product_type');

    // =============================
    // PRESERVE EXISTING IMAGES (EDIT MODE)
    // =============================
    // phpcs:disable WordPress.Security.NonceVerification.Missing -- stakmv_nonce is verified above before reading uploaded files.
    $has_uploaded_images = !empty($_FILES['images']['name'][0]);
    // phpcs:enable WordPress.Security.NonceVerification.Missing
    if (
        $edit_id &&
        !$has_uploaded_images &&
        empty($post_data['image_order']) &&
        empty($post_data['removed_images'])
    ) {
        // Do nothing — existing images remain untouched
    }

    // =============================
    // DELETE REMOVED IMAGES
    // =============================
    if (!empty($post_data['removed_images'])) {
        $removed = array_map('intval', explode(',', (string) $post_data['removed_images']));
        foreach ($removed as $attachment_id) {
            wp_delete_attachment($attachment_id, true);
        }
    }

    // =============================
    // HANDLE IMAGE UPLOADS
    // =============================
    if ($has_uploaded_images) {

        $image_ids = [];
        $count = 0;
        // phpcs:disable WordPress.Security.NonceVerification.Missing -- stakmv_nonce is verified above before reading uploaded files.
        $image_names = isset($_FILES['images']['name']) && is_array($_FILES['images']['name'])
            ? array_map('sanitize_file_name', wp_unslash($_FILES['images']['name']))
            : array();
        $image_types = isset($_FILES['images']['type']) && is_array($_FILES['images']['type'])
            ? array_map('sanitize_mime_type', wp_unslash($_FILES['images']['type']))
            : array();
        $image_tmp_names = isset($_FILES['images']['tmp_name']) && is_array($_FILES['images']['tmp_name'])
            ? array_map('sanitize_text_field', wp_unslash($_FILES['images']['tmp_name']))
            : array();
        $image_errors = isset($_FILES['images']['error']) && is_array($_FILES['images']['error'])
            ? array_map('intval', wp_unslash($_FILES['images']['error']))
            : array();
        $image_sizes = isset($_FILES['images']['size']) && is_array($_FILES['images']['size'])
            ? array_map('intval', wp_unslash($_FILES['images']['size']))
            : array();
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        foreach ($image_names as $i => $name) {

            if ($count >= $max_images) break;
            if (!isset($image_errors[$i]) || (int) $image_errors[$i] !== UPLOAD_ERR_OK) continue;

            $_FILES['upload_image'] = [
                'name'     => isset($image_names[$i]) ? (string) $image_names[$i] : '',
                'type'     => isset($image_types[$i]) ? (string) $image_types[$i] : '',
                'tmp_name' => isset($image_tmp_names[$i]) ? (string) $image_tmp_names[$i] : '',
                'error'    => isset($image_errors[$i]) ? (int) $image_errors[$i] : UPLOAD_ERR_NO_FILE,
                'size'     => isset($image_sizes[$i]) ? (int) $image_sizes[$i] : 0,
            ];

            $image_id = media_handle_upload('upload_image', $product_id);

            if (!is_wp_error($image_id)) {
                $image_ids[] = $image_id;
                $count++;
            }
        }

        if ($image_ids) {
            set_post_thumbnail($product_id, $image_ids[0]);
            update_post_meta(
                $product_id,
                '_product_image_gallery',
                implode(',', array_slice($image_ids, 1))
            );
        }
    }

    // =============================
    // SAVE IMAGE ORDER
    // =============================
    if (!empty($post_data['image_order']) && !$has_uploaded_images) {

        $ordered_ids = array_map('intval', explode(',', (string) $post_data['image_order']));

        if ($ordered_ids) {
            set_post_thumbnail($product_id, $ordered_ids[0]);
            update_post_meta(
                $product_id,
                '_product_image_gallery',
                implode(',', array_slice($ordered_ids, 1))
            );
        }
    }

    do_action('stakmv_listing_saved', $product_id, stakmv_sanitize_listing_hook_payload($post_data), $user_id, $edit_id);

    if ($request_key && $edit_id === 0) {
        set_transient(
            $request_key,
            array(
                'status'     => 'complete',
                'product_id' => (int) $product_id,
                'created_at' => time(),
            ),
            10 * MINUTE_IN_SECONDS
        );
    }

    stakmv_listing_finish(
        add_query_arg('updated', 1, get_permalink($product_id)),
        $is_ajax
    );
}
