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

// ── Helpers ──────────────────────────────────────────────────────────────────

function chcpl_get_white_label() {
	$saved = get_option( 'chcpl_white_label', array() );
	return is_array( $saved ) ? $saved : array();
}

function chcpl_wl_get( $key, $fallback = '' ) {
	$wl = chcpl_get_white_label();
	return ( isset( $wl[ $key ] ) && $wl[ $key ] !== '' ) ? $wl[ $key ] : $fallback;
}

function chcpl_is_white_labeled() {
	if ( ! ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'business' ) ) ) {
		return false;
	}
	$wl = chcpl_get_white_label();
	return ! empty( $wl['enabled'] ) && $wl['enabled'] === '1';
}

// ── Apply white label ─────────────────────────────────────────────────────────

// Plugins list: override name, description, author, author URL
add_filter( 'all_plugins', function( $plugins ) {
	if ( ! chcpl_is_white_labeled() ) {
		return $plugins;
	}
	$basename = plugin_basename( CHCPL_PLUGIN_FILE );
	if ( ! isset( $plugins[ $basename ] ) ) {
		return $plugins;
	}

	$name        = chcpl_wl_get( 'plugin_name' );
	$description = chcpl_wl_get( 'plugin_description' );
	$author      = chcpl_wl_get( 'author_name' );
	$author_url  = chcpl_wl_get( 'author_url' );

	if ( $name ) {
		$plugins[ $basename ]['Name']  = $name;
		$plugins[ $basename ]['Title'] = $name;
	}
	if ( $description ) {
		$plugins[ $basename ]['Description'] = $description;
	}
	if ( $author ) {
		$plugins[ $basename ]['Author']     = '<a href="' . esc_url( $author_url ?: '#' ) . '">' . esc_html( $author ) . '</a>';
		$plugins[ $basename ]['AuthorName'] = $author;
	}
	if ( $author_url ) {
		$plugins[ $basename ]['AuthorURI'] = $author_url;
		$plugins[ $basename ]['PluginURI'] = $author_url;
	}

	return $plugins;
} );

// Top-level admin menu label
add_action( 'admin_menu', function() {
	if ( ! chcpl_is_white_labeled() ) {
		return;
	}
	$custom_name = chcpl_wl_get( 'plugin_name' );
	if ( ! $custom_name ) {
		return;
	}
	global $menu;
	foreach ( $menu as $key => $item ) {
		if ( isset( $item[2] ) && $item[2] === 'edit.php?post_type=price_list' ) {
			$menu[ $key ][0] = esc_html( $custom_name ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
			break;
		}
	}
}, 9999 );

// ── Admin menu ────────────────────────────────────────────────────────────────

function chcpl_add_white_label_page() {
	if ( ! ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'business' ) ) ) {
		return;
	}
	add_submenu_page(
		'edit.php?post_type=price_list',
		__( 'White Label', 'ad-pro-price-list' ),
		__( 'White Label', 'ad-pro-price-list' ),
		'manage_options',
		'chcpl_white_label',
		'chcpl_render_white_label_page'
	);
}
add_action( 'admin_menu', 'chcpl_add_white_label_page' );

// ── Settings page ─────────────────────────────────────────────────────────────

function chcpl_render_white_label_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}

	$saved  = false;
	$errors = array();

	if ( isset( $_POST['chcpl_wl_save'] ) && check_admin_referer( 'chcpl_white_label_save', 'chcpl_wl_nonce' ) ) {
		$wl = array(
			'enabled'            => isset( $_POST['chcpl_wl_enabled'] ) ? '1' : '0',
			'plugin_name'        => sanitize_text_field( wp_unslash( $_POST['chcpl_wl_plugin_name'] ?? '' ) ),
			'plugin_description' => sanitize_text_field( wp_unslash( $_POST['chcpl_wl_plugin_description'] ?? '' ) ),
			'author_name'        => sanitize_text_field( wp_unslash( $_POST['chcpl_wl_author_name'] ?? '' ) ),
			'author_url'         => esc_url_raw( wp_unslash( $_POST['chcpl_wl_author_url'] ?? '' ) ),
		);
		update_option( 'chcpl_white_label', $wl );
		$saved = true;
	}

	$wl = chcpl_get_white_label();
	?>
	<div class="wrap chcpl-admin">
		<h1><?php esc_html_e( 'White Label', 'ad-pro-price-list' ); ?></h1>

		<?php if ( $saved ) : ?>
			<div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'White label settings saved.', 'ad-pro-price-list' ); ?></p></div>
		<?php endif; ?>

		<div class="chcpl-card" style="max-width:680px;margin-top:16px;">
			<h2 class="chcpl-card-title"><?php esc_html_e( 'Branding Settings', 'ad-pro-price-list' ); ?></h2>
			<p class="chcpl-body" style="margin-bottom:16px;">
				<?php esc_html_e( 'When enabled, the plugin\'s branding is replaced with your custom values across the WordPress admin: the Plugins list, the top-level menu label, and the About page.', 'ad-pro-price-list' ); ?>
			</p>

			<form method="post">
				<?php wp_nonce_field( 'chcpl_white_label_save', 'chcpl_wl_nonce' ); ?>

				<table class="form-table" style="margin-top:0;">
					<tbody>
						<tr>
							<th scope="row" style="width:200px;">
								<label for="chcpl_wl_enabled"><?php esc_html_e( 'Enable White Label', 'ad-pro-price-list' ); ?></label>
							</th>
							<td>
								<label>
									<input type="checkbox" name="chcpl_wl_enabled" id="chcpl_wl_enabled" value="1" <?php checked( isset( $wl['enabled'] ) && $wl['enabled'] === '1' ); ?> />
									<?php esc_html_e( 'Hide plugin branding and show custom values below', 'ad-pro-price-list' ); ?>
								</label>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="chcpl_wl_plugin_name"><?php esc_html_e( 'Plugin Name', 'ad-pro-price-list' ); ?></label>
							</th>
							<td>
								<input type="text" name="chcpl_wl_plugin_name" id="chcpl_wl_plugin_name" class="regular-text" value="<?php echo esc_attr( $wl['plugin_name'] ?? '' ); ?>" placeholder="<?php esc_attr_e( 'e.g. My Price Lists', 'ad-pro-price-list' ); ?>" />
								<p class="description"><?php esc_html_e( 'Replaces "AD Pro Price Lists" in the Plugins list and the admin menu.', 'ad-pro-price-list' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="chcpl_wl_plugin_description"><?php esc_html_e( 'Plugin Description', 'ad-pro-price-list' ); ?></label>
							</th>
							<td>
								<input type="text" name="chcpl_wl_plugin_description" id="chcpl_wl_plugin_description" class="regular-text" value="<?php echo esc_attr( $wl['plugin_description'] ?? '' ); ?>" placeholder="<?php esc_attr_e( 'Short description shown in the Plugins list', 'ad-pro-price-list' ); ?>" />
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="chcpl_wl_author_name"><?php esc_html_e( 'Author Name', 'ad-pro-price-list' ); ?></label>
							</th>
							<td>
								<input type="text" name="chcpl_wl_author_name" id="chcpl_wl_author_name" class="regular-text" value="<?php echo esc_attr( $wl['author_name'] ?? '' ); ?>" placeholder="<?php esc_attr_e( 'e.g. My Agency', 'ad-pro-price-list' ); ?>" />
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="chcpl_wl_author_url"><?php esc_html_e( 'Author URL', 'ad-pro-price-list' ); ?></label>
							</th>
							<td>
								<input type="url" name="chcpl_wl_author_url" id="chcpl_wl_author_url" class="regular-text" value="<?php echo esc_attr( $wl['author_url'] ?? '' ); ?>" placeholder="https://" />
							</td>
						</tr>
					</tbody>
				</table>

				<p style="padding-top:8px;margin-bottom:0;">
					<button type="submit" name="chcpl_wl_save" class="chcpl-btn chcpl-btn-green">
						<?php esc_html_e( 'Save White Label Settings', 'ad-pro-price-list' ); ?>
					</button>
				</p>
			</form>
		</div>

		<div class="chcpl-card" style="max-width:680px;background:#fefce8;border-color:#fde047;">
			<p class="chcpl-body" style="margin:0;color:#713f12;">
				<strong><?php esc_html_e( 'Note:', 'ad-pro-price-list' ); ?></strong>
				<?php esc_html_e( 'The plugin file header (visible during updates on WordPress.org-connected sites) cannot be changed dynamically. White label only affects the visible admin UI, not the underlying plugin metadata used for update checks.', 'ad-pro-price-list' ); ?>
			</p>
		</div>
	</div>
	<?php
}
