<?php
use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

if ( ! \WP_PowerSuite\Core\NetworkScope::canManagePlugin() ) {
	return;
}

if ( ! isset( $module_id ) || empty( $module_id ) ) {
	$module_id = 'default-featured-image';
}

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

$attachment_id = isset( $settings['attachment_id'] ) ? (int) $settings['attachment_id'] : 0;
$preview_url   = '';
$preview_alt   = '';

if ( $attachment_id > 0 && class_exists( \DefaultFeaturedImage\Module::class ) ) {
	$attachment_id = \DefaultFeaturedImage\Module::resolveAttachmentId( $attachment_id );
}

if ( $attachment_id > 0 ) {
	$preview_url = wp_get_attachment_image_url( $attachment_id, 'medium' );
	$preview_alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
	if ( ! is_string( $preview_alt ) ) {
		$preview_alt = '';
	}
}
?>

<div class="wp-powersuite-module-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<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" role="presentation">
			<tbody>
				<tr>
					<th scope="row">
						<label><?php esc_html_e( 'Default Featured Image', 'wp-powersuite' ); ?></label>
					</th>
					<td>
						<p class="description" style="margin-bottom: 10px;">
							<?php esc_html_e( 'This image is shown for any post or page that has no featured image set. It appears in archives, category pages, widgets, related posts, social link previews (Open Graph / Twitter), and anywhere the theme displays the featured image.', 'wp-powersuite' ); ?>
						</p>

						<div id="<?php echo esc_attr( $module_id ); ?>_preview_wrap" class="wpps-dfi-preview-wrap" style="margin-bottom: 12px; min-height: 120px;">
							<div id="<?php echo esc_attr( $module_id ); ?>_preview_placeholder" class="wpps-dfi-placeholder" style="width: 300px; height: 158px; border: 1px dashed #8c8f94; border-radius: 4px; background: #f0f0f1; display: flex; align-items: center; justify-content: center; color: #646970; font-size: 13px; text-align: center; padding: 12px; <?php echo $preview_url ? esc_attr( 'display: none;' ) : ''; ?>">
								<?php esc_html_e( 'No image set', 'wp-powersuite' ); ?>
							</div>
							<img id="<?php echo esc_attr( $module_id ); ?>_preview_img" src="<?php echo $preview_url ? esc_url( $preview_url ) : ''; ?>" alt="<?php echo esc_attr( $preview_alt ); ?>" style="max-width: 100%; width: 300px; height: auto; border: 1px solid #8c8f94; border-radius: 4px; <?php echo esc_attr( $preview_url ? 'display: block;' : 'display: none;' ); ?>" />
						</div>

						<input type="hidden"
							id="<?php echo esc_attr( $module_id ); ?>_attachment_id"
							name="attachment_id"
							class="wp-powersuite-advanced-setting"
							data-setting-key="attachment_id"
							value="<?php echo esc_attr( (string) ( $attachment_id > 0 ? $attachment_id : '' ) ); ?>"
						/>

						<p style="margin-bottom: 10px;">
							<button type="button" class="button" id="<?php echo esc_attr( $module_id ); ?>_select_image">
								<?php echo $attachment_id > 0 ? esc_html__( 'Change Image', 'wp-powersuite' ) : esc_html__( 'Select Image', 'wp-powersuite' ); ?>
							</button>
							<?php if ( $attachment_id > 0 ) : ?>
								<button type="button" class="button" id="<?php echo esc_attr( $module_id ); ?>_remove_image">
									<?php esc_html_e( 'Remove Image', 'wp-powersuite' ); ?>
								</button>
							<?php else : ?>
								<button type="button" class="button" id="<?php echo esc_attr( $module_id ); ?>_remove_image" style="display: none;">
									<?php esc_html_e( 'Remove Image', 'wp-powersuite' ); ?>
								</button>
							<?php endif; ?>
						</p>

						<p class="description">
							<?php esc_html_e( 'Recommended size: 1200×630px for best results in archives and social shares (e.g. Open Graph, Twitter Card).', '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 selectBtnId = '#' + moduleId + '_select_image';
	var removeBtnId = '#' + moduleId + '_remove_image';
	var inputId = '#' + moduleId + '_attachment_id';
	var previewImgId = '#' + moduleId + '_preview_img';
	var placeholderId = '#' + moduleId + '_preview_placeholder';

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

	function updatePreview(url, alt) {
		var $ = jQuery;
		var $img = $(previewImgId);
		var $placeholder = $(placeholderId);
		if (url) {
			$img.attr('src', url).attr('alt', alt || '').show();
			if ($placeholder.length) $placeholder.hide();
			$(removeBtnId).show();
			$(selectBtnId).text('<?php echo esc_js( __( 'Change Image', 'wp-powersuite' ) ); ?>');
		} else {
			$img.attr('src', '').attr('alt', '').hide();
			if ($placeholder.length) $placeholder.show();
			$(removeBtnId).hide();
			$(selectBtnId).text('<?php echo esc_js( __( 'Select Image', 'wp-powersuite' ) ); ?>');
		}
	}

	function handleSelectClick(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 (fileFrame) {
			fileFrame.open();
			return false;
		}
		fileFrame = wp.media({
			title: '<?php echo esc_js( __( 'Select Default Featured Image', 'wp-powersuite' ) ); ?>',
			button: { text: '<?php echo esc_js( __( 'Use this image', 'wp-powersuite' ) ); ?>' },
			library: { type: 'image' },
			multiple: false
		});
		fileFrame.on('select', function() {
			var attachment = fileFrame.state().get('selection').first().toJSON();
			$(inputId).val(attachment.id);
			updatePreview(attachment.url, attachment.alt || '');
		});
		fileFrame.open();
		return false;
	}

	function handleRemoveClick(e) {
		e.preventDefault();
		e.stopPropagation();
		var $ = jQuery;
		$(inputId).val('');
		updatePreview(null);
		return false;
	}

	function initMediaUploader() {
		if (typeof jQuery === 'undefined') {
			setTimeout(initMediaUploader, 100);
			return;
		}
		var $ = jQuery;
		var $wrap = $('.wp-powersuite-module-settings[data-module-id="' + moduleId + '"]');
		if (!$wrap.length) return;
		$wrap.find(selectBtnId).off('click').on('click', handleSelectClick);
		$wrap.find(removeBtnId).off('click').on('click', handleRemoveClick);
	}

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