<?php

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

class B2BKing_Customer_Pricing_Module {

	private static $instance = null;

	public static function get_instance() {
		if (null === self::$instance) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		if (is_admin()) {
			add_action('admin_enqueue_scripts', array($this, 'enqueue'));
			add_action('woocommerce_product_options_pricing', array($this, 'product_page_link'), 100);
			add_action('woocommerce_variation_options_pricing', array($this, 'variation_page_link'), 100, 3);
			add_action('wp_ajax_b2bking_crm_pricing_products', array($this, 'crm_pricing_products'));
			add_action('wp_ajax_b2bking_crm_pricing_save', array($this, 'save_price'));
			add_action('wp_ajax_b2bking_product_customer_prices', array($this, 'product_customer_prices'));
			add_action('wp_ajax_b2bking_product_customer_price_save', array($this, 'save_price'));
			add_action('wp_ajax_b2bking_customer_pricing_export_woo_csv', array($this, 'export_woo_csv'));
		}
	}

	public function enqueue($hook) {
		$screen = function_exists('get_current_screen') ? get_current_screen() : false;
		$page = sanitize_key($_GET['page'] ?? '');
		$post_type = $screen && !empty($screen->post_type) ? $screen->post_type : '';
		$is_b2bking_page = strpos($hook, 'b2bking') !== false || strpos($page, 'b2bking') === 0 || strpos($post_type, 'b2bking') === 0;
		$is_customer_pricing_page = $is_b2bking_page || $hook === 'user-edit.php' || $hook === 'profile.php' || $post_type === 'product';
		if (!$is_customer_pricing_page) {
			return;
		}

		$base_url = plugin_dir_url(B2BKING_DIR.'b2bking.php');
		wp_enqueue_script('b2bking-sweetalert2', $base_url.'includes/assets/lib/sweetalert/sweetalert2.all.min.js', array(), B2BKING_VERSION, true);
		wp_enqueue_script('b2bking-popper', $base_url.'includes/assets/lib/popper/popper.min.js', array(), B2BKING_VERSION, true);
		wp_enqueue_script('b2bking-tippy', $base_url.'includes/assets/lib/popper/tippy.min.js', array('b2bking-popper'), B2BKING_VERSION, true);
		wp_enqueue_style('select2', $base_url.'includes/assets/lib/select2/select2.min.css', array(), B2BKING_VERSION);
		wp_enqueue_script('select2', $base_url.'includes/assets/lib/select2/select2.min.js', array('jquery'), B2BKING_VERSION, true);
		wp_enqueue_style('b2bking_customer_pricing', plugins_url('customer-pricing.css', __FILE__), array(), B2BKING_VERSION);
		wp_enqueue_script('b2bking_customer_pricing', plugins_url('customer-pricing.js', __FILE__), array('jquery', 'b2bking-sweetalert2', 'select2', 'b2bking-tippy'), B2BKING_VERSION, true);
		wp_add_inline_script('b2bking_customer_pricing', 'window.b2bking_customer_pricing = '.wp_json_encode(array(
			'security' => wp_create_nonce('b2bking_security_nonce'),
			'error' => esc_html__('Error', 'b2bking'),
			'saving' => esc_html__('Saving...', 'b2bking'),
			'saved' => esc_html__('Saved', 'b2bking'),
			'type_to_search_users' => esc_html__('Type to search users...', 'b2bking'),
			'tier_value_label' => get_option('b2bking_enter_percentage_tiered_setting') === '1' ? esc_html__('% Discount', 'b2bking') : esc_html__('Price', 'b2bking').' ('.get_woocommerce_currency_symbol().')',
			'remove_prices' => esc_html__('Remove prices', 'b2bking'),
		)).';', 'before');
	}

	public static function crm_tab_button($active_tab) {
		?>
		<button type="button" class="b2bking-crm-tab-btn<?php echo $active_tab === 'pricing' ? ' active' : ''; ?>" data-tab="pricing"><svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"></path><line x1="7" y1="7" x2="7.01" y2="7"></line></svg> <?php esc_html_e('Pricing','b2bking'); ?></button>
		<?php
	}

	public static function crm_tab_pane($user_id, $active_tab) {
		$export_url = add_query_arg(array(
			'action' => 'b2bking_customer_pricing_export_woo_csv',
			'user_id' => $user_id,
			'security' => wp_create_nonce('b2bking_security_nonce'),
		), admin_url('admin-ajax.php'));
		$import_url = add_query_arg('b2bking_update_existing', '1', admin_url('edit.php?post_type=product&page=product_importer'));
		$docs_url = 'https://woocommerce-b2b-plugin.com/docs/customer-price-lists/';
		?>
		<div class="b2bking-crm-tab-pane<?php echo $active_tab === 'pricing' ? ' active' : ''; ?>" data-tab="pricing">
			<div class="b2bking-customer-pricing" data-user-id="<?php echo esc_attr($user_id); ?>">
				<div class="b2bking-customer-pricing-top">
					<p class="b2bking-customer-pricing-description"><?php esc_html_e('Individual negotiated prices for this customer, used outside their group pricing.', 'b2bking'); ?></p>
					<button type="button" class="button b2bking-customer-pricing-import-export-toggle"><?php esc_html_e('Import & Export', 'b2bking'); ?></button>
				</div>
				<div class="b2bking-customer-pricing-import-export-panel" style="display:none;">
					<p><?php esc_html_e('Download this customer\'s CSV price list, edit it, then import it with WooCommerce.', 'b2bking'); ?> <a href="<?php echo esc_url($docs_url); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e('Documentation', 'b2bking'); ?></a></p>
					<div class="b2bking-customer-pricing-import-export-actions">
						<a href="<?php echo esc_url($export_url); ?>" class="button b2bking-customer-pricing-export"><span class="dashicons dashicons-media-spreadsheet"></span><?php esc_html_e('Download CSV price list', 'b2bking'); ?></a>
						<a href="<?php echo esc_url($import_url); ?>" target="_blank" rel="noopener noreferrer" class="button b2bking-customer-pricing-export b2bking-customer-pricing-import"><span class="dashicons dashicons-upload"></span><?php esc_html_e('Open Woo importer', 'b2bking'); ?></a>
					</div>
				</div>
				<div class="b2bking-customer-pricing-editor">
					<div class="b2bking-customer-pricing-toolbar">
						<input type="text" class="b2bking-customer-pricing-search" placeholder="<?php esc_attr_e('Search products...', 'b2bking'); ?>">
						<button type="button" class="button b2bking-customer-pricing-search-btn"><?php esc_html_e('Search', 'b2bking'); ?></button>
					</div>
					<div class="b2bking-customer-pricing-table" data-page="1">
						<div class="b2bking-crm-empty-state"><?php esc_html_e('Loading customer prices...', 'b2bking'); ?></div>
					</div>
				</div>
			</div>
		</div>
		<?php
	}

	public function product_page_link() {
		global $post;
		if (!$post || $post->post_type !== 'product' || $post->post_status === 'auto-draft') {
			return;
		}
		$this->product_link_html($post->ID);
	}

	public function variation_page_link($loop, $variation_data, $variation) {
		if (empty($variation->ID)) {
			return;
		}
		$this->product_link_html($variation->ID, true);
	}

	private function product_link_html($product_id, $variation = false) {
		$count = $this->count_customers_with_prices($product_id);
		?>
		<div class="options_group b2bking-product-customer-pricing <?php echo $variation ? 'b2bking-product-customer-pricing-variation' : 'b2bking-product-customer-pricing-simple'; ?>">
			<p class="form-field b2bking-product-customer-pricing-field">
				<label><?php esc_html_e('Individual prices', 'b2bking'); ?> <?php echo function_exists('wc_help_tip') ? wc_help_tip(esc_html__('Optional prices for individual customers. Use this when a customer needs negotiated prices outside their group pricing.', 'b2bking')) : ''; ?></label>
				<span class="b2bking-product-customer-pricing-control">
					<button type="button" class="button b2bking-product-customer-prices" data-product-id="<?php echo esc_attr($product_id); ?>"><?php esc_html_e('Manage', 'b2bking'); ?></button>
					<?php if ($count > 0) : ?>
						<span class="b2bking-product-customer-pricing-count">
							<?php
							if ($count === 1) {
								esc_html_e('1 customer configured', 'b2bking');
							} else {
								printf(esc_html__('%s customers configured', 'b2bking'), esc_html($count));
							}
							?>
						</span>
					<?php endif; ?>
				</span>
			</p>
		</div>
		<?php
	}

	public function crm_pricing_products() {
		if (!$this->can_ajax()) {
			wp_send_json_error();
		}

		$user_id = intval($_POST['user_id']);
		$page = max(1, intval($_POST['page'] ?? 1));
		$search = sanitize_text_field(wp_unslash($_POST['search'] ?? ''));
		$ids = $this->get_customer_product_ids($user_id, $search, $page, 20);

		ob_start();
		$this->render_product_rows($ids['products'], $user_id);
		$this->render_pager($page, $ids['total'], 20);
		wp_send_json_success(array('html' => ob_get_clean()));
	}

	public function product_customer_prices() {
		if (!$this->can_ajax()) {
			wp_send_json_error();
		}

		$product_id = intval($_POST['product_id']);
		ob_start();
		?>
		<div class="b2bking-product-pricing-modal" data-product-id="<?php echo esc_attr($product_id); ?>">
			<div class="b2bking-product-pricing-add">
				<select class="b2bking-customer-price-user-search" style="width:100%"></select>
			</div>
			<div class="b2bking-product-pricing-rows">
				<div class="b2bking-product-pricing-row b2bking-product-pricing-head">
					<span><?php esc_html_e('Customer', 'b2bking'); ?></span>
					<span><?php echo esc_html__('Regular Price', 'b2bking').' ('.esc_html(get_woocommerce_currency_symbol()).')'; ?></span>
					<span><?php echo esc_html__('Sale Price', 'b2bking').' ('.esc_html(get_woocommerce_currency_symbol()).')'; ?></span>
					<span><?php esc_html_e('Actions', 'b2bking'); ?></span>
				</div>
				<?php $this->render_customer_rows($product_id); ?>
			</div>
			<div class="b2bking-product-pricing-footer">
				<button type="button" class="button button-primary b2bking-product-customer-prices-save-all"><?php esc_html_e('Save All', 'b2bking'); ?></button>
				<span class="b2bking-product-customer-prices-save-all-status"></span>
			</div>
		</div>
		<?php
		wp_send_json_success(array('html' => ob_get_clean()));
	}

	public function export_woo_csv() {
		if (!check_ajax_referer('b2bking_security_nonce', 'security', false) || !current_user_can(apply_filters('b2bking_backend_capability_needed', 'manage_woocommerce'))) {
			wp_die(esc_html__('You do not have permission to export customer prices.', 'b2bking'));
		}

		global $wpdb;
		$user_id = intval($_GET['user_id'] ?? 0);
		$user = get_userdata($user_id);
		if (!$user) {
			wp_die(esc_html__('Invalid customer.', 'b2bking'));
		}

		if (function_exists('set_time_limit')) {
			@set_time_limit(0);
		}

		$excluded_ids = array_filter(array_map('intval', array(
			get_option('b2bking_offer_product_id_setting', 0),
			get_option('b2bking_credit_product_id_setting', 0),
			get_option('marketking_credit_product_id_setting', 0),
		)));
		$where_excluded = empty($excluded_ids) ? '' : " AND p.ID NOT IN (".implode(',', $excluded_ids).")";
		$product_ids = $wpdb->get_col("SELECT p.ID FROM {$wpdb->posts} p WHERE p.post_type IN ('product','product_variation') AND p.post_status NOT IN ('trash','auto-draft') $where_excluded ORDER BY p.post_parent ASC, p.menu_order ASC, p.post_title ASC");

		nocache_headers();
		header('Content-Type: text/csv; charset=utf-8');
		header('Content-Disposition: attachment; filename=b2bking-customer-price-list-'.intval($user_id).'.csv');

		$output = fopen('php://output', 'w');
		fputcsv($output, array(
			'ID',
			'SKU',
			'Name',
			'Meta: b2bking_regular_price_user_'.$user_id,
			'Meta: b2bking_sale_price_user_'.$user_id,
			'Meta: b2bking_product_pricetiers_user_'.$user_id,
		));

		foreach ($product_ids as $product_id) {
			$product = wc_get_product($product_id);
			if (!$product) {
				continue;
			}
			$prices = b2bking()->get_user_product_prices($product_id, $user_id);
			$tiers = b2bking()->get_user_product_tiers($product_id, $user_id);
			fputcsv($output, array($product_id, $product->get_sku(), $product->get_name(), $prices['regular'], $prices['sale'], $tiers));
		}
		fclose($output);
		exit;
	}

	public function save_price() {
		if (!$this->can_ajax()) {
			wp_send_json_error();
		}

		$product_id = intval($_POST['product_id']);
		$user_id = intval($_POST['user_id']);
		b2bking()->set_user_product_prices($product_id, $user_id, sanitize_text_field(wp_unslash($_POST['regular'] ?? '')), sanitize_text_field(wp_unslash($_POST['sale'] ?? '')));
		if (isset($_POST['tiers_present'])) {
			b2bking()->set_user_product_tiers($product_id, $user_id, isset($_POST['tiers']) ? wc_clean(wp_unslash($_POST['tiers'])) : array());
		}
		if (function_exists('wc_delete_product_transients')) {
			wc_delete_product_transients($product_id);
		}
		b2bking()->clear_caches_transients();
		wp_send_json_success();
	}

	private function can_ajax() {
		return check_ajax_referer('b2bking_security_nonce', 'security', false) && current_user_can(apply_filters('b2bking_backend_capability_needed', 'manage_woocommerce'));
	}

	private function get_customer_product_ids($user_id, $search, $page, $per_page) {
		global $wpdb;
		$offset = ($page - 1) * $per_page;
		$types = "'product','product_variation'";

		if ($search !== '') {
			$like = '%'.$wpdb->esc_like($search).'%';
			$id_search = absint($search);
			$where = $wpdb->prepare("(p.post_title LIKE %s OR sku.meta_value LIKE %s OR p.ID = %d)", $like, $like, $id_search);
			$join = "LEFT JOIN {$wpdb->postmeta} sku ON sku.post_id = p.ID AND sku.meta_key = '_sku'";
		} else {
			$user = get_userdata($user_id);
			$keys = array('b2bking_regular_price_user_'.$user_id, 'b2bking_sale_price_user_'.$user_id, 'b2bking_product_pricetiers_user_'.$user_id);
			if ($user) {
				$keys[] = 'b2bking_regular_price_user_'.$user->user_login;
				$keys[] = 'b2bking_sale_price_user_'.$user->user_login;
				$keys[] = 'b2bking_product_pricetiers_user_'.$user->user_login;
			}
			$placeholders = implode(',', array_fill(0, count($keys), '%s'));
			$where = call_user_func_array(array($wpdb, 'prepare'), array_merge(array("pm.meta_key IN ($placeholders) AND pm.meta_value != ''"), $keys));
			$join = "INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID";
		}

		$status = "p.post_status NOT IN ('trash','auto-draft')";
		$total = (int) $wpdb->get_var("SELECT COUNT(DISTINCT p.ID) FROM {$wpdb->posts} p $join WHERE p.post_type IN ($types) AND $status AND $where");
		$products = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT p.ID FROM {$wpdb->posts} p $join WHERE p.post_type IN ($types) AND $status AND $where ORDER BY p.post_title ASC LIMIT %d OFFSET %d", $per_page, $offset));
		return array('products' => array_map('intval', $products), 'total' => $total);
	}

	private function render_product_rows($product_ids, $user_id) {
		$currency = get_woocommerce_currency_symbol();
		?>
		<div class="b2bking-customer-pricing-row b2bking-customer-pricing-head">
			<span><?php esc_html_e('Product', 'b2bking'); ?></span><span><?php echo esc_html__('Regular Price', 'b2bking').' ('.esc_html($currency).')'; ?></span><span><?php echo esc_html__('Sale Price', 'b2bking').' ('.esc_html($currency).')'; ?></span><span><?php esc_html_e('Actions', 'b2bking'); ?></span>
		</div>
		<?php
		if (empty($product_ids)) {
			echo '<div class="b2bking-crm-empty-state">'.esc_html__('No customer-specific prices found.', 'b2bking').'</div>';
			return;
		}
		foreach ($product_ids as $product_id) {
			$product = wc_get_product($product_id);
			if (!$product) {
				continue;
			}
			$prices = b2bking()->get_user_product_prices($product_id, $user_id);
			$tiers = b2bking()->get_user_product_tiers($product_id, $user_id);
			$tiers_count = count(array_filter(explode(';', $tiers)));
			$woo_regular = get_post_meta($product_id, '_regular_price', true);
			$woo_sale = get_post_meta($product_id, '_sale_price', true);
			$group_id = b2bking()->get_user_group($user_id);
			$group_regular = get_post_meta($product_id, 'b2bking_regular_product_price_group_'.$group_id, true);
			$group_sale = get_post_meta($product_id, 'b2bking_sale_product_price_group_'.$group_id, true);
			$details = array();
			if ($product->get_sku() !== '') {
				$details[] = esc_html__('SKU', 'b2bking').': '.$product->get_sku();
			}
			$details[] = esc_html__('Woo Regular', 'b2bking').' ('.$currency.'): '.($woo_regular !== '' ? $woo_regular : '-');
			$details[] = esc_html__('Woo Sale', 'b2bking').' ('.$currency.'): '.($woo_sale !== '' ? $woo_sale : '-');
			$details[] = esc_html__('Group Regular', 'b2bking').' ('.$currency.'): '.($group_regular !== '' ? $group_regular : '-');
			$details[] = esc_html__('Group Sale', 'b2bking').' ('.$currency.'): '.($group_sale !== '' ? $group_sale : '-');
			$tooltip = implode('<br>', array_map('esc_html', $details));
			?>
			<div class="b2bking-customer-pricing-row" data-product-id="<?php echo esc_attr($product_id); ?>" data-user-id="<?php echo esc_attr($user_id); ?>">
				<span class="b2bking-customer-pricing-product"><a href="<?php echo esc_url(get_edit_post_link($product_id)); ?>"><?php echo esc_html($product->get_name()); ?></a><span class="b2bking-customer-pricing-tip" data-tippy-content="<?php echo esc_attr($tooltip); ?>">?</span></span>
				<span><input type="text" class="b2bking-customer-regular short wc_input_price" value="<?php echo esc_attr($prices['regular']); ?>"></span>
				<span><input type="text" class="b2bking-customer-sale short wc_input_price" value="<?php echo esc_attr($prices['sale']); ?>"></span>
				<span class="b2bking-customer-pricing-actions"><button type="button" class="button button-small b2bking-customer-pricing-tiers-toggle"><?php echo esc_html($tiers_count ? sprintf(esc_html__('Tiers (%s)', 'b2bking'), $tiers_count) : esc_html__('Tiers', 'b2bking')); ?></button><button type="button" class="button button-small b2bking-customer-price-save"><?php esc_html_e('Save', 'b2bking'); ?></button><button type="button" class="button button-small b2bking-customer-price-clear" title="<?php esc_attr_e('Remove prices', 'b2bking'); ?>" aria-label="<?php esc_attr_e('Remove prices', 'b2bking'); ?>">&times;</button><span class="b2bking-customer-price-status"></span></span>
			</div>
			<?php $this->render_tiers_panel($product_id, $user_id); ?>
			<?php
		}
		?>
		<div class="b2bking-customer-pricing-footer">
			<button type="button" class="button button-primary b2bking-customer-pricing-save-all"><?php esc_html_e('Save All', 'b2bking'); ?></button>
			<span class="b2bking-customer-pricing-save-all-status"></span>
		</div>
		<?php
	}

	private function render_customer_rows($product_id) {
		global $wpdb;
		$rows = $wpdb->get_results($wpdb->prepare("SELECT meta_key FROM {$wpdb->postmeta} WHERE post_id = %d AND (meta_key LIKE %s OR meta_key LIKE %s OR meta_key LIKE %s) AND meta_value != ''", $product_id, $wpdb->esc_like('b2bking_regular_price_user_').'%', $wpdb->esc_like('b2bking_sale_price_user_').'%', $wpdb->esc_like('b2bking_product_pricetiers_user_').'%'));
		$users = array();
		foreach ($rows as $row) {
			$suffix = str_replace(array('b2bking_regular_price_user_', 'b2bking_sale_price_user_', 'b2bking_product_pricetiers_user_'), '', $row->meta_key);
			$user = is_numeric($suffix) ? get_userdata((int) $suffix) : get_user_by('login', $suffix);
			if ($user) {
				$users[$user->ID] = $user;
			}
		}
		if (empty($users)) {
			echo '<div class="b2bking-crm-empty-state">'.esc_html__('Search for a customer above to add a customer-specific price for this product.', 'b2bking').'</div>';
			return;
		}
		foreach ($users as $user) {
			$this->render_customer_row($product_id, $user);
		}
	}

	private function count_customers_with_prices($product_id) {
		global $wpdb;
		$rows = $wpdb->get_results($wpdb->prepare("SELECT meta_key FROM {$wpdb->postmeta} WHERE post_id = %d AND (meta_key LIKE %s OR meta_key LIKE %s OR meta_key LIKE %s) AND meta_value != ''", $product_id, $wpdb->esc_like('b2bking_regular_price_user_').'%', $wpdb->esc_like('b2bking_sale_price_user_').'%', $wpdb->esc_like('b2bking_product_pricetiers_user_').'%'));
		$users = array();
		foreach ($rows as $row) {
			$suffix = str_replace(array('b2bking_regular_price_user_', 'b2bking_sale_price_user_', 'b2bking_product_pricetiers_user_'), '', $row->meta_key);
			$user = is_numeric($suffix) ? get_userdata((int) $suffix) : get_user_by('login', $suffix);
			if ($user) {
				$users[$user->ID] = true;
			}
		}
		return count($users);
	}

	private function render_customer_row($product_id, $user) {
		$prices = b2bking()->get_user_product_prices($product_id, $user->ID);
		$tiers = b2bking()->get_user_product_tiers($product_id, $user->ID);
		$tiers_count = count(array_filter(explode(';', $tiers)));
		?>
		<div class="b2bking-product-pricing-row" data-product-id="<?php echo esc_attr($product_id); ?>" data-user-id="<?php echo esc_attr($user->ID); ?>">
			<span><?php echo esc_html($user->display_name.' ('.$user->user_email.')'); ?></span>
			<input type="text" class="b2bking-customer-regular short wc_input_price" value="<?php echo esc_attr($prices['regular']); ?>">
			<input type="text" class="b2bking-customer-sale short wc_input_price" value="<?php echo esc_attr($prices['sale']); ?>">
			<span class="b2bking-customer-pricing-actions"><button type="button" class="button button-small b2bking-customer-pricing-tiers-toggle"><?php echo esc_html($tiers_count ? sprintf(esc_html__('Tiers (%s)', 'b2bking'), $tiers_count) : esc_html__('Tiers', 'b2bking')); ?></button><button type="button" class="button button-small b2bking-customer-price-save"><?php esc_html_e('Save', 'b2bking'); ?></button><button type="button" class="button button-small b2bking-customer-price-clear" title="<?php esc_attr_e('Remove prices', 'b2bking'); ?>" aria-label="<?php esc_attr_e('Remove prices', 'b2bking'); ?>">&times;</button><span class="b2bking-customer-price-status"></span></span>
		</div>
		<?php $this->render_tiers_panel($product_id, $user->ID); ?>
		<?php
	}

	private function render_tiers_panel($product_id, $user_id) {
		$tiers = array_filter(explode(';', b2bking()->get_user_product_tiers($product_id, $user_id)));
		$tier_value_label = get_option('b2bking_enter_percentage_tiered_setting') === '1' ? esc_html__('% Discount', 'b2bking') : esc_html__('Price', 'b2bking').' ('.get_woocommerce_currency_symbol().')';
		?>
		<div class="b2bking-customer-pricing-tiers-row" style="display:none;">
			<div class="b2bking-customer-pricing-tiers">
				<div class="b2bking-customer-pricing-tier-head"><span><?php esc_html_e('Min. Quantity', 'b2bking'); ?></span><span><?php echo esc_html($tier_value_label); ?></span><span></span></div>
				<div class="b2bking-customer-pricing-tier-list">
					<?php foreach ($tiers as $tier) :
						$values = explode(':', $tier);
						if (count($values) < 2) {
							continue;
						}
						?>
						<div class="b2bking-customer-pricing-tier">
							<input type="number" step="any" min="0" class="b2bking-customer-tier-quantity" value="<?php echo esc_attr($values[0]); ?>">
							<input type="text" class="b2bking-customer-tier-price wc_input_price" value="<?php echo esc_attr($values[1]); ?>">
							<button type="button" class="button button-small b2bking-customer-tier-remove">&times;</button>
						</div>
					<?php endforeach; ?>
				</div>
				<button type="button" class="button button-small b2bking-customer-tier-add"><?php esc_html_e('Add Tier', 'b2bking'); ?></button>
			</div>
		</div>
		<?php
	}

	private function render_pager($page, $total, $per_page) {
		if ($total <= $per_page) {
			return;
		}
		$pages = (int) ceil($total / $per_page);
		echo '<div class="b2bking-customer-pricing-pager">';
		echo '<button type="button" class="button button-small b2bking-customer-pricing-page" data-page="'.esc_attr(max(1, $page - 1)).'"'.disabled($page <= 1, true, false).'>'.esc_html__('Previous', 'b2bking').'</button>';
		echo '<span>'.esc_html($page).' / '.esc_html($pages).'</span>';
		echo '<button type="button" class="button button-small b2bking-customer-pricing-page" data-page="'.esc_attr(min($pages, $page + 1)).'"'.disabled($page >= $pages, true, false).'>'.esc_html__('Next', 'b2bking').'</button>';
		echo '</div>';
	}

}

B2BKing_Customer_Pricing_Module::get_instance();
