<?php
// phpcs:disable WordPress.DB.SlowDBQuery
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// ── Plan-awareness helpers ────────────────────────────────────────────────────

function chcpl_upgrade_url() {
	if ( function_exists( 'appl_fs' ) ) {
		try {
			return appl_fs()->get_upgrade_url();
		} catch ( Exception $e ) {
			return '#';
		}
	}
	return '#';
}

function chcpl_admin_plan_notices() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$screen = get_current_screen();
	if ( ! $screen ) {
		return;
	}

	$is_free         = function_exists( 'chcpl_is_free' ) && chcpl_is_free();
	$is_solo_not_pro = ! $is_free && function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'solo' ) && ! chcpl_is_plan( 'pro' );
	$upgrade_url     = chcpl_upgrade_url();

	if ( $is_free ) {
		$free_cta = sprintf(
			' <a href="%s" class="button button-small" style="margin-left:8px;vertical-align:baseline;">%s</a>',
			esc_url( $upgrade_url ),
			esc_html__( 'Upgrade Now!', 'ad-pro-price-list' )
		);

		if ( $screen->id === 'edit-price_list' ) {
			printf(
				'<div class="notice notice-info" style="border-left-color:#2563eb;"><p><strong>%s</strong> %s%s</p></div>',
				esc_html__( 'Free plan:', 'ad-pro-price-list' ),
				esc_html__( 'Only your first price list renders on the frontend. Upgrade to Pro for unlimited price lists, category icons, custom display order, and the quote requests dashboard.', 'ad-pro-price-list' ),
				$free_cta // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			);
		}
		if ( $screen->id === 'edit-price_service' ) {
			printf(
				'<div class="notice notice-info" style="border-left-color:#2563eb;"><p><strong>%s</strong> %s%s</p></div>',
				esc_html__( 'Free plan:', 'ad-pro-price-list' ),
				esc_html__( 'Your active list is limited to 5 services. Category icons and custom display order are also Solo+ features.', 'ad-pro-price-list' ),
				$free_cta // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			);
		}
		if ( $screen->id === 'edit-price_category' ) {
			printf(
				'<div class="notice notice-info" style="border-left-color:#2563eb;"><p><strong>%s</strong> %s%s</p></div>',
				esc_html__( 'Free plan:', 'ad-pro-price-list' ),
				esc_html__( 'Category icons and custom display order are Solo+ features.', 'ad-pro-price-list' ),
				$free_cta // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			);
		}
		if ( $screen->id === 'chcpl_global_settings' ) {
			printf(
				'<div class="notice notice-info" style="border-left-color:#2563eb;"><p><strong>%s</strong> %s%s</p></div>',
				esc_html__( 'Free plan:', 'ad-pro-price-list' ),
				esc_html__( 'Access request copy customisation, admin auto-unlock, and global password management are Pro features. Upgrade to unlock password-protected price lists.', 'ad-pro-price-list' ),
				$free_cta // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			);
		}
	}

	if ( $is_solo_not_pro ) {
		$pro_cta = sprintf(
			' <a href="%s" class="button button-small" style="margin-left:8px;vertical-align:baseline;">%s</a>',
			esc_url( $upgrade_url ),
			esc_html__( 'Upgrade Now!', 'ad-pro-price-list' )
		);

		if ( $screen->id === 'price_list' ) {
			printf(
				'<div class="notice notice-info" style="border-left-color:#7c3aed;"><p><strong>%s</strong> %s%s</p></div>',
				esc_html__( 'Pro features available:', 'ad-pro-price-list' ),
				esc_html__( 'Password-protect this list with a fully customisable access block, global password management, and post-submission redirect.', 'ad-pro-price-list' ),
				$pro_cta // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			);
		}
		if ( $screen->id === 'price_service' ) {
			printf(
				'<div class="notice notice-info" style="border-left-color:#7c3aed;"><p><strong>%s</strong> %s%s</p></div>',
				esc_html__( 'Pro feature available:', 'ad-pro-price-list' ),
				esc_html__( 'Add a hover image overlay to this service — shown on desktop when a visitor hovers over the service row.', 'ad-pro-price-list' ),
				$pro_cta // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			);
		}
	}
}
add_action( 'admin_notices', 'chcpl_admin_plan_notices' );

// ── Plan badge (shown on all plugin pages) ────────────────────────────────────

function chcpl_render_plan_badge() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$screen = get_current_screen();
	if ( ! $screen ) {
		return;
	}
	$is_our_page = (
		strpos( $screen->id, 'price_list' )     !== false ||
		strpos( $screen->id, 'price_service' )  !== false ||
		strpos( $screen->id, 'price_category' ) !== false ||
		strpos( $screen->id, 'chcpl_' )         !== false ||
		( isset( $screen->parent_base ) && strpos( $screen->parent_base, 'price_list' ) !== false ) ||
		( isset( $screen->parent_file ) && strpos( $screen->parent_file, 'price_list' ) !== false )
	);
	if ( ! $is_our_page ) {
		return;
	}

	$is_free = function_exists( 'chcpl_is_free' ) && chcpl_is_free();
	$is_pro  = function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'pro' );
	$is_biz  = function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'business' );
	$is_solo = ! $is_free && ! $is_pro && ! $is_biz;

	if ( $is_biz ) {
		$label = __( 'Business Plan', 'ad-pro-price-list' );
		$class = 'chcpl-badge-biz';
	} elseif ( $is_pro ) {
		$label = __( 'Pro Plan', 'ad-pro-price-list' );
		$class = 'chcpl-badge-pro';
	} elseif ( $is_solo ) {
		$label = __( 'Solo Plan', 'ad-pro-price-list' );
		$class = 'chcpl-badge-solo';
	} else {
		$label = __( 'Free Plan', 'ad-pro-price-list' );
		$class = 'chcpl-badge-solo';
	}

	printf(
		'<div style="margin:8px 0 -8px;"><span class="chcpl-badge %s">%s</span></div>',
		esc_attr( $class ),
		esc_html( $label )
	);
}
add_action( 'admin_notices', 'chcpl_render_plan_badge' );

// ── Shared admin styles ───────────────────────────────────────────────────────

function chcpl_enqueue_admin_styles( $hook ) {
	$screen = get_current_screen();
	if ( ! $screen ) {
		return;
	}
	$is_our_page = (
		strpos( $screen->id, 'price_list' )     !== false ||
		strpos( $screen->id, 'price_service' )  !== false ||
		strpos( $screen->id, 'price_category' ) !== false ||
		strpos( $screen->id, 'chcpl_' )         !== false ||
		( isset( $screen->parent_base ) && strpos( $screen->parent_base, 'price_list' ) !== false ) ||
		( isset( $screen->parent_file ) && strpos( $screen->parent_file, 'price_list' ) !== false )
	);
	if ( ! $is_our_page ) {
		return;
	}
	wp_enqueue_style(
		'chcpl-admin',
		plugins_url( 'assets/css/admin.css', CHCPL_PLUGIN_FILE ),
		array(),
		CHCPL_VERSION
	);
}
add_action( 'admin_enqueue_scripts', 'chcpl_enqueue_admin_styles' );

// Fix side-column gap on price_list edit screen
function chcpl_fix_pricelist_editor_layout() {
	$screen = get_current_screen();
	if ( ! $screen || $screen->id !== 'price_list' ) {
		return;
	}
	echo '<style>#post-body.columns-2 #postbox-container-2 { padding-top: 0 !important; }</style>';
}
add_action( 'admin_head', 'chcpl_fix_pricelist_editor_layout' );

// Redirect to price list index after creating a new price list
function chcpl_redirect_after_new_pricelist( $location, $post_id ) {
	$post = get_post( $post_id );
	if ( ! $post || $post->post_type !== 'price_list' ) {
		return $location;
	}
	// phpcs:ignore WordPress.Security.NonceVerification.Missing
	$original_status = isset( $_POST['original_post_status'] ) ? sanitize_key( wp_unslash( $_POST['original_post_status'] ) ) : '';
	if ( $original_status === 'auto-draft' ) {
		return admin_url( 'edit.php?post_type=price_list' );
	}
	return $location;
}
add_filter( 'redirect_post_location', 'chcpl_redirect_after_new_pricelist', 10, 2 );

// Lock teaser for free/solo users
function chcpl_add_lock_teaser_metabox() {
	if ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'pro' ) ) {
		return;
	}
	add_meta_box(
		'chcpl_list_lock_teaser',
		__( 'Price List Password Lock &amp; Lead Capture', 'ad-pro-price-list' ),
		'chcpl_render_lock_teaser_metabox',
		'price_list',
		'normal',
		'default'
	);
}
add_action( 'add_meta_boxes', 'chcpl_add_lock_teaser_metabox' );

function chcpl_render_lock_teaser_metabox( $post ) {
	$upgrade_url = chcpl_upgrade_url();
	?>
	<div style="max-width:700px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
		<p style="margin:0 0 20px;font-size:13px;color:#535353;line-height:1.65;">
			<?php esc_html_e( 'Lock this price list behind an access request form. Visitors submit their name, company, and email to request access. Every submission is saved to your Submissions dashboard for follow-up. No third-party form plugin needed.', 'ad-pro-price-list' ); ?>
		</p>

		<div style="display:inline-flex;gap:32px;margin-bottom:20px;align-items:flex-start;">
			<div style="white-space:nowrap;">
				<p style="margin:0 0 8px;font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#000;">
					<?php esc_html_e( 'Access control', 'ad-pro-price-list' ); ?>
				</p>
				<ul style="margin:0 0 0 1.2em;list-style:disc;color:#535353;font-size:13px;line-height:1.85;white-space:normal;">
					<li><?php esc_html_e( 'Password-protect with a custom lock screen', 'ad-pro-price-list' ); ?></li>
					<li><?php esc_html_e( 'Global password manager for all your lists', 'ad-pro-price-list' ); ?></li>
					<li><?php esc_html_e( 'Set an expiration date on access', 'ad-pro-price-list' ); ?></li>
					<li><?php esc_html_e( 'Auto-unlock for logged-in admins', 'ad-pro-price-list' ); ?></li>
				</ul>
			</div>
			<div style="padding-left:32px;border-left:1px solid #dedede;white-space:nowrap;">
				<p style="margin:0 0 8px;font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:#000;">
					<?php esc_html_e( 'Lead generation', 'ad-pro-price-list' ); ?>
				</p>
				<ul style="margin:0 0 0 1.2em;list-style:disc;color:#535353;font-size:13px;line-height:1.85;white-space:normal;">
					<li><?php esc_html_e( 'Built-in access request form on the lock screen', 'ad-pro-price-list' ); ?></li>
					<li><?php esc_html_e( 'Captures name, company &amp; email', 'ad-pro-price-list' ); ?></li>
					<li><?php esc_html_e( 'All requests saved to your Submissions dashboard', 'ad-pro-price-list' ); ?></li>
					<li><?php esc_html_e( 'Unread badge so nothing slips through', 'ad-pro-price-list' ); ?></li>
					<li><?php esc_html_e( 'Redirect to a thank-you page after submission', 'ad-pro-price-list' ); ?></li>
				</ul>
			</div>
		</div>

		<a href="<?php echo esc_url( $upgrade_url ); ?>" class="chcpl-btn chcpl-btn-purple">
			<?php esc_html_e( 'Upgrade Now!', 'ad-pro-price-list' ); ?>
		</a>
	</div>
	<?php
}

/* <fs_premium_only> */
// Redirection meta box for Price List — Pro only
function chcpl_add_pricelist_redirect_metabox() {
	if ( ! ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'pro' ) ) ) {
		return;
	}
	add_meta_box(
		'chcpl_pl_redirect',
		__( 'Redirection', 'ad-pro-price-list' ),
		'chcpl_render_pricelist_redirect_metabox',
		'price_list',
		'normal',
		'default'
	);
}
add_action( 'add_meta_boxes', 'chcpl_add_pricelist_redirect_metabox' );

function chcpl_render_pricelist_redirect_metabox( $post ) {
	wp_nonce_field( 'chcpl_save_pricelist_redirect', 'chcpl_pricelist_redirect_nonce' );
	$redirect_enabled = get_post_meta( $post->ID, '_chcpl_redirect_enabled', true ) === '1';
	$redirect_page_id = (int) get_post_meta( $post->ID, '_chcpl_redirect_page_id', true );
	?>
	<p>
		<label style="font-weight:600;">
			<input type="checkbox" name="chcpl_redirect_enabled" value="1" <?php checked( $redirect_enabled ); ?> id="chcpl_redirect_enabled" />
			<?php echo esc_html__( 'Enable redirection after access request submission', 'ad-pro-price-list' ); ?>
		</label>
	</p>
	<p id="chcpl_redirect_page_row" style="<?php echo $redirect_enabled ? '' : 'display:none;'; ?>margin-top:8px;">
		<label for="chcpl_redirect_page_id"><strong><?php echo esc_html__( 'Redirect to page', 'ad-pro-price-list' ); ?></strong></label><br />
		<?php
		wp_dropdown_pages( array(
			'name'              => 'chcpl_redirect_page_id',
			'id'                => 'chcpl_redirect_page_id',
			'selected'          => (int) $redirect_page_id,
			'show_option_none'  => esc_html( __( '— Select a page —', 'ad-pro-price-list' ) ),
			'option_none_value' => '0',
			'post_status'       => array( 'publish', 'draft' ),
		) );
		?>
	</p>
	<script>
	jQuery(document).ready(function($) {
		$('#chcpl_redirect_enabled').on('change', function() {
			$('#chcpl_redirect_page_row').toggle(this.checked);
		});
	});
	</script>
	<?php
}

function chcpl_save_pricelist_redirect( $post_id, $post ) {
	if ( $post->post_type !== 'price_list' ) {
		return;
	}
	if ( ! isset( $_POST['chcpl_pricelist_redirect_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['chcpl_pricelist_redirect_nonce'] ) ), 'chcpl_save_pricelist_redirect' ) ) {
		return;
	}
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}

	$redirect_enabled = isset( $_POST['chcpl_redirect_enabled'] ) ? '1' : '';
	$redirect_page_id = isset( $_POST['chcpl_redirect_page_id'] ) ? (int) $_POST['chcpl_redirect_page_id'] : 0;

	if ( $redirect_enabled ) {
		update_post_meta( $post_id, '_chcpl_redirect_enabled', '1' );
	} else {
		delete_post_meta( $post_id, '_chcpl_redirect_enabled' );
	}
	if ( $redirect_page_id > 0 ) {
		update_post_meta( $post_id, '_chcpl_redirect_page_id', $redirect_page_id );
	} else {
		delete_post_meta( $post_id, '_chcpl_redirect_page_id' );
	}
}
add_action( 'save_post', 'chcpl_save_pricelist_redirect', 10, 2 );
/* </fs_premium_only> */

// Add Shortcode column to Price Lists list table
function chcpl_price_list_columns( $columns ) {
	$insertion = array(
		'chcpl_shortcode' => __( 'Shortcode', 'ad-pro-price-list' ),
	);
	// Insert after title
	$new = array();
	foreach ( $columns as $key => $label ) {
		$new[ $key ] = $label;
		if ( 'title' === $key ) {
			$new = array_merge( $new, $insertion );
		}
	}
	return $new;
}
add_filter( 'manage_edit-price_list_columns', 'chcpl_price_list_columns' );

function chcpl_price_list_custom_column( $column, $post_id ) {
	if ( 'chcpl_shortcode' === $column ) {
		$shortcode = '[comhit_pricelist id="' . (int) $post_id . '"]';
		echo '<code>' . esc_html( $shortcode ) . '</code>';
	}
}
add_action( 'manage_price_list_posts_custom_column', 'chcpl_price_list_custom_column', 10, 2 );

// Metabox on Price List edit screen showing the shortcode
function chcpl_add_pricelist_metabox() {
	add_meta_box(
		'chcpl_pl_shortcode',
		__( 'Shortcode', 'ad-pro-price-list' ),
		'chcpl_render_pricelist_shortcode_metabox',
		'price_list',
		'side',
		'high'
	);
}
add_action( 'add_meta_boxes', 'chcpl_add_pricelist_metabox' );

function chcpl_render_pricelist_shortcode_metabox( $post ) {
	$shortcode = '[comhit_pricelist id="' . (int) $post->ID . '"]';
	echo '<p>' . esc_html__( 'Use this shortcode to display this price list:', 'ad-pro-price-list' ) . '</p>';
	echo '<p><code style="user-select:all;">' . esc_html( $shortcode ) . '</code></p>';
}

// Add Categories submenu under Price Lists (links to taxonomy management)
function chcpl_admin_menu() {
	add_submenu_page(
		'edit.php?post_type=price_list',
		__( 'Service Categories', 'ad-pro-price-list' ),
		__( 'Categories', 'ad-pro-price-list' ),
		'manage_categories',
		'edit-tags.php?taxonomy=price_category&post_type=price_service'
	);
	add_submenu_page(
		'edit.php?post_type=price_list',
		__( 'About AD Pro Price Lists', 'ad-pro-price-list' ),
		__( 'About', 'ad-pro-price-list' ),
		'manage_options',
		'chcpl-about',
		'chcpl_render_about_page'
	);
}
add_action( 'admin_menu', 'chcpl_admin_menu' );

function chcpl_reorder_submenu() {
	global $submenu;
	$key = 'edit.php?post_type=price_list';
	if ( empty( $submenu[ $key ] ) ) {
		return;
	}
	$about_item = null;
	$about_index = null;
	foreach ( $submenu[ $key ] as $index => $item ) {
		if ( isset( $item[2] ) && $item[2] === 'chcpl-about' ) {
			$about_item  = $item;
			$about_index = $index;
			break;
		}
	}
	if ( $about_item === null ) {
		return;
	}
	unset( $submenu[ $key ][ $about_index ] );
	array_unshift( $submenu[ $key ], $about_item );
}
add_action( 'admin_menu', 'chcpl_reorder_submenu', 999 );

function chcpl_render_about_page() {
	$plugin_data = get_plugin_data( CHCPL_PLUGIN_FILE );

	$wl_active  = function_exists( 'chcpl_is_white_labeled' ) && chcpl_is_white_labeled();
	$name       = $wl_active && function_exists( 'chcpl_wl_get' ) && chcpl_wl_get( 'plugin_name' )
		? chcpl_wl_get( 'plugin_name' ) : $plugin_data['Name'];
	$author     = $wl_active && function_exists( 'chcpl_wl_get' ) && chcpl_wl_get( 'author_name' )
		? chcpl_wl_get( 'author_name' ) : $plugin_data['AuthorName'];
	$author_url = $wl_active && function_exists( 'chcpl_wl_get' ) && chcpl_wl_get( 'author_url' )
		? chcpl_wl_get( 'author_url' ) : $plugin_data['AuthorURI'];

	$upgrade_url = chcpl_upgrade_url();

	$checkmark = '<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg" style="flex-shrink:0;margin-top:2px;"><circle cx="7" cy="7" r="7" fill="#81c424"/><path d="M3.5 7L5.8 9.5L10.5 4.5" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';

	$author_url_display = preg_replace( '#^https?://#', '', rtrim( $author_url, '/' ) );

	$plans = array(
		array(
			'badge'       => __( 'Essential', 'ad-pro-price-list' ),
			'badge_class' => 'chcpl-badge-solo',
			'border'      => '#2563eb',
			'tagline'     => __( 'For freelancers and small businesses presenting their own pricing.', 'ad-pro-price-list' ),
			'sections'    => array(
				array(
					'title'    => __( 'Price List Display', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Shortcode [comhit_pricelist id="123"] — embed anywhere', 'ad-pro-price-list' ),
						__( 'Services grouped by category with custom display order', 'ad-pro-price-list' ),
						__( 'Category icons (optional image per category)', 'ad-pro-price-list' ),
						__( 'Per-service: title, description, price, Sur devis toggle', 'ad-pro-price-list' ),
						__( 'Price suffix (HT, TTC, etc.)', 'ad-pro-price-list' ),
					),
				),
				array(
					'title'    => __( 'Inquiry Modal', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Quote request button per service', 'ad-pro-price-list' ),
						__( 'Fields: name, company, email, message', 'ad-pro-price-list' ),
						__( 'Email to admin with Reply-To header', 'ad-pro-price-list' ),
						__( 'Requests stored in DB with full dashboard', 'ad-pro-price-list' ),
					),
				),
				array(
					'title'    => __( 'Admin', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Price Lists, Services, Categories management', 'ad-pro-price-list' ),
						__( 'Quote Requests dashboard with bulk actions', 'ad-pro-price-list' ),
						__( 'Global Settings (price suffix)', 'ad-pro-price-list' ),
					),
				),
				array(
					'title'    => __( 'Security', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Nonce verification on all forms', 'ad-pro-price-list' ),
						__( 'Honeypot + rate limiting on public endpoints', 'ad-pro-price-list' ),
						__( 'Full input sanitization & output escaping', 'ad-pro-price-list' ),
					),
				),
			),
		),
		array(
			'badge'       => __( 'Professional', 'ad-pro-price-list' ),
			'badge_class' => 'chcpl-badge-pro',
			'border'      => '#7c3aed',
			'tagline'     => __( 'For web agencies building and managing client price lists.', 'ad-pro-price-list' ),
			'sections'    => array(
				array(
					'title'    => __( 'Everything in Essential, plus:', 'ad-pro-price-list' ),
					'features' => array(),
				),
				array(
					'title'    => __( 'Price List Display', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Hover image overlay per service (smart viewport positioning, desktop only)', 'ad-pro-price-list' ),
						__( 'Per-shortcode overrides: max_width, button_bg, button_text', 'ad-pro-price-list' ),
					),
				),
				array(
					'title'    => __( 'Password Lock / Access Block', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Per-list lock with fully customisable copy (surtitle, title, description, button labels)', 'ad-pro-price-list' ),
						__( 'Two-panel lock card: access request form + direct password entry', 'ad-pro-price-list' ),
						__( 'Optional redirect to a WordPress page after successful access request', 'ad-pro-price-list' ),
						__( 'noindex / nofollow injected on locked lists', 'ad-pro-price-list' ),
						__( 'AJAX unlock with chcpl-list-unlocked JS event', 'ad-pro-price-list' ),
					),
				),
				array(
					'title'    => __( 'Global Password Management', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Multiple global passwords, each valid for any locked list', 'ad-pro-price-list' ),
						__( 'Per-password expiry (indefinite or fixed date)', 'ad-pro-price-list' ),
						__( 'Admin auto-unlock with frontend notice banner (toggleable)', 'ad-pro-price-list' ),
					),
				),
				array(
					'title'    => __( 'Dashboards', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Submissions dashboard: stat cards, filter tabs, bulk actions, pagination', 'ad-pro-price-list' ),
						__( 'Unread indicators, colour-coded action buttons, empty states', 'ad-pro-price-list' ),
					),
				),
				array(
					'title'    => __( 'Import / Export', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Export any or all price lists to JSON (lists, services, categories, settings, passwords)', 'ad-pro-price-list' ),
						__( 'Import with draft mode, settings overwrite, title prefix, ID remapping', 'ad-pro-price-list' ),
						__( 'File validation: JSON only, 10 MB max', 'ad-pro-price-list' ),
					),
				),
				array(
					'title'    => __( 'Styling (extended)', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Full CSS custom property set: modal, form fields, lock card, buttons, backdrop, subtext', 'ad-pro-price-list' ),
						__( 'Transparent option on applicable colour fields', 'ad-pro-price-list' ),
					),
				),
			),
		),
		array(
			'badge'       => __( 'Business', 'ad-pro-price-list' ),
			'badge_class' => 'chcpl-badge-biz',
			'border'      => '#059669',
			'tagline'     => __( 'For resellers and large agencies deploying on client infrastructure.', 'ad-pro-price-list' ),
			'sections'    => array(
				array(
					'title'    => __( 'Everything in Professional, plus:', 'ad-pro-price-list' ),
					'features' => array(),
				),
				array(
					'title'    => __( 'White Label', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Plugin branding removed from admin UI (name, author, links)', 'ad-pro-price-list' ),
						__( 'Custom plugin name and branding for client-facing installs', 'ad-pro-price-list' ),
					),
				),
				array(
					'title'    => __( 'Multisite Support', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Network activation with per-site or network-wide settings', 'ad-pro-price-list' ),
					),
				),
				array(
					'title'    => __( 'Priority Support', 'ad-pro-price-list' ),
					'features' => array(
						__( 'Dedicated support queue with faster response SLA', 'ad-pro-price-list' ),
					),
				),
			),
		),
	);
	?>
	<div class="wrap chcpl-about-wrap">

		<div style="display:flex;align-items:center;gap:15px;margin-bottom:24px;padding-top:20px;">
			<?php if ( ! $wl_active ) : ?>
			<img src="<?php echo esc_url( plugins_url( 'assets/images/ad-pro-price-lists-logo.jpg', CHCPL_PLUGIN_FILE ) ); ?>" alt="<?php echo esc_attr( $name ); ?>" style="width:85px;height:85px;border-radius:4px;object-fit:cover;flex-shrink:0;" />
			<?php endif; ?>
			<div>
				<div style="font-size:28px;font-weight:700;color:#000;line-height:1.2;"><?php echo esc_html( $name ); ?></div>
				<div style="font-size:14px;color:#535353;font-weight:500;margin-top:8px;"><?php esc_html_e( 'Versatile Price List Management', 'ad-pro-price-list' ); ?></div>
			</div>
		</div>

		<div class="chcpl-about-cols">

			<div class="chcpl-about-col-left">

				<?php if ( ! $wl_active ) : ?>
				<div style="background:#fff;border:1px solid #dedede;border-radius:4px;padding:25px 20px;box-sizing:border-box;">
					<h3 style="margin:0 0 17px;font-size:13px;font-weight:700;color:#000;">
						<?php
						/* translators: %s: plugin name */
						echo esc_html( sprintf( __( 'What is %s?', 'ad-pro-price-list' ), $name ) );
						?>
					</h3>
					<p style="margin:0;font-size:13px;color:#535353;font-weight:400;line-height:1.65;">
						<?php esc_html_e( 'AD Pro Price Lists lets you create and manage multiple service price lists directly from the WordPress admin. Each price list supports custom service categories, per-service pricing, and a built-in inquiry form modal so visitors can request more information without leaving the page.', 'ad-pro-price-list' ); ?>
					</p>
				</div>
				<?php endif; ?>

				<div style="background:#fff;border:1px solid #dedede;border-radius:4px;padding:25px 20px;box-sizing:border-box;">
					<h3 style="margin:0 0 17px;font-size:13px;font-weight:700;color:#000;"><?php esc_html_e( 'Plugin Information', 'ad-pro-price-list' ); ?></h3>
					<table style="width:100%;border-collapse:collapse;font-size:13px;">
						<tr>
							<td style="padding:8px 0;font-weight:700;color:#000;width:120px;"><?php esc_html_e( 'Version', 'ad-pro-price-list' ); ?></td>
							<td style="padding:8px 0;font-weight:500;color:#000;"><?php echo esc_html( $plugin_data['Version'] ); ?></td>
						</tr>
						<tr style="border-top:1px solid #dedede;">
							<td style="padding:8px 0;font-weight:700;color:#000;"><?php esc_html_e( 'Created by', 'ad-pro-price-list' ); ?></td>
							<td style="padding:8px 0;font-weight:500;color:#000;"><?php echo esc_html( $author ); ?></td>
						</tr>
						<tr style="border-top:1px solid #dedede;">
							<td style="padding:8px 0;font-weight:700;color:#000;"><?php esc_html_e( 'Website', 'ad-pro-price-list' ); ?></td>
							<td style="padding:8px 0;font-weight:500;">
								<a href="<?php echo esc_url( $author_url ); ?>" target="_blank" rel="noopener noreferrer" style="color:#000;text-decoration:none;">
									<?php echo esc_html( $author_url_display ); ?>
								</a>
							</td>
						</tr>
					</table>
				</div>

			</div>

			<div class="chcpl-about-col-right">
				<div style="background:#fff;border:1px solid #dedede;border-top:3px solid #7c3aed;border-radius:4px;padding:25px 20px;box-sizing:border-box;display:flex;flex-direction:column;gap:16px;height:100%;">
					<div>
						<p style="margin:0 0 6px;font-size:13px;font-weight:700;color:#000;"><?php esc_html_e( 'Unlock the full feature set', 'ad-pro-price-list' ); ?></p>
						<p style="margin:0;font-size:13px;color:#535353;line-height:1.65;"><?php esc_html_e( 'Password locks, lead capture dashboards, import/export, white label, and more — available on Professional and Business plans.', 'ad-pro-price-list' ); ?></p>
					</div>
					<div>
						<a href="<?php echo esc_url( $upgrade_url ); ?>" class="chcpl-btn chcpl-btn-purple">
							<?php esc_html_e( 'Upgrade Now!', 'ad-pro-price-list' ); ?>
						</a>
					</div>
				</div>
			</div>

		</div>

		<div style="margin-top:20px;">
			<h2 style="font-size:13px;font-weight:700;color:#000;margin:0 0 16px;"><?php esc_html_e( 'Plan Features', 'ad-pro-price-list' ); ?></h2>
			<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;align-items:start;">
				<?php foreach ( $plans as $plan ) : ?>
				<div style="background:#fff;border:1px solid #dedede;border-top:3px solid <?php echo esc_attr( $plan['border'] ); ?>;border-radius:4px;padding:20px;box-sizing:border-box;">
					<div style="margin-bottom:14px;">
						<span class="chcpl-badge <?php echo esc_attr( $plan['badge_class'] ); ?>"><?php echo esc_html( $plan['badge'] ); ?></span>
						<p style="margin:8px 0 0;font-size:12px;color:#6b7280;line-height:1.5;"><?php echo esc_html( $plan['tagline'] ); ?></p>
					</div>
					<?php foreach ( $plan['sections'] as $section ) : ?>
					<div style="margin-top:14px;">
						<p style="margin:0 0 6px;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#374151;"><?php echo esc_html( $section['title'] ); ?></p>
						<?php if ( ! empty( $section['features'] ) ) : ?>
						<div style="display:flex;flex-direction:column;gap:6px;">
							<?php foreach ( $section['features'] as $feature ) : ?>
							<div style="display:flex;align-items:flex-start;gap:8px;font-size:12px;color:#535353;line-height:1.5;">
								<?php echo $checkmark; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
								<?php echo esc_html( $feature ); ?>
							</div>
							<?php endforeach; ?>
						</div>
						<?php endif; ?>
					</div>
					<?php endforeach; ?>
				</div>
				<?php endforeach; ?>
			</div>
		</div>

	</div>
	<?php
}

// Keep the Price Lists menu open when on the Categories taxonomy page
function chcpl_fix_category_menu_parent( $parent_file ) {
	global $pagenow;
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( $pagenow === 'edit-tags.php' && isset( $_GET['taxonomy'] ) && sanitize_key( wp_unslash( $_GET['taxonomy'] ) ) === 'price_category' ) {
		$parent_file = 'edit.php?post_type=price_list';
	}
	return $parent_file;
}
add_filter( 'parent_file', 'chcpl_fix_category_menu_parent' );

function chcpl_fix_category_submenu_file( $submenu_file ) {
	global $pagenow;
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	if ( $pagenow === 'edit-tags.php' && isset( $_GET['taxonomy'] ) && sanitize_key( wp_unslash( $_GET['taxonomy'] ) ) === 'price_category' ) {
		$submenu_file = 'edit-tags.php?taxonomy=price_category&post_type=price_service';
	}
	return $submenu_file;
}
add_filter( 'submenu_file', 'chcpl_fix_category_submenu_file' );

/* <fs_premium_only> */
// Add Order/Icon fields to category forms — Solo+ only
function chcpl_add_category_order_field_add() {
	if ( ! ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'solo' ) ) ) {
		return;
	}
	wp_enqueue_media(); // Enqueue media scripts for icon uploader
	?>
	<div class="form-field term-order-wrap">
		<label for="chcpl_category_order"><?php echo esc_html__( 'Display Order', 'ad-pro-price-list' ); ?></label>
		<input type="number" name="chcpl_category_order" id="chcpl_category_order" value="0" min="0" step="1" style="width:100px;" />
		<p class="description"><?php echo esc_html__( 'Lower numbers appear first. Leave 0 to use alphabetical order.', 'ad-pro-price-list' ); ?></p>
	</div>
	<div class="form-field term-icon-wrap">
		<label for="chcpl_category_icon"><?php echo esc_html__( 'Category Icon', 'ad-pro-price-list' ); ?></label>
		<input type="hidden" name="chcpl_category_icon" id="chcpl_category_icon" value="" />
		<div id="chcpl_category_icon_preview" style="margin:10px 0;">
		</div>
		<button type="button" class="button" id="chcpl_upload_category_icon_btn"><?php echo esc_html__( 'Select Icon', 'ad-pro-price-list' ); ?></button>
		<button type="button" class="button" id="chcpl_remove_category_icon_btn" style="margin-left:5px;display:none;"><?php echo esc_html__( 'Remove Icon', 'ad-pro-price-list' ); ?></button>
		<p class="description"><?php echo esc_html__( 'Select an icon to display next to the category title in the price list.', 'ad-pro-price-list' ); ?></p>
	</div>
	<script>
	jQuery(document).ready(function($) {
		var frame;
		$('#chcpl_upload_category_icon_btn').on('click', function(e) {
			e.preventDefault();
			if (frame) { frame.open(); return; }
			frame = wp.media({
				title: '<?php echo esc_js( __( 'Select Category Icon', 'ad-pro-price-list' ) ); ?>',
				button: { text: '<?php echo esc_js( __( 'Use this image', 'ad-pro-price-list' ) ); ?>' },
				multiple: false
			});
			frame.on('select', function() {
				var attachment = frame.state().get('selection').first().toJSON();
				$('#chcpl_category_icon').val(attachment.id);
				$('#chcpl_category_icon_preview').html('<img src="' + attachment.url + '" style="max-width:48px;height:auto;display:block;margin-bottom:10px;" />');
				$('#chcpl_remove_category_icon_btn').show();
			});
			frame.open();
		});
		$('#chcpl_remove_category_icon_btn').on('click', function(e) {
			e.preventDefault();
			$('#chcpl_category_icon').val('');
			$('#chcpl_category_icon_preview').html('');
			$(this).hide();
		});
	});
	</script>
	<?php
}
add_action( 'price_category_add_form_fields', 'chcpl_add_category_order_field_add' );

// Add Order field to category edit form
function chcpl_add_category_order_field_edit( $term ) {
	if ( ! ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'solo' ) ) ) {
		return;
	}
	wp_enqueue_media(); // Enqueue media scripts for icon uploader
	$order = (int) get_term_meta( $term->term_id, '_chcpl_category_order', true );
	$icon_id = (int) get_term_meta( $term->term_id, '_chcpl_category_icon', true );
	$icon_url = $icon_id ? wp_get_attachment_image_url( $icon_id, 'medium' ) : '';
	?>
	<tr class="form-field term-order-wrap">
		<th scope="row">
			<label for="chcpl_category_order"><?php echo esc_html__( 'Display Order', 'ad-pro-price-list' ); ?></label>
		</th>
		<td>
			<input type="number" name="chcpl_category_order" id="chcpl_category_order" value="<?php echo esc_attr( $order ); ?>" min="0" step="1" style="width:100px;" />
			<p class="description"><?php echo esc_html__( 'Lower numbers appear first. Leave 0 to use alphabetical order.', 'ad-pro-price-list' ); ?></p>
		</td>
	</tr>
	<tr class="form-field term-icon-wrap">
		<th scope="row">
			<label for="chcpl_category_icon"><?php echo esc_html__( 'Category Icon', 'ad-pro-price-list' ); ?></label>
		</th>
		<td>
			<input type="hidden" name="chcpl_category_icon" id="chcpl_category_icon" value="<?php echo esc_attr( $icon_id ); ?>" />
			<div id="chcpl_category_icon_preview" style="margin:10px 0;">
				<?php if ( $icon_url ) : ?>
					<img src="<?php echo esc_url( $icon_url ); ?>" style="max-width:48px;height:auto;display:block;margin-bottom:10px;" />
				<?php endif; ?>
			</div>
			<button type="button" class="button" id="chcpl_upload_category_icon_btn"><?php echo esc_html__( 'Select Icon', 'ad-pro-price-list' ); ?></button>
			<?php if ( $icon_id ) : ?>
				<button type="button" class="button" id="chcpl_remove_category_icon_btn" style="margin-left:5px;"><?php echo esc_html__( 'Remove Icon', 'ad-pro-price-list' ); ?></button>
			<?php else : ?>
				<button type="button" class="button" id="chcpl_remove_category_icon_btn" style="margin-left:5px;display:none;"><?php echo esc_html__( 'Remove Icon', 'ad-pro-price-list' ); ?></button>
			<?php endif; ?>
			<p class="description"><?php echo esc_html__( 'Select an icon to display next to the category title in the price list.', 'ad-pro-price-list' ); ?></p>
		</td>
	</tr>
	<script>
	jQuery(document).ready(function($) {
		var frame;
		$('#chcpl_upload_category_icon_btn').on('click', function(e) {
			e.preventDefault();
			if (frame) { frame.open(); return; }
			frame = wp.media({
				title: '<?php echo esc_js( __( 'Select Category Icon', 'ad-pro-price-list' ) ); ?>',
				button: { text: '<?php echo esc_js( __( 'Use this image', 'ad-pro-price-list' ) ); ?>' },
				multiple: false
			});
			frame.on('select', function() {
				var attachment = frame.state().get('selection').first().toJSON();
				$('#chcpl_category_icon').val(attachment.id);
				$('#chcpl_category_icon_preview').html('<img src="' + attachment.url + '" style="max-width:48px;height:auto;display:block;margin-bottom:10px;" />');
				$('#chcpl_remove_category_icon_btn').show();
			});
			frame.open();
		});
		$('#chcpl_remove_category_icon_btn').on('click', function(e) {
			e.preventDefault();
			$('#chcpl_category_icon').val('');
			$('#chcpl_category_icon_preview').html('');
			$(this).hide();
		});
	});
	</script>
	<?php
}
add_action( 'price_category_edit_form_fields', 'chcpl_add_category_order_field_edit' );

// Save category order and icon
function chcpl_save_category_order( $term_id ) {
	if ( ! ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'solo' ) ) ) {
		return;
	}
	// phpcs:disable WordPress.Security.NonceVerification.Missing
	if ( isset( $_POST['chcpl_category_order'] ) ) {
		$order = chcpl_sanitize_category_order( sanitize_text_field( wp_unslash( $_POST['chcpl_category_order'] ) ) );
		update_term_meta( $term_id, '_chcpl_category_order', $order );
	}
	if ( isset( $_POST['chcpl_category_icon'] ) ) {
		$icon_id = (int) sanitize_text_field( wp_unslash( $_POST['chcpl_category_icon'] ) );
	// phpcs:enable
		// Validate that the attachment exists and is an image
		if ( $icon_id > 0 ) {
			$attachment = get_post( $icon_id );
			if ( $attachment && wp_attachment_is_image( $icon_id ) ) {
				update_term_meta( $term_id, '_chcpl_category_icon', $icon_id );
			} else {
				delete_term_meta( $term_id, '_chcpl_category_icon' );
			}
		} else {
			delete_term_meta( $term_id, '_chcpl_category_icon' );
		}
	}
}
add_action( 'created_price_category', 'chcpl_save_category_order' );
add_action( 'edited_price_category', 'chcpl_save_category_order' );
/* </fs_premium_only> */

/* <fs_premium_only> */
// Add Order column to category list table — Solo+ only
function chcpl_category_columns( $columns ) {
	if ( ! ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'solo' ) ) ) {
		return $columns;
	}
	$columns['chcpl_order'] = __( 'Order', 'ad-pro-price-list' );
	return $columns;
}
add_filter( 'manage_edit-price_category_columns', 'chcpl_category_columns' );

// Display order in category list table
function chcpl_category_column_content( $content, $column_name, $term_id ) {
	if ( 'chcpl_order' === $column_name ) {
		$order = (int) get_term_meta( $term_id, '_chcpl_category_order', true );
		$content = $order > 0 ? $order : '—';
	}
	return $content;
}
add_filter( 'manage_price_category_custom_column', 'chcpl_category_column_content', 10, 3 );

// Make Order column sortable
function chcpl_category_sortable_columns( $columns ) {
	$columns['chcpl_order'] = 'chcpl_order';
	return $columns;
}
add_filter( 'manage_edit-price_category_sortable_columns', 'chcpl_category_sortable_columns' );

// Handle sorting by order
function chcpl_category_orderby( $vars ) {
	if ( isset( $vars['orderby'] ) && 'chcpl_order' === $vars['orderby'] ) {
		$vars = array_merge( $vars, array(
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
			'meta_key' => '_chcpl_category_order',
			'orderby' => 'meta_value_num',
		) );
	}
	return $vars;
}
add_filter( 'request', 'chcpl_category_orderby' );
/* </fs_premium_only> */
