<?php
if (!defined('ABSPATH')) exit;
 // Unified dashboard: allow buyers and vendors.

$user    = wp_get_current_user();
$display_name = function_exists('stakmv_get_vendor_display_name') ? stakmv_get_vendor_display_name($user->ID) : (string) $user->display_name;
$initial = strtoupper(substr($display_name, 0, 1));
$bio       = function_exists('stakmv_get_vendor_bio') ? stakmv_get_vendor_bio($user->ID) : get_user_meta($user->ID, 'description', true);
$location  = get_user_meta($user->ID, 'stakmv_location', true);
$instagram = get_user_meta($user->ID, 'stakmv_instagram', true);
$twitter   = get_user_meta($user->ID, 'stakmv_twitter', true);
$website   = function_exists('stakmv_get_vendor_website') ? stakmv_get_vendor_website($user->ID) : $user->user_url;

$is_vendor = function_exists('stakmv_is_vendor') ? (bool) stakmv_is_vendor( $user->ID ) : false;
$vendor_rating_average = 0.0;
$vendor_rating_count   = 0;
if ( $is_vendor && function_exists( 'stakmv_get_vendor_rating_summary' ) ) {
    $vendor_rating_summary = stakmv_get_vendor_rating_summary( $user->ID );
    $vendor_rating_average = (float) ( $vendor_rating_summary['average'] ?? 0 );
    $vendor_rating_count   = (int) ( $vendor_rating_summary['count'] ?? 0 );
}
// Compute total bids for stats card
global $wpdb;
$bids_table = $wpdb->prefix . 'stakmv_auction_bids';
$total_bids_user = 0;
if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $bids_table ) ) === $bids_table ) {
    $total_bids_user = (int) $wpdb->get_var(
        $wpdb->prepare(
            "SELECT COUNT(*) FROM {$bids_table} WHERE user_id = %d",
            $user->ID
        )
    );
}

;

/**
 * Create Listing page URL (from admin setting)
 */
$create_listing_page_id  = stakmv_get_option('create_listing_page');
$create_listing_base_url = $create_listing_page_id
    ? get_permalink($create_listing_page_id)
    : '#';
$apply_vendor_url = function_exists('stakmv_get_apply_vendor_url')
    ? stakmv_get_apply_vendor_url()
    : '#';
$site_name = get_bloginfo('name');
?>

<?php if (isset($_GET['profile_updated'])) : ?>
  <div class="woocommerce-message">
    Profile updated successfully.
  </div>
<?php endif; ?>

<div class="wcmv-dashboard">

  <!-- ===============================
       STATS BAR
  =============================== -->
  <div class="wcmv-stats">

    <?php if ( $is_vendor ) : ?>
    <div class="stat-card stat-green">
      <h4 class="carnival-text"><span class="dashicons dashicons-portfolio"></span> BALANCE</h4>
      <strong>$0.00</strong>
    </div>

    <div class="stat-card stat-blue">
      <h4 class="carnival-text"><span class="dashicons dashicons-cart"></span> ITEMS SOLD</h4>
      <strong>0</strong>
    </div>

    <?php endif; ?>

    <div class="stat-card stat-orange">
      <h4 class="carnival-text"><span class="dashicons dashicons-visibility"></span> TOTAL BIDS</h4>
      <strong><?php echo esc_html( (int) $total_bids_user ); ?></strong>
    </div>

    <?php if ( $is_vendor ) : ?>
    <div class="stat-card stat-purple">
      <h4 class="carnival-text"><span class="dashicons dashicons-star-filled"></span> RATING</h4>
      <strong><?php echo esc_html( $vendor_rating_count > 0 ? number_format_i18n( $vendor_rating_average, 1 ) : '—' ); ?></strong>
    </div>
    <?php endif; ?>

    <?php do_action('stakmv_vendor_dashboard_cards', $user->ID); ?>

  </div>

  <?php do_action('stakmv_vendor_dashboard_panel_overview', $user->ID); ?>

  <!-- ===============================
       NAVIGATION TABS
  =============================== -->
  <div class="wcmv-tabs">
    <button type="button" class="wcmv-tab active" data-tab="profile"><span class="dashicons dashicons-admin-users"></span> PROFILE</button>
    <?php if ( $is_vendor ) : ?>
    <button type="button" class="wcmv-tab" data-tab="balance"><span class="dashicons dashicons-portfolio"></span> BALANCE</button>
    <?php endif; ?>
    <?php if ( $is_vendor ) : ?>
    <button type="button" class="wcmv-tab" data-tab="inventory"><span class="dashicons dashicons-cart"></span> INVENTORY</button>
    <?php endif; ?>
    <button type="button" class="wcmv-tab" data-tab="bids"><span class="dashicons dashicons-hammer"></span> BIDS</button>
    <button type="button" class="wcmv-tab" data-tab="purchases"><span class="dashicons dashicons-money"></span> PURCHASES</button>
    <button type="button" class="wcmv-tab" data-tab="notifications"><span class="dashicons dashicons-megaphone"></span> NOTIFICATIONS</button>
    <button type="button" class="wcmv-tab" data-tab="settings"><span class="dashicons dashicons-admin-generic"></span> SETTINGS</button>
    <?php do_action( 'stakmv_vendor_dashboard_extra_tabs', $user->ID, $is_vendor ); ?>
  </div>

  <!-- ===============================
       PROFILE PANEL
  =============================== -->
  <div id="wcmv-profile" class="wcmv-panel active">

    <?php do_action('stakmv_vendor_dashboard_panel_profile', $user->ID); ?>

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

      <!-- LEFT -->
      <div class="vintage-card wcmv-text-center">

        <div class="wcmv-avatar">
          <?php echo esc_html($initial); ?>
        </div>

        <h3 class="carnival-text"><?php echo esc_html($display_name); ?></h3>
        <p><?php echo esc_html($user->user_email); ?></p>

        <?php if ( $vendor_rating_count > 0 ) : ?>
        <p class="wcmv-rating-line">⭐ <?php echo esc_html( number_format_i18n( $vendor_rating_average, 1 ) ); ?></p>
        <?php else : ?>
        <p class="wcmv-rating-line"><em><?php esc_html_e( 'No feedback yet', 'stak-multivendor' ); ?></em></p>
        <?php endif; ?>

        <p class="wcmv-meta-muted">
          Joined <?php echo date('d M Y', strtotime($user->user_registered)); ?>
        </p>

      </div>

      <!-- RIGHT -->
      <div>

        <div class="vintage-card">
          <h3 class="carnival-text">BASIC INFORMATION</h3>
         <p>
  <strong>Bio:</strong>
  <?php echo $bio ? esc_html($bio) : '<em>Not set</em>'; ?>
</p>

<p>
  <strong>Location:</strong>
  <?php echo $location ? esc_html($location) : '<em>Not set</em>'; ?>
</p>


        <button class="wcmv-btn wcmv-mt-15" id="wcmv-edit-profile-btn">
  EDIT PROFILE
</button>
         <?php if ($is_vendor && function_exists('stakmv_get_vendor_profile_url')) : ?>
         <a class="wcmv-btn wcmv-mt-10" href="<?php echo esc_url(stakmv_get_vendor_profile_url($user->ID)); ?>" target="_blank" rel="noopener">
           <?php esc_html_e('VIEW PUBLIC PROFILE', 'stak-multivendor'); ?>
         </a>
         <?php endif; ?>

        </div>

        <div class="vintage-card">
          <h3 class="carnival-text">SOCIAL LINKS</h3>
          <p>
  Website:
  <?php if ($website) : ?>
    <a href="<?php echo esc_url($website); ?>" target="_blank">
      <?php echo esc_html($website); ?>
    </a>
  <?php else : ?>
    <em>Not set</em>
  <?php endif; ?>
</p>

<p>
  Instagram:
  <?php echo $instagram ? esc_html($instagram) : '<em>Not set</em>'; ?>
</p>

<p>
  Twitter:
  <?php echo $twitter ? esc_html($twitter) : '<em>Not set</em>'; ?>
</p>

        </div>

      </div>

    </div>
  </div>
<div class="wcmv-profile-modal wcmv-hidden" id="wcmv-edit-profile-modal" aria-hidden="true">
<div class="wcmv-profile-modal-dialog vintage-card wcmv-mt-20" id="wcmv-edit-profile-form">

  <button type="button" class="wcmv-profile-modal-close" id="wcmv-close-edit-profile" aria-label="<?php esc_attr_e('Close edit profile', 'stak-multivendor'); ?>">&times;</button>

  <h3 class="carnival-text">EDIT PROFILE</h3>

  <form method="post" class="wcmv-form">

    <?php wp_nonce_field('stakmv_update_profile', 'stakmv_profile_nonce'); ?>

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

      <div class="wcmv-field full">
        <label>Display Name</label>
        <input type="text"
               name="display_name"
               value="<?php echo esc_attr($display_name); ?>">
      </div>

      <div class="wcmv-field full">
        <label>Bio</label>
        <textarea name="bio"><?php
          echo esc_textarea($bio);
        ?></textarea>
      </div>

      <div class="wcmv-field full">
        <label>Public Profile Banner Slides</label>
        <p class="wcmv-form-helper">
          Upload up to 5 images. They will rotate on your public profile.
        </p>
        <?php
        $banner_slides = get_user_meta($user->ID, 'stakmv_banner_slide_urls', true);
        $banner_slides = is_array($banner_slides) ? array_values($banner_slides) : array();
        for ($i = 0; $i < 5; $i++) :
            $slide_url = isset($banner_slides[$i]) ? (string) $banner_slides[$i] : '';
        ?>
          <div class="wcmv-banner-upload-row" data-banner-row>
            <div class="wcmv-banner-preview<?php echo $slide_url === '' ? ' is-empty' : ''; ?>" data-banner-preview>
              <?php if ($slide_url !== '') : ?>
                <img src="<?php echo esc_url($slide_url); ?>" alt="">
              <?php endif; ?>
            </div>
            <input type="url"
                   name="stakmv_banner_slide_urls[]"
                   value="<?php echo esc_attr($slide_url); ?>"
                   placeholder="https://example.com/banner-<?php echo esc_attr((string) ($i + 1)); ?>.jpg"
                   class="wcmv-banner-url-input"
                   data-banner-input>
            <button type="button" class="wcmv-secondary-btn wcmv-banner-upload-btn" data-banner-upload><?php esc_html_e('Upload', 'stak-multivendor'); ?></button>
            <button type="button" class="wcmv-secondary-btn wcmv-banner-remove-btn" data-banner-remove><?php esc_html_e('Remove', 'stak-multivendor'); ?></button>
          </div>
        <?php endfor; ?>
      </div>

      <div class="wcmv-field">
        <label>Location</label>
        <input type="text"
               name="location"
               value="<?php echo esc_attr(get_user_meta($user->ID, 'stakmv_location', true)); ?>">
      </div>

      <div class="wcmv-field full">
        <label>Shipping Origin (for calculated shipping)</label>
        <p class="wcmv-form-helper">
          Used to calculate live shipping rates for your listings.
        </p>
      </div>

      <div class="wcmv-field">
        <label>Origin Address 1</label>
        <input type="text"
               name="ship_origin_address_1"
               value="<?php echo esc_attr(get_user_meta($user->ID, 'stakmv_ship_origin_address_1', true)); ?>">
      </div>

      <div class="wcmv-field">
        <label>Origin Address 2</label>
        <input type="text"
               name="ship_origin_address_2"
               value="<?php echo esc_attr(get_user_meta($user->ID, 'stakmv_ship_origin_address_2', true)); ?>">
      </div>

      <div class="wcmv-field">
        <label>Origin City</label>
        <input type="text"
               name="ship_origin_city"
               value="<?php echo esc_attr(get_user_meta($user->ID, 'stakmv_ship_origin_city', true)); ?>">
      </div>

      <div class="wcmv-field">
        <label>Origin State/Province</label>
        <input type="text"
               name="ship_origin_state"
               value="<?php echo esc_attr(get_user_meta($user->ID, 'stakmv_ship_origin_state', true)); ?>">
      </div>

      <div class="wcmv-field">
        <label>Origin ZIP/Postal Code</label>
        <input type="text"
               name="ship_origin_postcode"
               value="<?php echo esc_attr(get_user_meta($user->ID, 'stakmv_ship_origin_postcode', true)); ?>">
      </div>

      <div class="wcmv-field">
        <label>Origin Country</label>
        <?php
        $origin_country = (string) get_user_meta($user->ID, 'stakmv_ship_origin_country', true);
        $countries = function_exists('WC') && WC()->countries ? WC()->countries->get_countries() : array();
        if (!empty($countries)) :
        ?>
          <select name="ship_origin_country">
            <option value="">Select country</option>
            <?php foreach ($countries as $code => $country_name) : ?>
              <option value="<?php echo esc_attr($code); ?>" <?php selected($origin_country, $code); ?>>
                <?php echo esc_html($country_name); ?>
              </option>
            <?php endforeach; ?>
          </select>
        <?php else : ?>
          <input type="text"
                 name="ship_origin_country"
                 value="<?php echo esc_attr($origin_country); ?>">
        <?php endif; ?>
      </div>

      <div class="wcmv-field">
        <label>Website</label>
        <input type="url"
               name="website"
               value="<?php echo esc_attr($website); ?>">
      </div>

      <div class="wcmv-field">
        <label>Instagram</label>
        <input type="text"
               name="instagram"
               value="<?php echo esc_attr(get_user_meta($user->ID, 'stakmv_instagram', true)); ?>">
      </div>

      <div class="wcmv-field">
        <label>Twitter</label>
        <input type="text"
               name="twitter"
               value="<?php echo esc_attr(get_user_meta($user->ID, 'stakmv_twitter', true)); ?>">
      </div>

    </div>

    <div class="wcmv-actions-row">
      <button type="submit"
              name="stakmv_save_profile"
              class="wcmv-primary-btn">
        Save Changes
      </button>

      <button type="button"
              class="wcmv-secondary-btn"
              id="wcmv-cancel-edit-profile">
        Cancel
      </button>
    </div>

  </form>
</div>
</div>

<?php if ( ! $is_vendor ) : ?>
  <div class="vintage-card wcmv-apply-vendor-card">
    <h3 class="carnival-text">Start Selling</h3>
    <p>Ready to sell? Become a vendor and list your items.</p>
    <a href="<?php echo esc_url( $apply_vendor_url ); ?>" class="wcmv-apply-vendor-fab">
      <?php echo esc_html( sprintf( 'Sell on %s', $site_name ) ); ?>
    </a>
  </div>
<?php endif; ?>

  <!-- ===============================
       BALANCE
  =============================== -->
  <div id="wcmv-balance" class="wcmv-panel">

    <?php
    // Vendor header (not inside a card)
    $vendor_id = $user->ID;

    // Balance: prefer stakmv_get_wallet_balance if available, otherwise use 0.0.
    $balance = 0.0;
    if ( function_exists( 'stakmv_get_wallet_balance' ) ) {
        $balance = floatval( stakmv_get_wallet_balance( $vendor_id ) );
    } else {
        $fallback = apply_filters( 'stakmv_get_wallet_balance', 0, $vendor_id );
        $balance = is_numeric( $fallback ) ? floatval( $fallback ) : 0.0;
    }

    $balance_display = function_exists( 'wc_price' ) ? wc_price( $balance ) : esc_html( number_format_i18n( $balance, 2 ) );
    ?>

    <div class="wcmv-balance-header">
      <h2 class="carnival-text wcmv-balance-title">Account Balance</h2>
      <div class="wcmv-balance-row">
        <div>Available Balance:</div>
        <div class="wcmv-fw-900"><?php echo $balance_display; ?></div>
      </div>
    </div>

    <?php
    // ---------------------------
    // FIRST BOX: Balance Overview
    // ---------------------------
    global $wpdb;

    // Get vendor auction IDs safely
    $auction_ids = get_posts( array(
        'post_type'      => 'product',
        'posts_per_page' => -1,
        'author'         => $vendor_id,
        'fields'         => 'ids',
        'meta_query'     => array(
            array(
                'key'     => '_stakmv_auction_start_price',
                'compare' => 'EXISTS',
            ),
        ),
    ) );

    $auction_ids = is_array( $auction_ids ) ? array_map( 'intval', $auction_ids ) : array();

    // Total bids (only if bids table exists)
    $bids_table = $wpdb->prefix . 'stakmv_auction_bids';
    $total_bids = 0;
    if ( ! empty( $auction_ids ) && $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $bids_table ) ) === $bids_table ) {
        $auction_ids = array_values(
            array_filter(
                array_map( 'intval', $auction_ids ),
                function ( $id ) {
                    return $id > 0;
                }
            )
        );

        if ( ! empty( $auction_ids ) ) {
            $placeholders = implode( ',', array_fill( 0, count( $auction_ids ), '%d' ) );
            $query = $wpdb->prepare(
                "SELECT COUNT(*) FROM {$bids_table} WHERE auction_id IN ({$placeholders})",
                $auction_ids
            );
            $total_bids = (int) $wpdb->get_var( $query );
        }
    }

    // Total sales (approved escrows). Conservative: only count orders with escrow approved.
    $total_sales = 0;
    if ( ! empty( $auction_ids ) && function_exists( 'wc_get_orders' ) ) {
        $orders = wc_get_orders( array(
            'limit'        => -1,
            'meta_key'     => '_stakmv_auction_id',
            'meta_value'   => $auction_ids,
            'meta_compare' => 'IN',
        ) );

        if ( ! empty( $orders ) ) {
            foreach ( $orders as $order ) {
                $order_id = is_object( $order ) && method_exists( $order, 'get_id' ) ? $order->get_id() : intval( $order->ID ?? 0 );
                $escrow_status = get_post_meta( $order_id, '_stakmv_escrow_status', true );
                if ( $escrow_status === 'approved' ) {
                    $total_sales++;
                }
            }
        }
    }
    ?>

    <div class="vintage-card wcmv-mb-18">
      <h3 class="carnival-text">Balance Overview</h3>

      <ul class="wcmv-list-reset">
        <li class="wcmv-li-spaced"><strong>Balance:</strong> <?php echo $balance_display; ?></li>
        <li class="wcmv-li-spaced"><strong>Total Sales:</strong> <?php echo esc_html( intval( $total_sales ) ); ?></li>
        <li class="wcmv-li-spaced"><strong>Total Bids:</strong> <?php echo esc_html( intval( $total_bids ) ); ?></li>
      </ul>

      <p class="wcmv-footnote">
        Balance reflects approved auction earnings. Funds are credited after admin approval.
        Escrow applies to auction orders.
      </p>

      <?php
      // Extensions can render analytics inside the Balance Overview box.
      do_action( 'stakmv_vendor_dashboard_panel_analytics', $vendor_id );
      ?>
    </div>

    <?php
    // Allow extensions to render withdrawals UI/logic.
    do_action( 'stakmv_vendor_balance_withdrawals', $vendor_id );

    // --------------------------------
    // SECOND BOX: Recent Transactions
    // --------------------------------
    $ledger_table = $wpdb->prefix . 'stakmv_vendor_wallet_ledger';
    $transactions = array();

    if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $ledger_table ) ) === $ledger_table ) {
        $transactions = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$ledger_table} WHERE vendor_id = %d ORDER BY created_at DESC LIMIT 10",
            $vendor_id
        ) );
    }
    ?>

    <div class="vintage-card">
      <h3 class="carnival-text">Recent Transactions</h3>

      <?php if ( empty( $transactions ) ) : ?>
        <p>No transactions yet.</p>
      <?php else : ?>
        <div class="wcmv-table-wrap">
          <table class="wcmv-table">
            <thead>
              <tr>
                <th class="wcmv-th-left">Date</th>
                <th class="wcmv-th-left">Description</th>
                <th class="wcmv-th-right">Amount</th>
                <th class="wcmv-th-left">Status</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ( $transactions as $tx ) :
                $date = date_i18n( 'd M Y', strtotime( $tx->created_at ) );
                $desc = '';
                if ( ! empty( $tx->context ) ) {
                    $desc = esc_html( $tx->context );
                } elseif ( ! empty( $tx->meta ) ) {
                    // try to decode JSON meta for a friendly description if present
                    $decoded = json_decode( $tx->meta, true );
                    if ( is_array( $decoded ) && ! empty( $decoded['description'] ) ) {
                        $desc = esc_html( $decoded['description'] );
                    }
                }
                if ( $desc === '' ) {
                    $desc = isset( $tx->type ) ? esc_html( $tx->type ) : 'Ledger entry';
                }

                $amount = is_numeric( $tx->amount ) ? floatval( $tx->amount ) : 0.0;
                $amount_display = function_exists( 'wc_price' ) ? wc_price( $amount ) : esc_html( number_format_i18n( $amount, 2 ) );
                $status = isset( $tx->type ) ? esc_html( ucfirst( $tx->type ) ) : 'N/A';
              ?>
                <tr>
                  <td class="wcmv-td-left"><?php echo esc_html( $date ); ?></td>
                  <td class="wcmv-td-left"><?php echo $desc; ?></td>
                  <td class="wcmv-td-right"><?php echo $amount_display; ?></td>
                  <td class="wcmv-td-left"><?php echo $status; ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>

    </div>

  </div>

<!-- ===============================
     INVENTORY
=============================== -->
<div id="wcmv-inventory" class="wcmv-panel">

  <?php
  // ===============================
  // Inventory state (DEFINE ONCE)
  // ===============================
  $inv_search = sanitize_text_field($_GET['inv_search'] ?? '');
  $inv_stock  = sanitize_text_field($_GET['inv_stock'] ?? '');
  $inv_tab    = sanitize_text_field($_GET['inv_tab'] ?? 'listings');
  $inv_page   = max(1, (int) ($_GET['inv_page'] ?? 1));
  $inv_per_page = 20;
  $inv_bulk   = sanitize_text_field($_POST['inv_bulk_action'] ?? '');
  $dashboard_url = get_permalink(get_queried_object_id());
  if (!$dashboard_url) {
      $dashboard_url = stakmv_get_vendor_dashboard_url();
  }

  // ===============================
  // Handle BULK ACTIONS (POST)
  // ===============================
  if (
      $inv_bulk === 'delete'
      && ! empty($_POST['inv_ids'])
      && check_admin_referer('stakmv_bulk_inventory_action', 'stakmv_bulk_nonce')
  ) {
      foreach ((array) $_POST['inv_ids'] as $pid) {
          $pid = intval($pid);
          if ($pid > 0 && get_post_field('post_author', $pid) == get_current_user_id()) {
              wp_trash_post($pid);
          }
      }

      wp_safe_redirect(
          add_query_arg(
              ['tab' => 'inventory', 'inv_tab' => $inv_tab],
              $dashboard_url
          )
      );
      exit;
  }
  ?>

  <!-- HEADER -->
  <div class="vintage-card wcmv-flex-between-center">
    <h2 class="carnival-text">INVENTORY</h2>
    <a href="<?php echo esc_url($create_listing_base_url); ?>" class="wcmv-btn">
      + CREATE LISTING
    </a>
  </div>

  <?php if (isset($_GET['deleted'])) : ?>
    <div class="vintage-card wcmv-mt-12 wcmv-text-success">
      Listing deleted successfully.
    </div>
  <?php endif; ?>

  <?php if (isset($_GET['relisted'])) : ?>
    <div class="vintage-card wcmv-mt-12 wcmv-text-info">
      Auction relisted successfully.
    </div>
  <?php endif; ?>

  <?php if (isset($_GET['relist_denied'])) : ?>
    <div class="vintage-card wcmv-mt-12 wcmv-text-warning">
      This auction cannot be relisted right now.
    </div>
  <?php endif; ?>

  <!-- SUBTABS -->
  <div class="vintage-card wcmv-mb-12">
    <div class="wcmv-subtabs">

      <a
        class="wcmv-subtab <?php echo $inv_tab === 'listings' ? 'active' : ''; ?>"
        href="<?php echo esc_url(add_query_arg(array('tab' => 'inventory', 'inv_tab' => 'listings'), stakmv_get_vendor_dashboard_url())); ?>"
      >
        LISTINGS
      </a>

      <a
        class="wcmv-subtab <?php echo $inv_tab === 'auctions' ? 'active' : ''; ?>"
        href="<?php echo esc_url(add_query_arg(array('tab' => 'inventory', 'inv_tab' => 'auctions'), stakmv_get_vendor_dashboard_url())); ?>"
      >
        AUCTIONS
      </a>

    </div>
  </div>

  <!-- FILTERS -->
  <form method="get" class="wcmv-inventory-filters vintage-card wcmv-mb-12">
    <input type="hidden" name="tab" value="inventory">
    <input type="hidden" name="inv_tab" value="<?php echo esc_attr($inv_tab); ?>">

    <div class="wcmv-filter-row">
      <input type="search" name="inv_search" placeholder="Search products…" value="<?php echo esc_attr($inv_search); ?>">

      <select name="inv_stock">
        <option value="">All stock</option>
        <option value="instock" <?php selected($inv_stock, 'instock'); ?>>In stock</option>
        <option value="outofstock" <?php selected($inv_stock, 'outofstock'); ?>>Out of stock</option>
      </select>

      <button class="button button-primary">Filter</button>

      <?php if ($inv_search || $inv_stock) : ?>
        <a href="?tab=inventory&inv_tab=<?php echo esc_attr($inv_tab); ?>" class="button">Reset</a>
      <?php endif; ?>
    </div>
  </form>

  <?php
  // ===============================
  // QUERY PRODUCTS
  // ===============================
  $meta_query = [];

  if ($inv_stock) {
      $meta_query[] = [
          'key'   => '_stock_status',
          'value' => $inv_stock,
      ];
  }

  $products = get_posts([
      'post_type'      => 'product',
      'posts_per_page' => -1,
      'author'         => get_current_user_id(),
      's'              => $inv_search,
      'meta_query'     => $meta_query,
      'fields'         => 'ids',
  ]);

  $listings = [];
  $auctions = [];

  foreach ($products as $pid) {
      $mode = get_post_meta($pid, '_stakmv_auction_sale_mode', true);
      if ($mode === 'buy_now') {
          $listings[] = $pid;
          continue;
      }
      if (in_array($mode, ['auction', 'both'], true)) {
          $auctions[] = $pid;
          continue;
      }

      // Fallback when sale mode meta is missing.
      $start_price = get_post_meta($pid, '_stakmv_auction_start_price', true);
      $buy_now     = get_post_meta($pid, '_stakmv_auction_buy_now_price', true);

      if ($start_price !== '' && $start_price !== null) {
          $auctions[] = $pid;
      } elseif ($buy_now !== '' && $buy_now !== null) {
          $listings[] = $pid;
      }
  }

  $active_items = $inv_tab === 'auctions' ? $auctions : $listings;
  $inv_total_items = count($active_items);
  $inv_total_pages = max(1, (int) ceil($inv_total_items / $inv_per_page));
  if ($inv_page > $inv_total_pages) {
      $inv_page = $inv_total_pages;
  }
  $inv_offset = ($inv_page - 1) * $inv_per_page;

  if ($inv_tab === 'auctions') {
      $auctions = array_slice($auctions, $inv_offset, $inv_per_page);
      $listings = array();
  } else {
      $listings = array_slice($listings, $inv_offset, $inv_per_page);
      $auctions = array();
  }

  $inv_page_start = $inv_total_items > 0 ? ($inv_offset + 1) : 0;
  $inv_page_end   = min($inv_total_items, $inv_offset + $inv_per_page);
  ?>

  <div class="vintage-card wcmv-mb-12 wcmv-px-16 wcmv-py-12">
    <strong><?php echo esc_html(ucfirst($inv_tab)); ?>:</strong>
    <?php if ($inv_total_items > 0) : ?>
      Showing <?php echo esc_html((string) $inv_page_start); ?>-<?php echo esc_html((string) $inv_page_end); ?>
      of <?php echo esc_html((string) $inv_total_items); ?> item(s).
    <?php else : ?>
      0 items found.
    <?php endif; ?>
  </div>

  <!-- BULK FORM -->
  <form method="post">
    <?php wp_nonce_field('stakmv_bulk_inventory_action', 'stakmv_bulk_nonce'); ?>

<div class="wcmv-bulk-actions">
  <select name="inv_bulk_action">
    <option value="">Bulk actions</option>
    <option value="delete">Delete</option>
  </select>

  <button type="submit" name="apply_bulk">
    Apply
  </button>
</div>


    <!-- LISTINGS PANEL -->
    <div id="wcmv-inventory-listings" class="wcmv-subpanel <?php echo $inv_tab === 'listings' ? 'active' : ''; ?>">
      <?php if ($inv_tab === 'listings') : ?>
        <?php include __DIR__ . '/partials/inventory-listings-table.php'; ?>
      <?php endif; ?>
    </div>

    <!-- AUCTIONS PANEL -->
    <div id="wcmv-inventory-auctions" class="wcmv-subpanel <?php echo $inv_tab === 'auctions' ? 'active' : ''; ?>">
      <?php if ($inv_tab === 'auctions') : ?>
        <?php include __DIR__ . '/partials/inventory-auctions-table.php'; ?>
      <?php endif; ?>
    </div>

    <?php if ($inv_total_pages > 1) : ?>
      <div class="wcmv-pagination wcmv-mt-12">
        <?php for ($p = 1; $p <= $inv_total_pages; $p++) :
          $url = add_query_arg(
            array(
              'tab'       => 'inventory',
              'inv_tab'   => $inv_tab,
              'inv_search'=> $inv_search,
              'inv_stock' => $inv_stock,
              'inv_page'  => $p,
            ),
            stakmv_get_vendor_dashboard_url()
          );
          ?>
          <a class="button <?php echo $p === $inv_page ? 'button-primary' : ''; ?>" href="<?php echo esc_url($url); ?>">
            <?php echo esc_html($p); ?>
          </a>
        <?php endfor; ?>
      </div>
    <?php endif; ?>

  </form>

</div>

  <!-- ===============================
       NOTIFICATIONS
  =============================== -->
  <div id="wcmv-notifications" class="wcmv-panel">
    <div class="vintage-card">
      <h3 class="carnival-text">Notifications</h3>
      <?php
      do_action( 'stakmv_vendor_dashboard_panel_notifications', $user->ID );
      $notes = (array) get_user_meta( $user->ID, 'stakmv_notifications', true );
      ?>
      <?php if ( empty( $notes ) ) : ?>
        <p>No notifications yet.</p>
      <?php else : ?>
        <ul>
          <?php foreach ( $notes as $n ) : ?>
            <li><?php echo esc_html( $n ); ?></li>
          <?php endforeach; ?>
        </ul>
      <?php endif; ?>
    </div>
  </div>

  <!-- ===============================
       BIDS
  =============================== -->
  <div id="wcmv-bids" class="wcmv-panel">

    <?php
    /**
     * Bid data source
     * ----------------
     * Bids are stored in the {$wpdb->prefix}stakmv_auction_bids table created by
     * stakmv_maybe_create_bid_table() (see mv-auctions.php). Columns include:
     *  - id, auction_id, user_id, bid_amount, created_at
     *
     * We reuse that table here (no new storage) and query it read-only to show
     * auctions the current user has bid on, their highest bid per auction,
     * the auction's highest bid, status and end date.
     */
    global $wpdb;
    $user_id    = intval( $user->ID );
    $bids_table = $wpdb->prefix . 'stakmv_auction_bids';

    // If the bids table does not exist, behave safely and show "no bids"
    $table_exists = ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $bids_table ) ) === $bids_table );

    if ( ! $table_exists ) :
    ?>
      <div class="vintage-card">
        <p>You have not placed any bids yet.</p>
      </div>
    <?php
    else :

      // Get distinct auction IDs the user has bid on (most recent first)
      $auction_ids = $wpdb->get_col(
        $wpdb->prepare(
          "SELECT DISTINCT auction_id FROM {$bids_table} WHERE user_id = %d ORDER BY created_at DESC",
          $user_id
        )
      );

      if ( empty( $auction_ids ) ) :
      ?>
        <div class="vintage-card">
          <p>You have not placed any bids yet.</p>
        </div>
      <?php
      else :
      ?>
        <div class="vintage-card">
          <h3 class="carnival-text">My Bids</h3>

          <div class="wcmv-table-wrap">
            <table class="wcmv-table">
              <thead>
                <tr>
                  <th class="wcmv-th-left">Auction</th>
                  <th class="wcmv-th-right">Your Bid</th>
                  <th class="wcmv-th-right">Highest Bid</th>
                  <th class="wcmv-th-left">Status</th>
                  <th class="wcmv-th-left">Ends</th>
                </tr>
              </thead>
              <tbody>
                <?php
                foreach ( $auction_ids as $aid ) :

                  $aid = intval( $aid );
                  if ( $aid <= 0 ) {
                    continue;
                  }

                  $post = get_post( $aid );
                  if ( ! $post ) {
                    continue;
                  }

                  // User's highest bid for this auction
                  $user_bid = $wpdb->get_var(
                    $wpdb->prepare(
                      "SELECT MAX(bid_amount) FROM {$bids_table} WHERE auction_id = %d AND user_id = %d",
                      $aid,
                      $user_id
                    )
                  );

                  // Highest bid overall for this auction
                  $highest_bid = $wpdb->get_var(
                    $wpdb->prepare(
                      "SELECT MAX(bid_amount) FROM {$bids_table} WHERE auction_id = %d",
                      $aid
                    )
                  );

                  $user_bid_display    = $user_bid !== null ? ( function_exists( 'wc_price' ) ? wc_price( $user_bid ) : esc_html( number_format_i18n( floatval( $user_bid ), 2 ) ) ) : '—';
                  $highest_bid_display = $highest_bid !== null ? ( function_exists( 'wc_price' ) ? wc_price( $highest_bid ) : esc_html( number_format_i18n( floatval( $highest_bid ), 2 ) ) ) : '—';

                  $status = get_post_meta( $aid, '_stakmv_auction_status', true );
                  $status = $status ? esc_html( $status ) : 'Active';

                  $end_time = get_post_meta( $aid, '_stakmv_auction_end_time', true );
                  $end_display = $end_time ? esc_html( date_i18n( 'd M Y H:i', strtotime( $end_time ) ) ) : '—';
                ?>
                  <tr>
                    <td class="wcmv-td-left">
                      <a href="<?php echo esc_url( get_permalink( $aid ) ); ?>"><?php echo esc_html( get_the_title( $aid ) ); ?></a>
                    </td>
                    <td class="wcmv-td-right"><?php echo $user_bid_display; ?></td>
                    <td class="wcmv-td-right"><?php echo $highest_bid_display; ?></td>
                    <td class="wcmv-td-left"><?php echo $status; ?></td>
                    <td class="wcmv-td-left"><?php echo $end_display; ?></td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>

        </div>
      <?php
      endif; // has auction_ids
    endif; // table exists
    ?>

  </div>

  <!-- ===============================
       COMPLETED PURCHASES
  =============================== -->
  <div id="wcmv-purchases" class="wcmv-panel">
    <div class="vintage-card">
      <h3 class="carnival-text">My Purchases</h3>

      <?php
      // Allow extensions to extend the panel.
      do_action( 'stakmv_vendor_dashboard_panel_completed_purchases', $user->ID );

      if ( function_exists( 'wc_get_orders' ) ) {
          $orders = wc_get_orders( array(
              'customer' => $user->ID,
              'status'   => array( 'wc-completed' ),
              'orderby'  => 'date',
              'order'    => 'DESC',
              'limit'    => 10,
          ) );
      } else {
          $orders = array();
      }
      ?>

      <?php if ( empty( $orders ) ) : ?>
        <p>No completed purchases found.</p>
      <?php else : ?>
        <div class="wcmv-table-wrap">
          <table class="wcmv-table">
            <thead>
              <tr>
                <th class="wcmv-th-left">Date</th>
                <th class="wcmv-th-left">Order</th>
                <th class="wcmv-th-right">Total</th>
                <th class="wcmv-th-left">Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ( $orders as $order ) :
                $order_id    = is_object( $order ) && method_exists( $order, 'get_id' ) ? $order->get_id() : intval( $order->ID ?? 0 );
                $order_date  = is_object( $order ) && method_exists( $order, 'get_date_created' ) && $order->get_date_created() ? $order->get_date_created()->date_i18n( 'd M Y' ) : esc_html( get_the_date( 'd M Y', $order_id ) );
                $order_link  = function_exists( 'wc_get_endpoint_url' ) ? wc_get_endpoint_url( 'view-order', $order_id, wc_get_page_permalink( 'myaccount' ) ) : get_permalink( $order_id );
                $order_total = is_object( $order ) && method_exists( $order, 'get_formatted_order_total' ) ? $order->get_formatted_order_total() : '';
              ?>
                <tr>
                  <td class="wcmv-td-left"><?php echo esc_html( $order_date ); ?></td>
                  <td class="wcmv-td-left">
                    <a href="<?php echo esc_url( $order_link ); ?>">#<?php echo esc_html( $order_id ); ?></a>
                  </td>
                  <td class="wcmv-td-right"><?php echo wp_kses_post( $order_total ); ?></td>
                  <td class="wcmv-td-left">
                    <?php do_action( 'stakmv_vendor_dashboard_completed_purchase_row_actions', $order ); ?>

                    <form method="post" class="wcmv-inline-form wcmv-mr-6">
                      <?php wp_nonce_field( 'stakmv_confirm_delivery', 'stakmv_confirm_delivery_nonce' ); ?>
                      <input type="hidden" name="stakmv_confirm_delivery" value="1">
                      <input type="hidden" name="order_id" value="<?php echo esc_attr( $order_id ); ?>">
                      <button type="submit" class="button">Confirm Delivery</button>
                    </form>

                    <form method="post" class="wcmv-inline-form">
                      <?php wp_nonce_field( 'stakmv_open_dispute', 'stakmv_open_dispute_nonce' ); ?>
                      <input type="hidden" name="stakmv_open_dispute" value="1">
                      <input type="hidden" name="order_id" value="<?php echo esc_attr( $order_id ); ?>">
                      <button type="submit" class="button">Open Dispute</button>
                    </form>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>

    </div>
  </div>

  <!-- ===============================
       SETTINGS
  =============================== -->
  <div id="wcmv-settings" class="wcmv-panel">
    <div class="vintage-card">
      <h3 class="carnival-text">Preferences</h3>
      <?php
      $notify_bids     = get_user_meta($user->ID, 'stakmv_notify_bids', true) === 'yes';
      $public_profile  = get_user_meta($user->ID, 'stakmv_public_profile', true) === 'yes';
      $expected_days   = (int) get_user_meta($user->ID, 'stakmv_expected_delivery_days', true );
      ?>
      <form method="post" class="wcmv-form">
        <?php wp_nonce_field('stakmv_save_settings', 'stakmv_settings_nonce'); ?>

        <div class="wcmv-form-grid">
          <div class="wcmv-field full wcmv-checkbox">
            <label>
              <input type="checkbox" name="stakmv_notify_bids" value="1" <?php checked($notify_bids); ?>>
              <span>Email me when there is activity on auctions I’m involved in</span>
            </label>
          </div>

          <div class="wcmv-field full wcmv-checkbox">
            <label>
              <input type="checkbox" name="stakmv_public_profile" value="1" <?php checked($public_profile); ?>>
              <span>Make my profile visible to other users</span>
            </label>
          </div>

          <!-- Expected delivery is now auto-calculated at checkout; field removed -->
        </div>

        <div class="wcmv-mt-16">
          <button type="submit" name="stakmv_save_settings" class="wcmv-primary-btn">Save Settings</button>
        </div>
      </form>
    </div>
  </div>

  <?php do_action( 'stakmv_vendor_dashboard_extra_panels', $user->ID, $is_vendor ); ?>

</div>
