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

$stakmv_vendor = get_query_var('stakmv_vendor_obj');
if (!$stakmv_vendor) {
    wp_die('Invalid vendor');
}

$stakmv_vendor_id = (int) $stakmv_vendor->ID;
$stakmv_vendor_display_name = function_exists('stakmv_get_vendor_display_name')
    ? stakmv_get_vendor_display_name($stakmv_vendor_id)
    : (string) $stakmv_vendor->display_name;
$stakmv_custom_enabled = get_user_meta($stakmv_vendor_id, 'stakmv_custom_page_enabled', true) === 'yes';
$stakmv_rating_summary = function_exists('stakmv_get_vendor_rating_summary')
    ? stakmv_get_vendor_rating_summary($stakmv_vendor_id)
    : array('average' => 0.0, 'count' => 0, 'stars' => array());
$stakmv_reputation_summary = function_exists('stakmv_get_vendor_reputation_summary')
    ? stakmv_get_vendor_reputation_summary($stakmv_vendor_id)
    : array();
$stakmv_banner_slides = get_user_meta($stakmv_vendor_id, 'stakmv_banner_slide_urls', true);
$stakmv_banner_slides = is_array($stakmv_banner_slides) ? array_values(array_filter(array_map('esc_url', $stakmv_banner_slides))) : array();
$stakmv_viewer_id = get_current_user_id();
$stakmv_is_owner = ($stakmv_viewer_id > 0 && $stakmv_viewer_id === $stakmv_vendor_id);
$stakmv_profile_url = function_exists('stakmv_get_vendor_profile_url')
    ? stakmv_get_vendor_profile_url($stakmv_vendor_id)
    : home_url('/');

$stakmv_positive_feedback = 0.0;
if (!empty($stakmv_rating_summary['count']) && !empty($stakmv_rating_summary['stars']) && is_array($stakmv_rating_summary['stars'])) {
    $stakmv_positive_count = (int) ($stakmv_rating_summary['stars'][4] ?? 0) + (int) ($stakmv_rating_summary['stars'][5] ?? 0);
    $stakmv_positive_feedback = ($stakmv_positive_count / max(1, (int) $stakmv_rating_summary['count'])) * 100;
}

$stakmv_fulfillment = max(0, min(100, (float) ($stakmv_reputation_summary['fulfillment_rate'] ?? 0)));
$stakmv_cancellation = max(0, min(100, (float) ($stakmv_reputation_summary['cancellation_rate'] ?? 0)));
$stakmv_repeat_buyers = max(0, min(100, (float) ($stakmv_reputation_summary['repeat_buyers_rate'] ?? 0)));
$stakmv_product_count = count_user_posts($stakmv_vendor_id, 'product');

// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public profile section selection is read-only and does not mutate state.
$stakmv_section_raw = filter_input(INPUT_GET, 'section', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$stakmv_section = $stakmv_section_raw ? sanitize_key((string) $stakmv_section_raw) : 'shop';
if (!in_array($stakmv_section, array('shop', 'sold', 'about', 'feedback'), true)) {
    $stakmv_section = 'shop';
}

// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Public profile search is read-only and does not mutate state.
$stakmv_search_raw = filter_input(INPUT_GET, 'q', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$stakmv_search_term = $stakmv_search_raw ? sanitize_text_field((string) $stakmv_search_raw) : '';
$stakmv_public_about = (string) get_user_meta($stakmv_vendor_id, 'stakmv_public_about', true);
$stakmv_about_saved = false;
$stakmv_show_about_editor = false;

// phpcs:ignore WordPress.Security.NonceVerification.Missing -- This only detects the owner form before the nonce is read and verified below.
$stakmv_save_public_about = filter_input(INPUT_POST, 'stakmv_save_public_about', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if ($stakmv_is_owner && $stakmv_save_public_about) {
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Reading the nonce value in order to verify it immediately.
    $stakmv_nonce_raw = filter_input(INPUT_POST, 'stakmv_public_about_nonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $stakmv_nonce = sanitize_text_field((string) $stakmv_nonce_raw);
    if (wp_verify_nonce($stakmv_nonce, 'stakmv_save_public_about_' . $stakmv_vendor_id)) {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- stakmv_public_about_nonce is verified before reading content.
        $stakmv_public_about_raw = filter_input(INPUT_POST, 'stakmv_public_about', FILTER_UNSAFE_RAW);
        $stakmv_public_about = wp_kses_post((string) $stakmv_public_about_raw);
        update_user_meta($stakmv_vendor_id, 'stakmv_public_about', $stakmv_public_about);
        $stakmv_about_saved = true;
        $stakmv_show_about_editor = false;
    } else {
        $stakmv_show_about_editor = true;
    }
}

wp_enqueue_style(
    'stakmv-vendor-profile',
    STAKMV_PLUGIN_URL . 'assets/css/vendor-profile.css',
    array(),
    file_exists(STAKMV_PLUGIN_PATH . 'assets/css/vendor-profile.css')
        ? (string) filemtime(STAKMV_PLUGIN_PATH . 'assets/css/vendor-profile.css')
        : (defined('STAKMV_VERSION') ? STAKMV_VERSION : '1.0.0')
);
wp_enqueue_script(
    'stakmv-vendor-profile',
    STAKMV_PLUGIN_URL . 'assets/js/vendor-profile.js',
    array(),
    file_exists(STAKMV_PLUGIN_PATH . 'assets/js/vendor-profile.js')
        ? (string) filemtime(STAKMV_PLUGIN_PATH . 'assets/js/vendor-profile.js')
        : (defined('STAKMV_VERSION') ? STAKMV_VERSION : '1.0.0'),
    true
);

get_header();
?>

<div class="stakmv-vendor-profile-page">
  <div class="wcmv-vendor-header">
    <div class="wcmv-vendor-banner <?php echo empty($stakmv_banner_slides) ? 'default' : ''; ?>">
      <?php if (!empty($stakmv_banner_slides)) : ?>
        <div class="wcmv-vendor-banner-slider" data-autoplay="1">
	          <?php foreach ($stakmv_banner_slides as $stakmv_slide_index => $stakmv_slide_url) : ?>
	            <div class="wcmv-vendor-banner-slide <?php echo $stakmv_slide_index === 0 ? 'is-active' : ''; ?>">
	              <img src="<?php echo esc_url($stakmv_slide_url); ?>" alt="<?php echo esc_attr($stakmv_vendor_display_name); ?>">
            </div>
          <?php endforeach; ?>
          <?php if (count($stakmv_banner_slides) > 1) : ?>
            <button class="wcmv-vendor-banner-nav prev" type="button" aria-label="<?php esc_attr_e('Previous slide', 'stak-multivendor'); ?>">&#10094;</button>
            <button class="wcmv-vendor-banner-nav next" type="button" aria-label="<?php esc_attr_e('Next slide', 'stak-multivendor'); ?>">&#10095;</button>
          <?php endif; ?>
        </div>
      <?php endif; ?>
    </div>

    <div class="wcmv-vendor-meta">
      <div class="wcmv-vendor-identity-left">
        <?php echo get_avatar($stakmv_vendor_id, 96); ?>
        <div class="wcmv-vendor-identity-copy">
          <h1><?php echo esc_html($stakmv_vendor_display_name); ?></h1>
          <p class="wcmv-vendor-kpis">
            <?php if (!empty($stakmv_rating_summary['count'])) : ?>
              <span><strong><?php echo esc_html(number_format_i18n($stakmv_positive_feedback, 1)); ?>%</strong> <?php esc_html_e('positive feedback', 'stak-multivendor'); ?></span>
            <?php endif; ?>
            <span><strong><?php echo esc_html((string) ((int) ($stakmv_reputation_summary['total_orders'] ?? 0))); ?></strong> <?php esc_html_e('items sold', 'stak-multivendor'); ?></span>
            <span><strong><?php echo esc_html((string) ((int) $stakmv_product_count)); ?></strong> <?php esc_html_e('active listings', 'stak-multivendor'); ?></span>
          </p>
        </div>
      </div>

      <div class="wcmv-vendor-identity-actions">
        <a href="<?php echo esc_url(add_query_arg('section', 'shop', $stakmv_profile_url)); ?>#wcmv-vendor-products"><?php esc_html_e("Seller's other items", 'stak-multivendor'); ?></a>
        <?php do_action('stakmv_vendor_profile_actions', $stakmv_vendor_id, $stakmv_viewer_id); ?>
        <button type="button" class="wcmv-vendor-action-btn" data-wcmv-share><?php esc_html_e('Share', 'stak-multivendor'); ?></button>
      </div>
    </div>

    <div class="wcmv-vendor-nav-row">
      <nav class="wcmv-vendor-nav">
        <a class="<?php echo $stakmv_section === 'shop' ? 'is-active' : ''; ?>" href="<?php echo esc_url(add_query_arg('section', 'shop', $stakmv_profile_url)); ?>#wcmv-vendor-products"><?php esc_html_e('Shop', 'stak-multivendor'); ?></a>
        <a class="<?php echo $stakmv_section === 'sold' ? 'is-active' : ''; ?>" href="<?php echo esc_url(add_query_arg('section', 'sold', $stakmv_profile_url)); ?>#wcmv-vendor-products"><?php esc_html_e('Sold', 'stak-multivendor'); ?></a>
        <a class="<?php echo $stakmv_section === 'about' ? 'is-active' : ''; ?>" href="<?php echo esc_url(add_query_arg('section', 'about', $stakmv_profile_url)); ?>#wcmv-vendor-products"><?php esc_html_e('About', 'stak-multivendor'); ?></a>
        <a class="<?php echo $stakmv_section === 'feedback' ? 'is-active' : ''; ?>" href="<?php echo esc_url(add_query_arg('section', 'feedback', $stakmv_profile_url)); ?>#wcmv-vendor-products"><?php esc_html_e('Feedback', 'stak-multivendor'); ?></a>
      </nav>
      <?php if ($stakmv_section === 'shop' || $stakmv_section === 'sold') : ?>
        <form class="wcmv-vendor-search" method="get" action="<?php echo esc_url($stakmv_profile_url); ?>">
          <input type="hidden" name="section" value="<?php echo esc_attr($stakmv_section); ?>">
          <input type="search" name="q" value="<?php echo esc_attr($stakmv_search_term); ?>" placeholder="<?php esc_attr_e('Search seller items', 'stak-multivendor'); ?>">
        </form>
      <?php endif; ?>
    </div>
  </div>

  <div class="wcmv-vendor-content" id="wcmv-vendor-products">

    <?php if ($stakmv_custom_enabled) {
        do_action('stakmv_vendor_custom_sections', $stakmv_vendor_id);
    } ?>

    <?php if ($stakmv_section === 'about') : ?>
      <h2><?php esc_html_e('About seller', 'stak-multivendor'); ?></h2>
      <div class="vintage-card">
        <?php if ($stakmv_about_saved) : ?>
          <p class="woocommerce-message"><?php esc_html_e('About section updated.', 'stak-multivendor'); ?></p>
        <?php endif; ?>
        <div class="wcmv-vendor-about-content">
          <?php if ($stakmv_public_about !== '') : ?>
            <?php echo wp_kses_post(wpautop($stakmv_public_about)); ?>
          <?php else : ?>
            <p><?php echo esc_html__('No about information yet.', 'stak-multivendor'); ?></p>
          <?php endif; ?>
        </div>
        <?php if ($stakmv_is_owner) : ?>
          <button type="button" class="wcmv-primary-btn wcmv-about-edit-toggle"<?php echo $stakmv_show_about_editor ? ' style="display:none;"' : ''; ?>>
            <?php esc_html_e('Edit About', 'stak-multivendor'); ?>
          </button>
          <form method="post" class="wcmv-vendor-about-form<?php echo $stakmv_show_about_editor ? '' : ' wcmv-hidden'; ?>">
            <?php wp_nonce_field('stakmv_save_public_about_' . $stakmv_vendor_id, 'stakmv_public_about_nonce'); ?>
            <?php
            wp_editor(
                $stakmv_public_about,
                'stakmv_public_about_editor_' . $stakmv_vendor_id,
                array(
                    'textarea_name' => 'stakmv_public_about',
                    'textarea_rows' => 10,
                    'media_buttons' => true,
                    'teeny'         => false,
                    'quicktags'     => true,
                )
            );
            ?>
            <div class="wcmv-about-actions">
            <button type="submit" name="stakmv_save_public_about" class="wcmv-primary-btn"><?php esc_html_e('Save About', 'stak-multivendor'); ?></button>
            <button type="button" class="wcmv-secondary-btn wcmv-about-cancel"><?php esc_html_e('Cancel', 'stak-multivendor'); ?></button>
            </div>
          </form>
        <?php endif; ?>
      </div>

    <?php elseif ($stakmv_section === 'feedback') : ?>
      <h2><?php esc_html_e('Seller feedback', 'stak-multivendor'); ?></h2>
      <div class="vintage-card">
        <?php if (!empty($stakmv_reputation_summary)) : ?>
          <div class="wcmv-vendor-reputation">
            <div class="wcmv-vendor-metric">
              <div class="wcmv-vendor-metric-head">
                <span><?php esc_html_e('Fulfillment', 'stak-multivendor'); ?></span>
                <strong><?php echo esc_html(number_format_i18n($stakmv_fulfillment, 1)); ?>%</strong>
              </div>
              <div class="wcmv-vendor-metric-track"><span style="width: <?php echo esc_attr((string) $stakmv_fulfillment); ?>%"></span></div>
            </div>
            <div class="wcmv-vendor-metric">
              <div class="wcmv-vendor-metric-head">
                <span><?php esc_html_e('Cancellation rate', 'stak-multivendor'); ?></span>
                <strong><?php echo esc_html(number_format_i18n($stakmv_cancellation, 1)); ?>%</strong>
              </div>
              <div class="wcmv-vendor-metric-track is-danger"><span style="width: <?php echo esc_attr((string) $stakmv_cancellation); ?>%"></span></div>
            </div>
            <div class="wcmv-vendor-metric">
              <div class="wcmv-vendor-metric-head">
                <span><?php esc_html_e('Repeat buyers', 'stak-multivendor'); ?></span>
                <strong><?php echo esc_html(number_format_i18n($stakmv_repeat_buyers, 1)); ?>%</strong>
              </div>
              <div class="wcmv-vendor-metric-track"><span style="width: <?php echo esc_attr((string) $stakmv_repeat_buyers); ?>%"></span></div>
            </div>
          </div>
        <?php endif; ?>
	        <?php
	        global $wpdb;
		        $stakmv_ratings_table = $wpdb->prefix . 'stakmv_vendor_ratings';
		        $stakmv_feedback_rows = array();
		        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Read-only feedback list scoped to vendor.
		        $stakmv_table_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $stakmv_ratings_table));
		        if ($stakmv_table_exists === $stakmv_ratings_table) {
		            $stakmv_feedback_sql = '';
		            // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Plugin-owned table with prepared vendor id.
		            $stakmv_feedback_sql = $wpdb->prepare(
		                'SELECT buyer_id, rating, review, created_at FROM ' . $stakmv_ratings_table . ' WHERE vendor_id = %d ORDER BY created_at DESC LIMIT 50',
		                $stakmv_vendor_id
		            );
		            // phpcs:enable WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter
		            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Plugin-owned table, read-only feedback query.
		            $stakmv_feedback_rows = $wpdb->get_results($stakmv_feedback_sql);
		        }
	        ?>

	        <?php if (!empty($stakmv_feedback_rows)) : ?>
          <p class="wcmv-feedback-summary">
            <strong><?php echo esc_html(number_format_i18n((float) ($stakmv_rating_summary['average'] ?? 0), 1)); ?>/5</strong>
            (<?php echo esc_html((string) ((int) ($stakmv_rating_summary['count'] ?? 0))); ?> <?php esc_html_e('ratings', 'stak-multivendor'); ?>)
          </p>
	          <div class="wcmv-feedback-list">
	            <?php foreach ($stakmv_feedback_rows as $stakmv_feedback_row) :
	              $stakmv_buyer = get_userdata((int) ($stakmv_feedback_row->buyer_id ?? 0));
	              $stakmv_buyer_name = $stakmv_buyer ? $stakmv_buyer->display_name : __('Buyer', 'stak-multivendor');
	              $stakmv_stars = max(1, min(5, (int) ($stakmv_feedback_row->rating ?? 0)));
	              ?>
	              <article class="wcmv-feedback-item">
	                <p class="wcmv-feedback-head">
	                  <strong><?php echo esc_html($stakmv_buyer_name); ?></strong>
	                  <span><?php echo esc_html(str_repeat('★', $stakmv_stars)); ?></span>
	                  <time><?php echo esc_html(date_i18n('d M Y', strtotime((string) $stakmv_feedback_row->created_at))); ?></time>
	                </p>
	                <?php if (!empty($stakmv_feedback_row->review)) : ?>
	                  <p class="wcmv-feedback-body"><?php echo esc_html((string) $stakmv_feedback_row->review); ?></p>
	                <?php endif; ?>
	              </article>
	            <?php endforeach; ?>
          </div>
        <?php else : ?>
          <p><?php esc_html_e('No feedback yet.', 'stak-multivendor'); ?></p>
        <?php endif; ?>
      </div>

	    <?php else : ?>
	      <?php if ($stakmv_section === 'sold') : ?>
	        <?php /* translators: %s is the seller display name. */ ?>
	        <h2><?php echo esc_html(sprintf(__('Sold by %s', 'stak-multivendor'), $stakmv_vendor_display_name)); ?></h2>
	      <?php else : ?>
	        <?php /* translators: %s is the seller display name. */ ?>
	        <h2><?php echo esc_html(sprintf(__('Items by %s', 'stak-multivendor'), $stakmv_vendor_display_name)); ?></h2>
	      <?php endif; ?>
	      <?php
	      global $wpdb;
	      $stakmv_query_args = array(
          'post_type'      => 'product',
          'post_status'    => 'publish',
          'posts_per_page' => 24,
      );

      if ($stakmv_section === 'shop') {
          $stakmv_query_args['author'] = $stakmv_vendor_id;
          if ($stakmv_search_term !== '') {
              $stakmv_query_args['s'] = $stakmv_search_term;
          }
      } else {
	          $stakmv_sold_ids = array();
	          $stakmv_lookup_table = $wpdb->prefix . 'wc_order_product_lookup';
	          $stakmv_posts_table = $wpdb->posts;
			          // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- Read-only sold products query.
			          $stakmv_lookup_exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $stakmv_lookup_table));
			          if ($stakmv_lookup_exists === $stakmv_lookup_table) {
			              $stakmv_sold_ids_sql = '';
			              // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Core Woo/WP tables with prepared vendor ids.
			              $stakmv_sold_ids_sql = $wpdb->prepare(
			                  'SELECT DISTINCT opl.product_id FROM ' . $stakmv_lookup_table . ' opl INNER JOIN ' . $stakmv_posts_table . ' p ON p.ID = opl.product_id LEFT JOIN ' . $stakmv_posts_table . ' pp ON pp.ID = p.post_parent WHERE ((p.post_type = \'product\' AND p.post_author = %d) OR (p.post_type = \'product_variation\' AND pp.post_author = %d))',
			                  $stakmv_vendor_id,
			                  $stakmv_vendor_id
			              );
			              // phpcs:enable WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter
		              // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Read-only sold products query.
			              $stakmv_raw_product_ids = $wpdb->get_col($stakmv_sold_ids_sql);
	              foreach ((array) $stakmv_raw_product_ids as $stakmv_raw_id) {
	                  $stakmv_pid = (int) $stakmv_raw_id;
	                  if ($stakmv_pid <= 0) {
	                      continue;
	                  }
	                  $stakmv_type = get_post_type($stakmv_pid);
	                  if ($stakmv_type === 'product_variation') {
	                      $stakmv_parent_id = (int) wp_get_post_parent_id($stakmv_pid);
	                      if ($stakmv_parent_id > 0) {
	                          $stakmv_pid = $stakmv_parent_id;
	                      }
	                  }
	                  $stakmv_sold_ids[$stakmv_pid] = $stakmv_pid;
	              }
	          }

          if ($stakmv_search_term !== '') {
	              $stakmv_search_ids = get_posts(array(
	                  'post_type'      => 'product',
	                  'post_status'    => 'publish',
	                  'author'         => $stakmv_vendor_id,
	                  'posts_per_page' => 200,
	                  'fields'         => 'ids',
	                  's'              => $stakmv_search_term,
	              ));
	              $stakmv_search_map = array_fill_keys(array_map('intval', (array) $stakmv_search_ids), true);
	              foreach (array_keys($stakmv_sold_ids) as $stakmv_pid) {
	                  if (!isset($stakmv_search_map[$stakmv_pid])) {
	                      unset($stakmv_sold_ids[$stakmv_pid]);
	                  }
	              }
	          }

	          if (!empty($stakmv_sold_ids)) {
	              $stakmv_query_args['post__in'] = array_values($stakmv_sold_ids);
	              $stakmv_query_args['orderby'] = 'post__in';
	          } else {
              $stakmv_query_args['post__in'] = array(0);
          }
      }

      $stakmv_products = new WP_Query($stakmv_query_args);

      if ($stakmv_products->have_posts()) :
          echo '<div class="wcmv-vendor-products">';
          while ($stakmv_products->have_posts()) : $stakmv_products->the_post();
              $stakmv_item_id = get_the_ID();
              $stakmv_item_product = wc_get_product($stakmv_item_id);
              $stakmv_item_price_html = $stakmv_item_product instanceof WC_Product ? $stakmv_item_product->get_price_html() : '';
              ?>
              <article class="wcmv-vendor-product-card">
                <a class="wcmv-vendor-product-thumb" href="<?php the_permalink(); ?>">
                  <?php
                  if (has_post_thumbnail()) {
                      the_post_thumbnail('woocommerce_thumbnail');
                  } else {
                      echo '<img src="' . esc_url(wc_placeholder_img_src('woocommerce_thumbnail')) . '" alt="">';
                  }
                  ?>
                </a>
                <h3 class="wcmv-vendor-product-title">
                  <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                </h3>
                <?php if ($stakmv_item_price_html !== '') : ?>
                  <p class="wcmv-vendor-product-price"><?php echo wp_kses_post($stakmv_item_price_html); ?></p>
                <?php endif; ?>
              </article>
              <?php
          endwhile;
          echo '</div>';
          wp_reset_postdata();
      endif;
      ?>
    <?php endif; ?>

  </div>
</div>

<?php get_footer(); ?>
