<?php
namespace CustomLoginLogo;

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

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

$default_settings = [
	'logo_source'    => 'upload',
	'logo_url'       => '',
	'logo_width'     => 200,
	'logo_height'    => 80,
	'logo_size_mode' => 'contain',
];

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

$logo_source   = in_array( $settings['logo_source'] ?? 'upload', [ 'upload', 'site_icon' ], true )
	? ( $settings['logo_source'] ?? 'upload' )
	: 'upload';
$site_icon_url = get_site_icon_url( 512 );
$customizor_on = OptionStoreModuleSettingsRepository::isModuleEnabled( 'login-page-customizor' );

?>
<div class="wp-powersuite-module-settings">
	<p class="description">
		<?php esc_html_e( 'Replace the WordPress logo on the login page with your site icon or a custom image. Enable Custom Login Logo Link separately to control where the logo click goes.', 'wp-powersuite' ); ?>
	</p>

	<?php if ( $customizor_on ) : ?>
		<div class="notice notice-warning inline" style="margin: 0 0 16px 0;">
			<p>
				<?php esc_html_e( 'Login Page Customizer (Pro) is enabled. If its Form Customization logo settings are active, they take priority over this module.', 'wp-powersuite' ); ?>
			</p>
		</div>
	<?php endif; ?>

	<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_source' ); ?>">
							<?php esc_html_e( 'Logo Source:', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<select id="<?php echo esc_attr( $module_id . '_logo_source' ); ?>"
							name="logo_source"
							class="wp-powersuite-advanced-setting"
							data-setting-key="logo_source">
							<option value="upload" <?php selected( $logo_source, 'upload' ); ?>><?php esc_html_e( 'Media Library', 'wp-powersuite' ); ?></option>
							<option value="site_icon" <?php selected( $logo_source, 'site_icon' ); ?>><?php esc_html_e( 'Site Icon', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description">
							<?php esc_html_e( 'Use your Site Icon from Settings → General, or upload a dedicated login logo.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
				<tr class="wpps-custom-login-logo-upload-row" <?php echo $logo_source === 'upload' ? '' : 'style="display:none;"'; ?>>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_logo_url' ); ?>">
							<?php esc_html_e( 'Logo URL:', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<input type="url"
							id="<?php echo esc_attr( $module_id . '_logo_url' ); ?>"
							name="logo_url"
							class="wp-powersuite-advanced-setting regular-text"
							data-setting-key="logo_url"
							value="<?php echo esc_url( $settings['logo_url'] ?? '' ); ?>"
							placeholder="https://example.com/logo.png"
						/>
						<button type="button" class="button" id="<?php echo esc_attr( $module_id . '_upload_logo' ); ?>">
							<?php esc_html_e( 'Upload Logo', 'wp-powersuite' ); ?>
						</button>
						<p class="description">
							<?php esc_html_e( 'Use "Upload Logo" to select from the media library. Only URLs from your site (uploads, content) are accepted for security.', 'wp-powersuite' ); ?>
						</p>
						<?php if ( ! empty( $settings['logo_url'] ) ) : ?>
							<p class="wpps-custom-login-logo-preview" style="margin-top: 10px;">
								<img src="<?php echo esc_url( $settings['logo_url'] ); ?>" alt="" style="max-width: 200px; height: auto; border: 1px solid #ddd; padding: 5px;" />
							</p>
						<?php endif; ?>
					</td>
				</tr>
				<tr class="wpps-custom-login-logo-site-icon-row" <?php echo $logo_source === 'site_icon' ? '' : 'style="display:none;"'; ?>>
					<th scope="row"><?php esc_html_e( 'Site Icon:', 'wp-powersuite' ); ?></th>
					<td>
						<?php if ( $site_icon_url ) : ?>
							<p style="margin: 0 0 8px;">
								<img src="<?php echo esc_url( $site_icon_url ); ?>" alt="" style="width: 64px; height: 64px; border-radius: 8px; object-fit: contain; border: 1px solid #ddd; padding: 4px;" />
							</p>
							<p class="description">
								<a href="<?php echo esc_url( admin_url( 'options-general.php' ) ); ?>"><?php esc_html_e( 'Change in Settings → General', 'wp-powersuite' ); ?></a>
							</p>
						<?php else : ?>
							<p class="description">
								<?php esc_html_e( 'No Site Icon is set yet.', 'wp-powersuite' ); ?>
								<a href="<?php echo esc_url( admin_url( 'options-general.php' ) ); ?>"><?php esc_html_e( 'Add one in Settings → General', 'wp-powersuite' ); ?></a>
							</p>
						<?php endif; ?>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_logo_width' ); ?>">
							<?php esc_html_e( 'Logo Width:', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<input type="number"
							id="<?php echo esc_attr( $module_id . '_logo_width' ); ?>"
							name="logo_width"
							class="wp-powersuite-advanced-setting"
							data-setting-key="logo_width"
							value="<?php echo esc_attr( $settings['logo_width'] ?? 200 ); ?>"
							min="50"
							max="500"
							step="10"
						/>
						<span><?php esc_html_e( 'pixels', 'wp-powersuite' ); ?></span>
						<p class="description"><?php esc_html_e( 'Maximum display width of your logo.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_logo_height' ); ?>">
							<?php esc_html_e( 'Logo Height:', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<input type="number"
							id="<?php echo esc_attr( $module_id . '_logo_height' ); ?>"
							name="logo_height"
							class="wp-powersuite-advanced-setting"
							data-setting-key="logo_height"
							value="<?php echo esc_attr( $settings['logo_height'] ?? 80 ); ?>"
							min="30"
							max="200"
							step="10"
						/>
						<span><?php esc_html_e( 'pixels', 'wp-powersuite' ); ?></span>
						<p class="description"><?php esc_html_e( 'Maximum display height of your logo.', 'wp-powersuite' ); ?></p>
					</td>
				</tr>
				<tr class="wpps-custom-login-logo-site-icon-size-row" <?php echo $logo_source === 'site_icon' ? '' : 'style="display:none;"'; ?>>
					<th scope="row">
						<label for="<?php echo esc_attr( $module_id . '_logo_size_mode' ); ?>">
							<?php esc_html_e( 'Size Mode:', 'wp-powersuite' ); ?>
						</label>
					</th>
					<td>
						<select id="<?php echo esc_attr( $module_id . '_logo_size_mode' ); ?>"
							name="logo_size_mode"
							class="wp-powersuite-advanced-setting"
							data-setting-key="logo_size_mode">
							<option value="contain" <?php selected( ( $settings['logo_size_mode'] ?? 'contain' ) === 'contain' ); ?>><?php esc_html_e( 'Contain (preserve aspect ratio)', 'wp-powersuite' ); ?></option>
							<option value="fixed" <?php selected( ( $settings['logo_size_mode'] ?? '' ) === 'fixed' ); ?>><?php esc_html_e( 'Fixed (exact dimensions)', 'wp-powersuite' ); ?></option>
						</select>
						<p class="description">
							<?php esc_html_e( 'Applies when using the Site Icon as the login logo.', 'wp-powersuite' ); ?>
						</p>
					</td>
				</tr>
			</tbody>
		</table>
	</form>
</div>

<script type="text/javascript">
(function() {
	var fileFrame;
	var moduleId = '<?php echo esc_js( $module_id ); ?>';
	var buttonId = '#' + moduleId + '_upload_logo';
	var inputId = '#' + moduleId + '_logo_url';
	var sourceId = '#' + moduleId + '_logo_source';

	function toggleLogoSourceRows() {
		var source = document.querySelector(sourceId);
		if (!source) return;
		var isUpload = source.value === 'upload';
		document.querySelectorAll('.wpps-custom-login-logo-upload-row').forEach(function(row) {
			row.style.display = isUpload ? '' : 'none';
		});
		document.querySelectorAll('.wpps-custom-login-logo-site-icon-row, .wpps-custom-login-logo-site-icon-size-row').forEach(function(row) {
			row.style.display = isUpload ? 'none' : '';
		});
	}

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

		var $ = jQuery;

		$(document).off('change', sourceId).on('change', sourceId, toggleLogoSourceRows);

		$(document).off('click', buttonId).on('click', buttonId, function(e) {
			e.preventDefault();
			e.stopPropagation();

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

			fileFrame = wp.media({
				title: '<?php esc_html_e( 'Select Logo', 'wp-powersuite' ); ?>',
				button: {
					text: '<?php esc_html_e( 'Use this logo', 'wp-powersuite' ); ?>'
				},
				library: {
					type: 'image'
				},
				multiple: false
			});

			fileFrame.on('select', function() {
				var attachment = fileFrame.state().get('selection').first().toJSON();
				$(inputId).val(attachment.url);

				var preview = $(inputId).closest('td').find('.wpps-custom-login-logo-preview img');
				if (preview.length) {
					preview.attr('src', attachment.url);
				} else {
					$(inputId).closest('td').append('<p class="wpps-custom-login-logo-preview" style="margin-top: 10px;"><img src="' + attachment.url + '" alt="" style="max-width: 200px; height: auto; border: 1px solid #ddd; padding: 5px;" /></p>');
				}
			});

			fileFrame.open();
			return false;
		});
	}

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

	if (typeof jQuery !== 'undefined') {
		jQuery(document).on('wp-powersuite-modal-loaded', function() {
			fileFrame = null;
			setTimeout(function() {
				toggleLogoSourceRows();
				initMediaUploader();
			}, 100);
		});
	}
})();
</script>
