<?php
namespace AdminLogo;

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

if ( ! isset( $module_id ) ) {
	$module_id = 'admin-logo';
}

$default_settings = [
	'logo_location'               => 'admin_bar_and_menu',
	'admin_bar_logo_url'          => '',
	'admin_bar_logo_size'         => '',
	'admin_menu_logo_url'         => '',
	'admin_menu_logo_width'       => '',
	'use_same_logo_for_menu'      => false,
	'admin_menu_link'             => 'home',
	'admin_menu_link_custom'      => '',
	'admin_menu_link_target'      => 'blank',
	'link_to_dashboard'           => false,
	'replace_admin_bar_home_icon' => false,
];

$settings = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
if ( ! is_array( $settings ) ) {
	$settings = [];
}
$settings = array_merge( $default_settings, $settings );

$logo_location = $settings['logo_location'] ?? 'admin_bar_and_menu';
$use_same_logo = ! empty( $settings['use_same_logo_for_menu'] );
$show_bar_fields = in_array( $logo_location, [ 'admin_bar', 'admin_bar_and_menu' ], true );
$show_same_logo_row = $logo_location === 'admin_bar_and_menu';
$show_menu_fields = in_array( $logo_location, [ 'admin_menu', 'admin_bar_and_menu' ], true ) && ! $use_same_logo;

?>
<div class="wp-powersuite-module-settings">
	<p class="description">
		<?php esc_html_e( 'Replace WordPress branding with your logo in the admin bar, admin menu, or both.', 'wp-powersuite' ); ?>
	</p>

	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>

		<table class="form-table">
			<tbody>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_logo_location' ); ?>">
							<?php esc_html_e( 'Location', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<select id="<?php echo esc_attr( $module_id . '_logo_location' ); ?>"
							name="logo_location"
							class="wp-powersuite-advanced-setting"
							data-setting-key="logo_location">
							<option value="admin_bar" <?php selected( $logo_location, 'admin_bar' ); ?>><?php esc_html_e( 'Admin bar', 'wp-powersuite' ); ?></option>
							<option value="admin_menu" <?php selected( $logo_location, 'admin_menu' ); ?>><?php esc_html_e( 'Admin menu', 'wp-powersuite' ); ?></option>
							<option value="admin_bar_and_menu" <?php selected( $logo_location, 'admin_bar_and_menu' ); ?>><?php esc_html_e( 'Admin bar & admin menu', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description">
							<?php esc_html_e( 'Choose where the logo appears. Combined mode shows the admin bar logo in the toolbar and the menu logo in the left sidebar.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr class="wpps-admin-logo-bar-row" <?php echo $show_bar_fields ? '' : 'style="display:none;"'; ?>>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_admin_bar_logo_url' ); ?>">
							<?php esc_html_e( 'Admin Bar Logo', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<input type="url"
							id="<?php echo esc_attr( $module_id . '_admin_bar_logo_url' ); ?>"
							name="admin_bar_logo_url"
							class="wp-powersuite-advanced-setting regular-text"
							data-setting-key="admin_bar_logo_url"
							value="<?php echo esc_url( $settings['admin_bar_logo_url'] ?? '' ); ?>"
							placeholder="https://example.com/logo.png"
						/>
						<button type="button" class="button" id="<?php echo esc_attr( $module_id . '_upload_admin_bar_logo' ); ?>">
							<?php esc_html_e( 'Select an Image', 'wp-powersuite' ); ?>
						</button>
						<button type="button" class="button wpps-remove-logo-btn" data-target="<?php echo esc_attr( $module_id . '_admin_bar_logo' ); ?>" <?php echo empty( $settings['admin_bar_logo_url'] ) ? 'style="display:none;"' : ''; ?>>
							<?php esc_html_e( 'Remove Logo', 'wp-powersuite' ); ?>
						</button>
						<p class="description">
							<?php esc_html_e( 'Replaces the WordPress logo in the top admin bar.', 'wp-powersuite' ); ?>
						</p>
						<div id="<?php echo esc_attr( $module_id . '_admin_bar_logo_preview' ); ?>" style="margin-top: 10px;">
							<?php if ( ! empty( $settings['admin_bar_logo_url'] ) ) : ?>
								<img src="<?php echo esc_url( $settings['admin_bar_logo_url'] ); ?>" alt="<?php esc_attr_e( 'Admin Bar Logo Preview', 'wp-powersuite' ); ?>" style="max-width: 200px; height: auto; border: 1px solid #ddd; padding: 5px; background: #fff;" />
							<?php endif; ?>
						</div>
					</td>
				</tr>
				<tr class="wpps-admin-logo-bar-row" <?php echo $show_bar_fields ? '' : 'style="display:none;"'; ?>>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_admin_bar_logo_size' ); ?>">
							<?php esc_html_e( 'Admin Bar Logo Size', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<input type="number"
							id="<?php echo esc_attr( $module_id . '_admin_bar_logo_size' ); ?>"
							name="admin_bar_logo_size"
							class="wp-powersuite-advanced-setting small-text"
							data-setting-key="admin_bar_logo_size"
							value="<?php echo esc_attr( $settings['admin_bar_logo_size'] ?? '' ); ?>"
							min="1"
							max="30"
							step="1"
						/>
						<span>px</span>
						<p class="description">
							<?php esc_html_e( 'Logo height and width in pixels (max 30px). Leave blank for 20px.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr class="wpps-admin-logo-menu-same-row" <?php echo $show_same_logo_row ? '' : 'style="display:none;"'; ?>>
					<th scope="row"><?php esc_html_e( 'Shared Logo', 'wp-powersuite' ); ?></th>
					<td>
						<label>
							<input type="checkbox"
								name="use_same_logo_for_menu"
								class="wp-powersuite-advanced-setting"
								data-setting-key="use_same_logo_for_menu"
								value="1"
								<?php checked( $use_same_logo ); ?>
							/>
							<?php esc_html_e( 'Use the admin bar logo for the admin menu as well', 'wp-powersuite' ); ?>
						</label>
					</td>
				</tr>
				<tr class="wpps-admin-logo-menu-row" <?php echo $show_menu_fields ? '' : 'style="display:none;"'; ?>>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_admin_menu_logo_url' ); ?>">
							<?php esc_html_e( 'Admin Menu Logo', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<input type="url"
							id="<?php echo esc_attr( $module_id . '_admin_menu_logo_url' ); ?>"
							name="admin_menu_logo_url"
							class="wp-powersuite-advanced-setting regular-text"
							data-setting-key="admin_menu_logo_url"
							value="<?php echo esc_url( $settings['admin_menu_logo_url'] ?? '' ); ?>"
							placeholder="https://example.com/logo.png"
						/>
						<button type="button" class="button" id="<?php echo esc_attr( $module_id . '_upload_admin_menu_logo' ); ?>">
							<?php esc_html_e( 'Select an Image', 'wp-powersuite' ); ?>
						</button>
						<button type="button" class="button wpps-remove-logo-btn" data-target="<?php echo esc_attr( $module_id . '_admin_menu_logo' ); ?>" <?php echo empty( $settings['admin_menu_logo_url'] ) ? 'style="display:none;"' : ''; ?>>
							<?php esc_html_e( 'Remove Logo', 'wp-powersuite' ); ?>
						</button>
						<p class="description">
							<?php esc_html_e( 'Shown at the top of the left admin menu.', 'wp-powersuite' ); ?>
						</p>
						<div id="<?php echo esc_attr( $module_id . '_admin_menu_logo_preview' ); ?>" style="margin-top: 10px;">
							<?php if ( ! empty( $settings['admin_menu_logo_url'] ) ) : ?>
								<img src="<?php echo esc_url( $settings['admin_menu_logo_url'] ); ?>" alt="<?php esc_attr_e( 'Admin Menu Logo Preview', 'wp-powersuite' ); ?>" style="max-width: 200px; height: auto; border: 1px solid #ddd; padding: 5px; background: #fff;" />
							<?php endif; ?>
						</div>
					</td>
				</tr>
				<tr class="wpps-admin-logo-menu-link-row" <?php echo ( $show_menu_fields || ( in_array( $logo_location, [ 'admin_menu', 'admin_bar_and_menu' ], true ) && $use_same_logo ) ) ? '' : 'style="display:none;"'; ?>>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_admin_menu_link' ); ?>">
							<?php esc_html_e( 'Admin Menu Logo Link', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<select id="<?php echo esc_attr( $module_id . '_admin_menu_link' ); ?>"
							name="admin_menu_link"
							class="wp-powersuite-advanced-setting"
							data-setting-key="admin_menu_link">
							<option value="home" <?php selected( ( $settings['admin_menu_link'] ?? 'home' ) === 'home' ); ?>><?php esc_html_e( 'Home', 'wp-powersuite' ); ?></option>
							<option value="dashboard" <?php selected( ( $settings['admin_menu_link'] ?? '' ) === 'dashboard' ); ?>><?php esc_html_e( 'Dashboard', 'wp-powersuite' ); ?></option>
							<option value="custom" <?php selected( ( $settings['admin_menu_link'] ?? '' ) === 'custom' ); ?>><?php esc_html_e( 'Custom URL', 'wp-powersuite' ); ?></option>
							<option value="none" <?php selected( ( $settings['admin_menu_link'] ?? '' ) === 'none' ); ?>><?php esc_html_e( 'No link', 'wp-powersuite' ); ?></option>
						</select>
						<div id="<?php echo esc_attr( $module_id . '_admin_menu_link_custom_wrap' ); ?>" style="margin-top: 8px; <?php echo ( $settings['admin_menu_link'] ?? '' ) === 'custom' ? '' : 'display:none;'; ?>">
							<input type="url"
								id="<?php echo esc_attr( $module_id . '_admin_menu_link_custom' ); ?>"
								name="admin_menu_link_custom"
								class="wp-powersuite-advanced-setting regular-text"
								data-setting-key="admin_menu_link_custom"
								value="<?php echo esc_url( $settings['admin_menu_link_custom'] ?? '' ); ?>"
								placeholder="https://example.com"
							/>
						</div>
					</td>
				</tr>
				<tr class="wpps-admin-logo-menu-link-row" <?php echo ( $show_menu_fields || ( in_array( $logo_location, [ 'admin_menu', 'admin_bar_and_menu' ], true ) && $use_same_logo ) ) ? '' : 'style="display:none;"'; ?>>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_admin_menu_link_target' ); ?>">
							<?php esc_html_e( 'Open menu link in', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<select id="<?php echo esc_attr( $module_id . '_admin_menu_link_target' ); ?>"
							name="admin_menu_link_target"
							class="wp-powersuite-advanced-setting"
							data-setting-key="admin_menu_link_target">
							<option value="blank" <?php selected( ( $settings['admin_menu_link_target'] ?? 'blank' ) === 'blank' ); ?>><?php esc_html_e( 'New tab', 'wp-powersuite' ); ?></option>
							<option value="same" <?php selected( ( $settings['admin_menu_link_target'] ?? '' ) === 'same' ); ?>><?php esc_html_e( 'Same tab', 'wp-powersuite' ); ?></option>
						</select>
					</td>
				</tr>
				<tr class="wpps-admin-logo-bar-row" <?php echo $show_bar_fields ? '' : 'style="display:none;"'; ?>>
					<th scope="row"><?php esc_html_e( 'Admin Bar Logo Link', 'wp-powersuite' ); ?></th>
					<td>
						<label>
							<input type="checkbox"
								name="link_to_dashboard"
								class="wp-powersuite-advanced-setting"
								data-setting-key="link_to_dashboard"
								value="1"
								<?php checked( ! empty( $settings['link_to_dashboard'] ) ); ?>
							/>
							<?php esc_html_e( 'Link to dashboard when the admin bar logo is shown on the frontend', 'wp-powersuite' ); ?>
						</label>
						<p class="description">
							<?php esc_html_e( 'When enabled, the admin bar logo links to the dashboard on the frontend. Otherwise it links to your site homepage everywhere.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Site Icon', 'wp-powersuite' ); ?></th>
					<td>
						<label>
							<input type="checkbox"
								name="replace_admin_bar_home_icon"
								class="wp-powersuite-advanced-setting"
								data-setting-key="replace_admin_bar_home_icon"
								value="1"
								<?php checked( ! empty( $settings['replace_admin_bar_home_icon'] ) ); ?>
							/>
							<?php
							printf(
								/* translators: %s: link to Settings → General */
								esc_html__( 'Replace admin bar home icon with the %s', 'wp-powersuite' ),
								'<a href="' . esc_url( admin_url( 'options-general.php' ) ) . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'site icon', 'wp-powersuite' ) . '</a>'
							);
							?>
						</label>
					</td>
				</tr>
			</tbody>
		</table>
	</form>
</div>

<script type="text/javascript">
(function() {
	var adminBarFileFrame, adminMenuFileFrame;
	var moduleId = '<?php echo esc_js( $module_id ); ?>';
	var adminBarButtonId = '#' + moduleId + '_upload_admin_bar_logo';
	var adminMenuButtonId = '#' + moduleId + '_upload_admin_menu_logo';

	function isMediaAvailable() {
		return typeof jQuery !== 'undefined' &&
			typeof wp !== 'undefined' &&
			typeof wp.media !== 'undefined';
	}

	function updateFieldVisibility() {
		if (typeof jQuery === 'undefined') {
			return;
		}

		var $ = jQuery;
		var location = $('#' + moduleId + '_logo_location').val() || 'admin_bar_and_menu';
		var useSame = $('input[data-setting-key="use_same_logo_for_menu"]').is(':checked');

		var showBar = location === 'admin_bar' || location === 'admin_bar_and_menu';
		var showMenuBlock = location === 'admin_menu' || location === 'admin_bar_and_menu';
		var showSameLogo = location === 'admin_bar_and_menu';
		var showMenuFields = showMenuBlock && !useSame;
		var showMenuLinks = showMenuBlock;

		$('.wpps-admin-logo-bar-row').toggle(showBar);
		$('.wpps-admin-logo-menu-same-row').toggle(showSameLogo);
		$('.wpps-admin-logo-menu-row').toggle(showMenuFields);
		$('.wpps-admin-logo-menu-link-row').toggle(showMenuLinks);
	}

	function handleAdminBarLogoClick(e) {
		e.preventDefault();
		e.stopPropagation();

		if (!isMediaAvailable()) {
			alert('<?php echo esc_js( __( 'Media library is not available. Please refresh the page.', 'wp-powersuite' ) ); ?>');
			return false;
		}

		var $ = jQuery;

		if (adminBarFileFrame) {
			adminBarFileFrame.open();
			return false;
		}

		adminBarFileFrame = wp.media({
			title: '<?php echo esc_js( __( 'Select Admin Bar Logo', 'wp-powersuite' ) ); ?>',
			button: { text: '<?php echo esc_js( __( 'Use this image', 'wp-powersuite' ) ); ?>' },
			library: { type: 'image' },
			multiple: false
		});

		adminBarFileFrame.on('select', function() {
			var attachment = adminBarFileFrame.state().get('selection').first().toJSON();
			var $input = $('#' + moduleId + '_admin_bar_logo_url');
			$input.val(attachment.url).trigger('change');

			var preview = $('#' + moduleId + '_admin_bar_logo_preview');
			if (preview.find('img').length) {
				preview.find('img').attr('src', attachment.url);
			} else {
				preview.html('<img src="' + attachment.url + '" alt="<?php echo esc_js( __( 'Admin Bar Logo Preview', 'wp-powersuite' ) ); ?>" style="max-width: 200px; height: auto; border: 1px solid #ddd; padding: 5px; background: #fff;" />');
			}
			$('.wpps-remove-logo-btn[data-target="' + moduleId + '_admin_bar_logo"]').show();
		});

		adminBarFileFrame.open();
		return false;
	}

	function handleAdminMenuLogoClick(e) {
		e.preventDefault();
		e.stopPropagation();

		if (!isMediaAvailable()) {
			alert('<?php echo esc_js( __( 'Media library is not available. Please refresh the page.', 'wp-powersuite' ) ); ?>');
			return false;
		}

		var $ = jQuery;

		if (adminMenuFileFrame) {
			adminMenuFileFrame.open();
			return false;
		}

		adminMenuFileFrame = wp.media({
			title: '<?php echo esc_js( __( 'Select Admin Menu Logo', 'wp-powersuite' ) ); ?>',
			button: { text: '<?php echo esc_js( __( 'Use this image', 'wp-powersuite' ) ); ?>' },
			library: { type: 'image' },
			multiple: false
		});

		adminMenuFileFrame.on('select', function() {
			var attachment = adminMenuFileFrame.state().get('selection').first().toJSON();
			var $input = $('#' + moduleId + '_admin_menu_logo_url');
			$input.val(attachment.url).trigger('change');

			var preview = $('#' + moduleId + '_admin_menu_logo_preview');
			if (preview.find('img').length) {
				preview.find('img').attr('src', attachment.url);
			} else {
				preview.html('<img src="' + attachment.url + '" alt="<?php echo esc_js( __( 'Admin Menu Logo Preview', 'wp-powersuite' ) ); ?>" style="max-width: 200px; height: auto; border: 1px solid #ddd; padding: 5px; background: #fff;" />');
			}
			$('.wpps-remove-logo-btn[data-target="' + moduleId + '_admin_menu_logo"]').show();
		});

		adminMenuFileFrame.open();
		return false;
	}

	function handleRemoveLogo(e) {
		var $ = jQuery;
		var target = $(e.currentTarget).data('target');
		$('#' + target + '_url').val('').trigger('change');
		$('#' + target + '_preview').empty();
		$(e.currentTarget).hide();
	}

	function initMediaUploader() {
		if (typeof jQuery === 'undefined') {
			setTimeout(initMediaUploader, 100);
			return;
		}

		var $ = jQuery;
		$(document).off('click', adminBarButtonId).on('click', adminBarButtonId, handleAdminBarLogoClick);
		$(document).off('click', adminMenuButtonId).on('click', adminMenuButtonId, handleAdminMenuLogoClick);
		$(document).off('click', '.wpps-remove-logo-btn').on('click', '.wpps-remove-logo-btn', handleRemoveLogo);
		$(document).off('change', '#' + moduleId + '_logo_location').on('change', '#' + moduleId + '_logo_location', updateFieldVisibility);
		$(document).off('change', 'input[data-setting-key="use_same_logo_for_menu"]').on('change', 'input[data-setting-key="use_same_logo_for_menu"]', updateFieldVisibility);
		$(document).off('change', '#' + moduleId + '_admin_menu_link').on('change', '#' + moduleId + '_admin_menu_link', function() {
			$('#' + moduleId + '_admin_menu_link_custom_wrap').toggle($(this).val() === 'custom');
		});

		updateFieldVisibility();
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', initMediaUploader);
	} else {
		initMediaUploader();
	}

	if (typeof jQuery !== 'undefined') {
		jQuery(document).on('wp-powersuite-modal-loaded', function(event) {
			if (event.detail && event.detail.moduleId && event.detail.moduleId !== moduleId) {
				return;
			}

			adminBarFileFrame = null;
			adminMenuFileFrame = null;
			setTimeout(initMediaUploader, 100);
		});
	}
})();
</script>
