
<?php

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

if (!is_user_logged_in()) {
    echo '<p>You must be logged in to create a listing.</p>';
    return;
}

if (!stakmv_current_user_can_access_vendor_area()) {
    wp_die(__('You are not allowed to create listings.', 'stak-multivendor'));
}

if (!stakmv_is_vendor()) {
    wp_die(__('You are not allowed to create listings.', 'stak-multivendor'));
}

$user_id = get_current_user_id();
$edit_id = isset($_GET['edit']) ? (int) $_GET['edit'] : 0;
$create_request_token = $edit_id ? '' : wp_generate_uuid4();

 // Defaults
$title = $description = $condition = $location = $length = $width = $height = '';
$start_price = $buy_now_price = $shipping_cost = $weight = '';
$quantity = 1;
$shipping_mode = '';
$shipping_scope = 'international';
$shipping_countries = array();
$handling_time_days = 2;
$returns_policy = 'no_returns';
$returns_days = 30;
$return_shipping_paid_by = 'buyer';
$listing_faqs = array();
$end_date = '';
$enable_buy_now = false; // kept for backward compatibility only
$listing_type = ''; // possible values: 'auction_only', 'buy_now_only', 'auction_buy_now'


/* ===============================
   ADDITIONS: edit lock + images
================================ */
$edit_locked = false;
$existing_images = [];

// ===============================
// EDIT MODE: LOAD PRODUCT
// ===============================
if ($edit_id) {
    $product = wc_get_product($edit_id);

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

    /* Lock editing only when real bids exist (avoid stale _stakmv_auction_has_bids meta). */
    $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);
    }
    $edit_locked = ($bid_count > 0);

    $title         = $product->get_name();
    $description   = $product->get_description();
    $weight        = $product->get_weight();
    $length = $product->get_length();
    $width  = $product->get_width();
    $height = $product->get_height();
    $saved_quantity = $product->get_stock_quantity();
    if ($saved_quantity !== null) {
      $quantity = max(1, (int) $saved_quantity);
    }


    $condition     = get_post_meta($edit_id, '_stakmv_auction_condition', true);
    $location      = get_post_meta($edit_id, '_stakmv_auction_location', true);
    $shipping_cost = get_post_meta($edit_id, '_stakmv_auction_shipping_cost', true);
    $shipping_mode = function_exists('stakmv_get_listing_shipping_mode')
        ? stakmv_get_listing_shipping_mode($edit_id)
        : 'calculated';
    if (function_exists('stakmv_get_listing_shipping_scope')) {
        $shipping_scope = stakmv_get_listing_shipping_scope($edit_id);
    }
    $saved_shipping_countries = get_post_meta($edit_id, '_stakmv_auction_shipping_countries', true);
    if (is_array($saved_shipping_countries)) {
        $shipping_countries = array_values(array_filter(array_map('sanitize_text_field', $saved_shipping_countries)));
    }
    $saved_handling_time = (int) get_post_meta($edit_id, '_stakmv_auction_handling_time_days', true);
    if ($saved_handling_time > 0) {
        $handling_time_days = $saved_handling_time;
    }
    $saved_returns_policy = sanitize_key((string) get_post_meta($edit_id, '_stakmv_auction_returns_policy', true));
    if (in_array($saved_returns_policy, array('no_returns', 'returns_accepted', 'returns_14_days', 'returns_30_days'), true)) {
        $returns_policy = $saved_returns_policy;
    }
    if ($returns_policy === 'returns_14_days') {
        $returns_policy = 'returns_accepted';
        $returns_days = 14;
    } elseif ($returns_policy === 'returns_30_days') {
        $returns_policy = 'returns_accepted';
        $returns_days = 30;
    }
    $saved_returns_days = (int) get_post_meta($edit_id, '_stakmv_auction_returns_days', true);
    if ($saved_returns_days > 0) {
        $returns_days = min(60, $saved_returns_days);
    }
    $saved_return_shipping_paid_by = sanitize_key((string) get_post_meta($edit_id, '_stakmv_auction_return_shipping_paid_by', true));
    if (in_array($saved_return_shipping_paid_by, array('buyer', 'seller'), true)) {
        $return_shipping_paid_by = $saved_return_shipping_paid_by;
    }
    $saved_listing_faqs = get_post_meta($edit_id, '_stakmv_listing_faqs', true);
    if (is_array($saved_listing_faqs)) {
        foreach ($saved_listing_faqs as $faq_row) {
            if (!is_array($faq_row)) {
                continue;
            }
            $faq_q = sanitize_text_field((string) ($faq_row['q'] ?? ''));
            $faq_a = sanitize_textarea_field((string) ($faq_row['a'] ?? ''));
            if ($faq_q === '' && $faq_a === '') {
                continue;
            }
            $listing_faqs[] = array('q' => $faq_q, 'a' => $faq_a);
        }
    }
    $start_price   = get_post_meta($edit_id, '_stakmv_auction_start_price', true);
    $buy_now_price = get_post_meta($edit_id, '_stakmv_auction_buy_now_price', true);
    $listing_type  = get_post_meta($edit_id, '_stakmv_auction_listing_type', true);

    // Infer combined mode if the listing type is missing but a Buy Now price exists.
    if ( empty( $listing_type ) && ! empty( $buy_now_price ) ) {
        $listing_type = 'auction_buy_now';
    }
    if ( empty( $listing_type ) ) {
        $listing_type = 'auction_only';
    }
    $enable_buy_now = ! empty( $buy_now_price );

    $end = get_post_meta($edit_id, '_stakmv_auction_end_time', true);
    if ($end) {
        $end_ts = is_numeric($end) ? (int) $end : strtotime($end);
        if ($end_ts) {
            $end_date = date('Y-m-d\TH:i', $end_ts);
        }
    }

    /* ðŸ–¼ ADDITION: load existing images */
    $featured = get_post_thumbnail_id($edit_id);
    if ($featured) {
        $existing_images[] = $featured;
    }

    $gallery = get_post_meta($edit_id, '_product_image_gallery', true);
    if ($gallery) {
        $existing_images = array_merge(
            $existing_images,
            array_map('intval', explode(',', $gallery))
        );
    }
}
?>
<?php
// Shipping carrier preferences (checkboxes, multi-select).
$carrier_options = array('USPS', 'UPS', 'FedEx', 'DHL');
$country_options = function_exists('WC') && WC()->countries ? WC()->countries->get_countries() : array();
$country_codes_lookup = array_fill_keys(array_keys($country_options), true);
$current_carriers = $carrier_options; // Default for new listings: all checked.

if (!empty($shipping_countries)) {
  $shipping_countries = array_values(array_filter(array_map(function ($country_code) use ($country_codes_lookup) {
    $country_code = strtoupper(sanitize_text_field((string) $country_code));
    return isset($country_codes_lookup[$country_code]) ? $country_code : '';
  }, $shipping_countries)));
}

if ($edit_id && isset($product)) {
  $saved_carriers = get_post_meta($edit_id, '_stakmv_auction_shipping_carriers', true);
  $normalized = array();

  if (is_array($saved_carriers)) {
    foreach ($saved_carriers as $carrier_value) {
      $carrier_value = sanitize_text_field((string) $carrier_value);
      if (in_array($carrier_value, $carrier_options, true)) {
        $normalized[] = $carrier_value;
      }
    }
  }

  if (empty($normalized)) {
    $single_carrier = sanitize_text_field((string) get_post_meta($edit_id, '_stakmv_auction_shipping_carrier', true));
    if (in_array($single_carrier, $carrier_options, true)) {
      $normalized[] = $single_carrier;
    }
  }

  if (!empty($normalized)) {
    $current_carriers = array_values(array_unique($normalized));
  }
}

$stakmv_show_section_item_details = function_exists('stakmv_is_listing_form_section_enabled') ? stakmv_is_listing_form_section_enabled('item_details') : true;
$stakmv_show_section_category_filters = function_exists('stakmv_is_listing_form_section_enabled') ? stakmv_is_listing_form_section_enabled('category_filters') : true;
$stakmv_show_section_pricing = function_exists('stakmv_is_listing_form_section_enabled') ? stakmv_is_listing_form_section_enabled('pricing_auction') : true;
$stakmv_show_section_shipping = function_exists('stakmv_is_listing_form_section_enabled') ? stakmv_is_listing_form_section_enabled('location_shipping') : true;
$stakmv_show_section_faq = function_exists('stakmv_is_listing_form_section_enabled') ? stakmv_is_listing_form_section_enabled('faq') : true;
$stakmv_show_section_photos = function_exists('stakmv_is_listing_form_section_enabled') ? stakmv_is_listing_form_section_enabled('photos') : true;

$stakmv_show_field_title = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('title') : true;
$stakmv_show_field_description = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('description') : true;
$stakmv_show_field_condition = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('condition') : true;
$stakmv_show_field_quantity = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('quantity') : true;
$stakmv_show_field_category = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('category') : true;
$stakmv_show_field_attributes = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('attributes') : true;
$stakmv_show_field_location = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('location') : true;
$stakmv_show_field_shipping_scope = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('shipping_scope') : true;
$stakmv_show_field_handling_time = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('handling_time') : true;
$stakmv_show_field_returns_policy = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('returns_policy') : true;
$stakmv_show_field_flat_shipping_cost = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('flat_shipping_cost') : true;
$stakmv_show_field_package_metrics = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('package_metrics') : true;
$stakmv_show_field_supported_carriers = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('supported_carriers') : true;
$stakmv_show_field_faq_builder = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('faq_builder') : true;
$stakmv_show_field_photo_upload = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('photo_upload') : true;
$stakmv_show_field_delete_action = function_exists('stakmv_is_listing_form_field_enabled') ? stakmv_is_listing_form_field_enabled('delete_listing_action') : true;
?>

<div class="stakmv-create-listing">

  <?php if ( isset( $_GET['stakmv_create_pending'] ) ) : ?>
    <div class="vintage-card wcmv-notice-card wcmv-notice-warning">
      Your listing is still being saved. Please wait a moment.
    </div>
  <?php endif; ?>

  <!-- ===============================
       PAGE HEADER
  =============================== -->
  <div class="mb-6 md:mb-8">
    <h1 class="carnival-text text-2xl md:text-3xl font-bold">
      <?php echo $edit_id ? 'Edit Listing' : 'List Your Treasure'; ?>
    </h1>
    <p class="text-sm md:text-base opacity-75">
      <?php echo $edit_id
        ? 'Update your auction details'
        : 'Join the carnival and let others discover your item'; ?>
    </p>
  </div>

  <?php if ($edit_locked): ?>
    <!-- ðŸ”’ EDIT RESTRICTION NOTICE -->
    <div class="vintage-card wcmv-notice-card wcmv-notice-error">
      This listing already has bids. Editing and deleting are disabled.
    </div>
  <?php endif; ?>

  <form method="post"
        id="stakmv-create-listing-form"
        enctype="multipart/form-data"
        class="wcmv-form space-y-6 md:space-y-8">

    <?php wp_nonce_field('stakmv_create_listing', 'stakmv_nonce'); ?>
    <?php if ( ! $edit_id ) : ?>
      <input type="hidden" name="stakmv_request_token" value="<?php echo esc_attr( $create_request_token ); ?>">
    <?php endif; ?>

    <?php if ($edit_id): ?>
      <input type="hidden" name="edit_id" value="<?php echo esc_attr($edit_id); ?>">
    <?php endif; ?>

    <!--hidden tracker-->
    <input type="hidden" name="removed_images" id="wcmv-removed-images">
    <input type="hidden" name="image_order" id="wcmv-image-order">

    <!-- ===============================
         ITEM DETAILS
    =============================== -->
    <?php if ($stakmv_show_section_item_details) : ?>
    <div class="wcmv-form-card">
      <h2 class="carnival-text mb-4">Item Details</h2>

      <div class="wcmv-form-grid">
        <?php if ($stakmv_show_field_title) : ?>
        <div class="wcmv-field full">
          <label>Title *</label>
          <input type="text"
                 name="title"
                 required
                 value="<?php echo esc_attr($title); ?>"
                 placeholder="What are you selling?" />
        </div>
        <?php endif; ?>

        <?php if ($stakmv_show_field_description) : ?>
        <div class="wcmv-field full">
          <label>Description</label>
          <?php
          if (function_exists('wp_editor')) {
            wp_editor(
              wp_kses_post((string) $description),
              'stakmv_listing_description',
              array(
                'textarea_name' => 'description',
                'textarea_rows' => 10,
                'media_buttons' => false,
                'teeny'         => false,
              )
            );
          } else {
            ?>
            <textarea name="description"
              placeholder="Describe your item in detail..."><?php
                echo esc_textarea($description);
            ?></textarea>
            <?php
          }
          ?>
        </div>
        <?php endif; ?>

       <?php if ($stakmv_show_field_condition) : ?>
       <div class="wcmv-field" id="wcmv-start-wrap">

          <label>Condition</label>
          <select name="condition">
            <option value="">Select condition</option>
            <?php
            $condition_options = function_exists('stakmv_get_condition_options')
              ? stakmv_get_condition_options()
              : array();
            foreach ($condition_options as $condition_key => $condition_row) :
              $condition_label = isset($condition_row['label']) ? (string) $condition_row['label'] : '';
              $condition_detail = isset($condition_row['detail']) ? (string) $condition_row['detail'] : '';
              if ($condition_label === '') {
                continue;
              }
              $option_text = $condition_label;
              if ($condition_detail !== '') {
                $option_text .= ' — ' . $condition_detail;
              }
              ?>
              <option value="<?php echo esc_attr($condition_key); ?>" <?php selected($condition, $condition_key); ?>>
                <?php echo esc_html($option_text); ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <?php endif; ?>

        <?php if ($stakmv_show_field_quantity) : ?>
        <div class="wcmv-field">
          <label>Quantity</label>
          <input type="number"
                 name="quantity"
                 min="1"
                 step="1"
                 value="<?php echo esc_attr((string) $quantity); ?>" />
        </div>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- ===============================
         CATEGORY & FILTERS
    =============================== -->
    <?php if ($stakmv_show_section_category_filters) : ?>
    <div class="wcmv-form-card">
      <h2 class="carnival-text mb-4">Category & Filters</h2>

      <div class="wcmv-form-grid">
        <?php if ($stakmv_show_field_category) : ?>
        <div class="wcmv-field">
          <label>Category</label>
          <select id="wcmv-category" name="product_cat">
            <option value=""><?php esc_html_e('Select a category', 'stak-multivendor'); ?></option>
            <?php
            $selected_cat_id = 0;
            $selected_subcat_id = 0;
            if ( $edit_id ) {
              $assigned_terms = wp_get_post_terms( $edit_id, 'product_cat' );
              if ( ! is_wp_error( $assigned_terms ) && ! empty( $assigned_terms ) ) {
                foreach ( $assigned_terms as $assigned_term ) {
                  if ( (int) $assigned_term->parent > 0 ) {
                    $selected_subcat_id = (int) $assigned_term->term_id;
                    $selected_cat_id = (int) $assigned_term->parent;
                    break;
                  }
                }
                if ( $selected_cat_id <= 0 ) {
                  $selected_cat_id = (int) $assigned_terms[0]->term_id;
                }
              }
            }
            $all_cats = get_terms( array(
              'taxonomy'   => 'product_cat',
              'parent'     => 0,
              'hide_empty' => false,
            ) );
            if ( ! is_wp_error( $all_cats ) && ! empty( $all_cats ) ) :
              foreach ( $all_cats as $cat ) :
                ?>
                <option value="<?php echo esc_attr( (string) $cat->term_id ); ?>" <?php selected( $selected_cat_id, (int) $cat->term_id ); ?>>
                  <?php echo esc_html( $cat->name ); ?>
                </option>
                <?php
              endforeach;
            endif;
            ?>
          </select>
        </div>
        <?php endif; ?>

        <div class="wcmv-field full <?php echo $selected_subcat_id > 0 ? '' : 'wcmv-hidden'; ?>" id="wcmv-subcategory-wrap">
          <label><?php esc_html_e('Subcategory', 'stak-multivendor'); ?></label>
          <select id="wcmv-subcategory" name="product_subcat" <?php echo $selected_subcat_id > 0 ? '' : 'disabled'; ?>>
            <option value=""><?php esc_html_e('Select a subcategory', 'stak-multivendor'); ?></option>
            <?php
            $all_subcats = get_terms(
              array(
                'taxonomy'   => 'product_cat',
                'hide_empty' => false,
              )
            );
            if ( ! is_wp_error( $all_subcats ) && ! empty( $all_subcats ) ) :
              foreach ( $all_subcats as $subcat ) :
                $parent_id = (int) $subcat->parent;
                if ( $parent_id <= 0 ) {
                  continue;
                }
                $is_selected_subcat = ((int) $selected_subcat_id === (int) $subcat->term_id);
                $is_visible_for_parent = ((int) $selected_cat_id > 0 && (int) $selected_cat_id === $parent_id);
                ?>
                <option
                  value="<?php echo esc_attr( (string) $subcat->term_id ); ?>"
                  data-parent="<?php echo esc_attr( (string) $parent_id ); ?>"
                  <?php selected( $is_selected_subcat ); ?>
                  <?php echo $is_visible_for_parent ? '' : 'hidden disabled'; ?>
                >
                  <?php echo esc_html( $subcat->name ); ?>
                </option>
                <?php
              endforeach;
            endif;
            ?>
          </select>
        </div>
      </div>
    </div>
    <?php endif; ?>

    <!-- ===============================
         PRICING & AUCTION
    =============================== -->

    <!-- ===============================
     PRICING & AUCTION
=============================== -->
<?php if ($stakmv_show_section_pricing) : ?>
<div class="wcmv-form-card" id="wcmv-pricing-auction">
  <h2 class="carnival-text mb-4">Pricing & Auction</h2>

  <div class="wcmv-form-grid">

    <?php
      $is_buy_now_only_mode = ('buy_now_only' === $listing_type);
      $is_stakmv_auction_buy_now_mode = ('auction_buy_now' === $listing_type);
    ?>

    <!-- LISTING MODE TABS -->
    <div class="wcmv-field full">
      <label>Listing Type</label>
      <div class="wcmv-mode-tabs" role="tablist" aria-label="Listing mode">
        <button type="button"
                class="wcmv-mode-tab <?php echo $is_buy_now_only_mode ? '' : 'is-active'; ?>"
                data-wcmv-mode-tab="auction"
                role="tab"
                aria-selected="<?php echo $is_buy_now_only_mode ? 'false' : 'true'; ?>">
          Auction
        </button>
        <button type="button"
                class="wcmv-mode-tab <?php echo $is_buy_now_only_mode ? 'is-active' : ''; ?>"
                data-wcmv-mode-tab="buy_now"
                role="tab"
                aria-selected="<?php echo $is_buy_now_only_mode ? 'true' : 'false'; ?>">
          Buy Now
        </button>
      </div>
      <input type="hidden" id="wcmv-listing-type" name="listing_type" value="<?php echo esc_attr($listing_type); ?>">
    </div>

    <!-- AUCTION TAB: BUY NOW TOGGLE -->
    <div class="wcmv-field full" id="wrap-auction-buy-now-toggle">
      <label>
        <input type="checkbox" id="wcmv-auction-enable-buy-now" <?php checked($is_stakmv_auction_buy_now_mode); ?>>
        Enable Buy Now in this auction
      </label>
    </div>

    <!-- START PRICE -->
    <div class="wcmv-field" id="wrap-start-price">
      <label>Starting Price *</label>
      <input type="number"
             id="start-price"
             name="start_price"
             step="0.01"
             min="0.01"
             value="<?php echo esc_attr($start_price); ?>"
             <?php echo $edit_locked ? 'disabled' : ''; ?>>

      <?php if ($edit_locked && $start_price !== ''): ?>
        <input type="hidden" name="start_price" value="<?php echo esc_attr($start_price); ?>">
      <?php endif; ?>
    </div>

    <!-- BUY NOW PRICE -->
    <div class="wcmv-field" id="wrap-buy-now">
      <label>Buy Now Price</label>
      <input type="number"
             id="buy-now-price"
             name="buy_now_price"
             step="0.01"
             class="<?php echo (!$is_buy_now_only_mode && !$is_stakmv_auction_buy_now_mode) ? 'wcmv-readonly-input' : ''; ?>"
             <?php echo (!$is_buy_now_only_mode && !$is_stakmv_auction_buy_now_mode) ? 'disabled' : ''; ?>
             value="<?php echo esc_attr($buy_now_price); ?>">
    </div>

    <?php
      do_action(
        'stakmv_create_listing_pricing_fields',
        array(
          'edit_id' => (int) $edit_id,
          'listing_type' => (string) $listing_type,
          'is_edit_locked' => (bool) $edit_locked,
        )
      );
    ?>

    <!-- END DATE -->
    <div class="wcmv-field" id="wrap-end-date">
      <label>Auction End Date *</label>
      <input type="datetime-local"
             id="end-date"
             name="end_date"
             value="<?php echo esc_attr($end_date); ?>">
    </div>

  </div>
</div>
<?php endif; ?>

    <!-- ===============================
         LOCATION & SHIPPING
    =============================== -->

<?php if ($stakmv_show_section_shipping) : ?>
<div class="wcmv-form-card">
  <h2 class="carnival-text mb-4">Location & Shipping</h2>

  <div class="wcmv-form-grid">

    <?php if ($stakmv_show_field_location) : ?>
    <div class="wcmv-field full">
      <label>Item Location</label>
      <input type="text"
             name="location"
             value="<?php echo esc_attr($location); ?>"
             placeholder="City, State" />
    </div>
    <?php endif; ?>

    <div class="wcmv-field full">
      <label>Shipping Type</label>
      <select
        name="shipping_mode"
        id="wcmv-shipping-mode"
        data-site-name="<?php echo esc_attr(get_bloginfo('name')); ?>"
        required
      >
        <option value="" <?php selected($shipping_mode, ''); ?>>Select shipping type</option>
        <option value="calculated" <?php selected($shipping_mode, 'calculated'); ?>>Calculated</option>
        <option value="flat" <?php selected($shipping_mode, 'flat'); ?>>Flat rate</option>
        <option value="free" <?php selected($shipping_mode, 'free'); ?>>Free shipping</option>
        <option value="pickup_only" <?php selected($shipping_mode, 'pickup_only'); ?>>Pickup only</option>
      </select>
      <p id="wcmv-shipping-mode-hint" class="description wcmv-shipping-mode-hint">
      </p>
    </div>

    <?php if ($stakmv_show_field_shipping_scope) : ?>
    <div class="wcmv-field full wcmv-ship-scope-row" id="wcmv-wrap-ship-scope-row">
      <div class="wcmv-ship-scope-cell" id="wcmv-wrap-shipping-scope">
        <label>Ships To</label>
        <select id="wcmv-shipping-scope" name="shipping_scope">
          <option value="international" <?php selected($shipping_scope, 'international'); ?>>International (all countries)</option>
          <option value="domestic" <?php selected($shipping_scope, 'domestic'); ?>>Domestic only</option>
          <option value="selected" <?php selected($shipping_scope, 'selected'); ?>>Selected countries only</option>
        </select>
        <p class="description">Control where this listing can be delivered.</p>
      </div>

      <div class="wcmv-ship-scope-cell" id="wcmv-wrap-shipping-countries">
        <label>Selected Countries</label>
        <div id="wcmv-shipping-countries" class="wcmv-country-checklist" role="group" aria-label="Selected Countries">
          <?php foreach ($country_options as $country_code => $country_name) : ?>
            <label class="wcmv-country-option">
              <input
                type="checkbox"
                name="shipping_countries[]"
                value="<?php echo esc_attr($country_code); ?>"
                <?php checked(in_array($country_code, $shipping_countries, true)); ?>
              >
              <?php echo esc_html($country_name); ?>
            </label>
          <?php endforeach; ?>
        </div>
        <p class="description">Used only when “Selected countries only” is chosen.</p>
      </div>
    </div>
    <?php endif; ?>

    <?php if ($stakmv_show_field_handling_time) : ?>
    <div class="wcmv-field">
      <label>Handling Time (days)</label>
      <input type="number"
             id="wcmv-handling-time-days"
             name="handling_time_days"
             min="0"
             max="30"
             step="1"
             value="<?php echo esc_attr((int) $handling_time_days); ?>" />
    </div>
    <?php endif; ?>

    <?php if ($stakmv_show_field_returns_policy) : ?>
    <div class="wcmv-field">
      <label>Returns Policy</label>
      <select id="wcmv-returns-policy" name="returns_policy">
        <option value="no_returns" <?php selected($returns_policy, 'no_returns'); ?>>No returns</option>
        <option value="returns_accepted" <?php selected($returns_policy, 'returns_accepted'); ?>>Returns accepted</option>
      </select>
    </div>

    <div class="wcmv-field" id="wcmv-wrap-returns-days">
      <label>Return Window (days)</label>
      <input type="number"
             id="wcmv-returns-days"
             name="returns_days"
             min="1"
             max="60"
             step="1"
             value="<?php echo esc_attr((int) $returns_days); ?>" />
    </div>

    <div class="wcmv-field" id="wcmv-wrap-return-shipping-paid-by">
      <label>Return Shipping Paid By</label>
      <select id="wcmv-return-shipping-paid-by" name="return_shipping_paid_by">
        <option value="buyer" <?php selected($return_shipping_paid_by, 'buyer'); ?>>Buyer</option>
        <option value="seller" <?php selected($return_shipping_paid_by, 'seller'); ?>>Seller</option>
      </select>
    </div>
    <?php endif; ?>

    <?php if ($stakmv_show_field_flat_shipping_cost) : ?>
    <div class="wcmv-field" id="wcmv-wrap-shipping-cost">
      <label>Flat Shipping Cost</label>
      <input type="number"
             id="wcmv-shipping-cost"
             name="shipping_cost"
             step="0.01"
             min="0.01"
             value="<?php echo esc_attr($shipping_cost); ?>" />
    </div>
    <?php endif; ?>

    <?php if ($stakmv_show_field_package_metrics) : ?>
    <div class="wcmv-field" id="wcmv-wrap-shipping-weight">
      <label>Package Weight (lbs)</label>
      <input type="number"
             id="wcmv-shipping-weight"
             name="weight"
             step="0.1"
             value="<?php echo esc_attr($weight); ?>" />
    </div>

    <!-- Dimensions (same size as above) -->
    <div class="wcmv-field" id="wcmv-wrap-shipping-length">
      <label>Length (in)</label>
      <input type="number"
             id="wcmv-shipping-length"
             step="0.1"
             name="length"
             value="<?php echo esc_attr($length); ?>">
    </div>

    <div class="wcmv-field" id="wcmv-wrap-shipping-width">
      <label>Width (in)</label>
      <input type="number"
             id="wcmv-shipping-width"
             step="0.1"
             name="width"
             value="<?php echo esc_attr($width); ?>">
    </div>

    <div class="wcmv-field" id="wcmv-wrap-shipping-height">
      <label>Height (in)</label>
      <input type="number"
             id="wcmv-shipping-height"
             step="0.1"
             name="height"
             value="<?php echo esc_attr($height); ?>">
    </div>
    <?php endif; ?>


    <!-- Preferred Shipping Carriers -->
    <?php if ($stakmv_show_field_supported_carriers) : ?>
    <div class="wcmv-field full" id="wcmv-wrap-shipping-carrier">
      <label>Supported Shipping Carriers</label>
      <div class="wcmv-carrier-options">
        <?php foreach ($carrier_options as $carrier_label) : ?>
          <label class="wcmv-carrier-option">
            <input
              type="checkbox"
              name="shipping_carriers[]"
              value="<?php echo esc_attr($carrier_label); ?>"
              <?php checked(in_array($carrier_label, $current_carriers, true)); ?>
            >
            <?php echo esc_html($carrier_label); ?>
          </label>
        <?php endforeach; ?>
      </div>
      <p class="description wcmv-carrier-description">
        Choose all carriers you can ship with for this listing.
      </p>
    </div>
    <?php endif; ?>

  </div>
</div>
<?php endif; ?>

    <?php if ($stakmv_show_section_faq && $stakmv_show_field_faq_builder) : ?>
    <div class="wcmv-form-card">
      <h2 class="carnival-text mb-4">FAQ</h2>

      <button type="button" id="wcmv-add-faq" class="wcmv-secondary-btn">+ Add FAQ</button>

      <div id="wcmv-faq-list" class="wcmv-faq-list <?php echo empty($listing_faqs) ? 'wcmv-hidden' : ''; ?>">
        <?php foreach ($listing_faqs as $faq_index => $faq_row) : ?>
          <div class="wcmv-faq-item">
            <div class="wcmv-field full">
              <label>Question</label>
              <input type="text" name="faq_question[]" value="<?php echo esc_attr((string) ($faq_row['q'] ?? '')); ?>" placeholder="Type a common buyer question">
            </div>
            <div class="wcmv-field full">
              <label>Answer</label>
              <textarea name="faq_answer[]" rows="3" placeholder="Type the answer"><?php echo esc_textarea((string) ($faq_row['a'] ?? '')); ?></textarea>
            </div>
            <button type="button" class="wcmv-remove-faq wcmv-secondary-btn">Remove</button>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- ===============================
         IMAGES
    =============================== -->
    <?php if ($stakmv_show_section_photos && $stakmv_show_field_photo_upload) : ?>
    <div class="wcmv-form-card">
      <h2 class="carnival-text mb-4">
        Photos <small>(Max 12)</small>
      </h2>

      <div class="wcmv-upload">
        <input type="file"
               id="wcmv-images"
               name="images[]"
               multiple
               accept="image/*">
      </div>

      <div id="wcmv-image-preview" class="wcmv-image-preview"></div>

      <div id="wcmv-image-editor-modal" class="wcmv-image-editor-modal wcmv-hidden">
        <div class="wcmv-image-editor-dialog">
          <div class="wcmv-image-editor-stage" id="wcmv-image-editor-stage"></div>
          <div class="wcmv-image-editor-actions">
            <button type="button" id="wcmv-image-rotate-left" class="wcmv-secondary-btn">Rotate Left</button>
            <button type="button" id="wcmv-image-rotate-right" class="wcmv-secondary-btn">Rotate Right</button>
            <button type="button" id="wcmv-image-cancel" class="wcmv-secondary-btn">Cancel</button>
            <button type="button" id="wcmv-image-apply" class="wcmv-primary-btn">Apply</button>
          </div>
        </div>
      </div>


<?php
$existing_images_payload = array();
if (! empty($existing_images)) {
  $existing_images_payload = array_map(function ($id) {
    return array(
      'id'  => $id,
      'url' => wp_get_attachment_image_url($id, 'thumbnail'),
    );
  }, $existing_images);
}
?>
      <input
        type="hidden"
        id="wcmv-existing-images-json"
        value="<?php echo esc_attr(wp_json_encode($existing_images_payload)); ?>"
      >


    
      
    </div>
    <?php endif; ?>

    <!-- ===============================
         ACTIONS
    =============================== -->
    <div class="wcmv-actions">
      <a href="javascript:history.back()" class="wcmv-secondary-btn">
        Cancel
      </a>
      <?php if ($edit_id && $stakmv_show_field_delete_action): ?>
        <button type="submit"
                name="stakmv_delete_listing"
                class="wcmv-secondary-btn"
                <?php echo $edit_locked ? 'disabled' : ''; ?>>
          Delete Listing
        </button>
      <?php endif; ?>
      <button type="submit"
              name="stakmv_create_listing"
              id="wcmv-create-submit"
              class="wcmv-primary-btn">
        <?php echo $edit_id ? 'Update Listing' : 'List Item'; ?>
      </button>
    </div>

    <div
      id="wcmv-submit-status"
      class="vintage-card wcmv-submit-status wcmv-hidden"
      role="status"
      aria-live="polite"
    ></div>

  </form>
</div>
