<?php
/**
 * Custom Image Sizes module settings template.
 *
 * @package CustomImageSizes
 */

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

if ( ! function_exists( 'wp_powersuite_is_license_valid' ) || ! wp_powersuite_is_license_valid() ) {
	$license_page_url = admin_url( 'admin.php?page=powersuite-license' );
	?>
	<div class="wp-powersuite-module-settings wpps-settings-panel" data-module-id="<?php echo esc_attr( $module_id ?? 'custom-image-sizes' ); ?>">
		<div class="notice notice-warning inline" style="margin:0;">
			<p>
				<?php esc_html_e( 'Custom Image Sizes requires an active license. Activate your license to register and manage custom image dimensions.', 'wppowersuite-lite' ); ?>
				<a href="<?php echo esc_url( $license_page_url ); ?>"><?php esc_html_e( 'Activate license', 'wppowersuite-lite' ); ?></a>
			</p>
		</div>
	</div>
	<?php
	return;
}

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

$module_id    = $module_id ?? 'custom-image-sizes';
$settings     = OptionStoreModuleSettingsRepository::forModule( $module_id )->all( [] );
$custom_sizes = [];
if ( isset( $settings['custom_sizes'] ) && is_array( $settings['custom_sizes'] ) ) {
	foreach ( $settings['custom_sizes'] as $size ) {
		if ( ! is_array( $size ) || empty( $size['name'] ) ) {
			continue;
		}
		$name = substr( preg_replace( '/[^a-z0-9_]/', '', strtolower( (string) $size['name'] ) ), 0, 50 );
		if ( $name === '' ) {
			continue;
		}
		$width  = max( 0, min( 4096, (int) ( $size['width'] ?? 0 ) ) );
		$height = max( 0, min( 4096, (int) ( $size['height'] ?? 0 ) ) );
		if ( $width <= 0 && $height <= 0 ) {
			continue;
		}
		$custom_sizes[] = [
			'name'   => $name,
			'width'  => $width,
			'height' => $height,
			'crop'   => ! empty( $size['crop'] ),
		];
	}
}

$wp_default_names = [ 'thumbnail', 'medium', 'medium_large', 'large' ];
$wp_default_sizes = [];
foreach ( $wp_default_names as $name ) {
	$wp_default_sizes[] = [
		'name'   => $name,
		'width'  => (int) get_option( "{$name}_size_w", 0 ),
		'height' => (int) get_option( "{$name}_size_h", 0 ),
		'crop'   => (bool) get_option( "{$name}_crop", false ),
	];
}

$custom_names = array_column( $custom_sizes, 'name' );
$theme_names  = get_transient( 'wpps_cis_theme_size_names' );
$theme_names  = is_array( $theme_names ) ? array_values( $theme_names ) : [];
$theme_sizes  = [];
if ( ! empty( $GLOBALS['_wp_additional_image_sizes'] ) && is_array( $GLOBALS['_wp_additional_image_sizes'] ) ) {
	foreach ( $GLOBALS['_wp_additional_image_sizes'] as $name => $data ) {
		if ( in_array( $name, $custom_names, true ) || in_array( $name, $wp_default_names, true ) ) {
			continue;
		}
		$theme_sizes[] = [
			'name'   => (string) $name,
			'width'  => (int) ( $data['width'] ?? 0 ),
			'height' => (int) ( $data['height'] ?? 0 ),
			'crop'   => (bool) ( $data['crop'] ?? false ),
		];
	}
}
$conflicts   = array_values( array_intersect( $custom_names, $theme_names ) );
$dtg_enabled = OptionStoreModuleSettingsRepository::isModuleEnabled( 'disable-thumbnail-generation' );
?>
<div class="wpps-cis-settings" data-module-id="<?php echo esc_attr( $module_id ); ?>">
	<p class="description wpps-cis-intro"><?php esc_html_e( 'Add custom image sizes. New uploads generate these sizes. Use Regenerate Thumbnails for existing images.', 'wppowersuite-lite' ); ?></p>

	<form class="wp-powersuite-module-settings-form" data-module-id="<?php echo esc_attr( $module_id ); ?>" onsubmit="return false;">
		<?php wp_nonce_field( 'wp_powersuite_save_module_settings_' . $module_id, 'wp_powersuite_nonce' ); ?>
		<input type="hidden" name="custom_sizes" class="wp-powersuite-advanced-setting" data-setting-key="custom_sizes" value="<?php echo esc_attr( wp_json_encode( $custom_sizes ) ); ?>" id="wpps-cis-custom-sizes-data" />

		<div class="wpps-cis-card wpps-cis-add-card" id="wpps-cis-add-form">
			<h3 class="wpps-cis-card-title"><?php esc_html_e( 'Add a New Size', 'wppowersuite-lite' ); ?></h3>

			<div class="wpps-cis-quick-actions">
				<div class="wpps-cis-action-group">
					<span class="wpps-cis-label"><?php esc_html_e( 'Presets', 'wppowersuite-lite' ); ?></span>
					<div class="wpps-cis-buttons">
						<button type="button" class="button button-small wpps-cis-preset" data-name="og_image" data-width="1200" data-height="630" data-crop="1">OG 1200×630</button>
						<button type="button" class="button button-small wpps-cis-preset" data-name="hero_banner" data-width="1920" data-height="600" data-crop="1">Hero 1920×600</button>
						<button type="button" class="button button-small wpps-cis-preset" data-name="card_thumb" data-width="400" data-height="300" data-crop="1">Card 400×300</button>
						<button type="button" class="button button-small wpps-cis-preset" data-name="gallery_square" data-width="600" data-height="600" data-crop="1">Square 600×600</button>
					</div>
				</div>
				<div class="wpps-cis-action-group">
					<span class="wpps-cis-label"><?php esc_html_e( 'Ratio', 'wppowersuite-lite' ); ?></span>
					<div class="wpps-cis-buttons">
						<button type="button" class="button button-small wpps-cis-ratio" data-w="16" data-h="9">16:9</button>
						<button type="button" class="button button-small wpps-cis-ratio" data-w="4" data-h="3">4:3</button>
						<button type="button" class="button button-small wpps-cis-ratio" data-w="1" data-h="1">1:1</button>
					</div>
				</div>
			</div>

			<div class="wpps-cis-form-grid">
				<div class="wpps-cis-field">
					<label for="wpps-cis-name"><?php esc_html_e( 'Name', 'wppowersuite-lite' ); ?></label>
					<input type="text" id="wpps-cis-name" placeholder="hero_banner" pattern="[a-z0-9_]+" maxlength="50" autocomplete="off" />
					<span class="wpps-cis-hint"><?php esc_html_e( 'Lowercase, numbers, underscores only', 'wppowersuite-lite' ); ?></span>
				</div>
				<div class="wpps-cis-field">
					<label for="wpps-cis-width"><?php esc_html_e( 'Width', 'wppowersuite-lite' ); ?></label>
					<input type="number" id="wpps-cis-width" min="0" max="4096" value="800" />
				</div>
				<div class="wpps-cis-field">
					<label for="wpps-cis-height"><?php esc_html_e( 'Height', 'wppowersuite-lite' ); ?></label>
					<input type="number" id="wpps-cis-height" min="0" max="4096" value="600" />
				</div>
				<div class="wpps-cis-field wpps-cis-field-inline">
					<label class="wpps-cis-checkbox-label">
						<input type="checkbox" id="wpps-cis-crop" />
						<?php esc_html_e( 'Crop', 'wppowersuite-lite' ); ?>
					</label>
				</div>
				<div class="wpps-cis-field wpps-cis-field-actions">
					<button type="button" class="button button-primary" id="wpps-cis-add-btn"><?php esc_html_e( 'Add', 'wppowersuite-lite' ); ?></button>
					<button type="button" class="button button-secondary" id="wpps-cis-cancel-edit" style="display:none"><?php esc_html_e( 'Cancel', 'wppowersuite-lite' ); ?></button>
				</div>
			</div>
		</div>

		<div class="wpps-cis-card wpps-cis-list-card">
			<h3 class="wpps-cis-card-title">
				<?php esc_html_e( 'Your Custom Sizes', 'wppowersuite-lite' ); ?>
				<span class="wpps-cis-saved-feedback" id="wpps-cis-saved-feedback" aria-live="polite"><?php esc_html_e( 'Saved', 'wppowersuite-lite' ); ?> ✓</span>
			</h3>
			<ul class="wpps-cis-sizes-list" id="wpps-cis-custom-list">
				<?php if ( empty( $custom_sizes ) ) : ?>
					<li class="wpps-cis-empty"><?php esc_html_e( 'None. Add one above.', 'wppowersuite-lite' ); ?></li>
				<?php else : ?>
					<?php foreach ( $custom_sizes as $s ) : ?>
						<?php
						$dims = ( $s['width'] || $s['height'] ) ? $s['width'] . '×' . $s['height'] : '—';
						?>
						<li data-name="<?php echo esc_attr( $s['name'] ); ?>" data-width="<?php echo esc_attr( (string) $s['width'] ); ?>" data-height="<?php echo esc_attr( (string) $s['height'] ); ?>" data-crop="<?php echo ! empty( $s['crop'] ) ? '1' : '0'; ?>">
							<span><?php echo esc_html( $s['name'] ); ?> (<?php echo esc_html( $dims ); ?><?php echo ! empty( $s['crop'] ) ? ', crop' : ''; ?>)</span>
							<span class="wpps-cis-item-actions">
								<button type="button" class="button button-small wpps-cis-edit"><?php esc_html_e( 'Edit', 'wppowersuite-lite' ); ?></button>
								<button type="button" class="button button-small wpps-cis-delete"><?php esc_html_e( 'Delete', 'wppowersuite-lite' ); ?></button>
							</span>
						</li>
					<?php endforeach; ?>
				<?php endif; ?>
			</ul>
		</div>

		<details class="wpps-cis-card wpps-cis-details">
			<summary class="wpps-cis-summary"><?php esc_html_e( 'WordPress & theme sizes', 'wppowersuite-lite' ); ?></summary>
			<?php if ( ! empty( $wp_default_sizes ) ) : ?>
			<div class="wpps-cis-subsection">
				<h4><?php esc_html_e( 'WordPress Defaults', 'wppowersuite-lite' ); ?></h4>
				<ul class="wpps-cis-sizes-list wpps-cis-readonly">
					<?php foreach ( $wp_default_sizes as $s ) : ?>
						<?php $dims = ( $s['width'] || $s['height'] ) ? $s['width'] . '×' . $s['height'] : '—'; ?>
						<li><?php echo esc_html( $s['name'] ); ?> (<?php echo esc_html( $dims ); ?><?php echo $s['crop'] ? ', crop' : ''; ?>)</li>
					<?php endforeach; ?>
				</ul>
			</div>
			<?php endif; ?>
			<?php if ( ! empty( $theme_sizes ) ) : ?>
			<div class="wpps-cis-subsection">
				<h4><?php esc_html_e( 'Theme/Plugin', 'wppowersuite-lite' ); ?></h4>
				<ul class="wpps-cis-sizes-list wpps-cis-readonly">
					<?php foreach ( $theme_sizes as $s ) : ?>
						<?php $dims = ( $s['width'] || $s['height'] ) ? $s['width'] . '×' . $s['height'] : '—'; ?>
						<li><?php echo esc_html( $s['name'] ); ?> (<?php echo esc_html( $dims ); ?>)</li>
					<?php endforeach; ?>
				</ul>
			</div>
			<?php endif; ?>
		</details>

		<?php if ( ! empty( $conflicts ) ) : ?>
		<div class="wpps-cis-warning" role="alert">
			<?php
			printf(
				/* translators: %s: string value. */
				esc_html__( 'Conflict: %s. Your settings override theme/plugin.', 'wppowersuite-lite' ),
				'<code>' . esc_html( implode( ', ', $conflicts ) ) . '</code>'
			);
			?>
		</div>
		<?php endif; ?>

		<div class="wpps-cis-regenerate">
			<p><strong><?php esc_html_e( 'Existing images', 'wppowersuite-lite' ); ?></strong><br>
			<?php esc_html_e( 'New sizes apply to future uploads. Use Regenerate Thumbnails for existing images.', 'wppowersuite-lite' ); ?></p>
			<button type="button" class="button button-primary wpps-cis-open-regenerate">
				<span class="dashicons dashicons-images-alt2" aria-hidden="true"></span> <?php esc_html_e( 'Open Regenerate Thumbnails', 'wppowersuite-lite' ); ?>
			</button>
		</div>

		<?php if ( $dtg_enabled ) : ?>
		<p class="description"><?php esc_html_e( 'Disable Thumbnail Generation is enabled. You can turn off specific sizes there.', 'wppowersuite-lite' ); ?></p>
		<?php endif; ?>
	</form>
</div>

<?php ob_start(); ?>
(function(){
	'use strict';
	var c=document.querySelector('.wpps-cis-settings');
	if(!c)return;
	var nameIn=c.querySelector('#wpps-cis-name'),widthIn=c.querySelector('#wpps-cis-width'),heightIn=c.querySelector('#wpps-cis-height'),cropIn=c.querySelector('#wpps-cis-crop');
	var addBtn=c.querySelector('#wpps-cis-add-btn'),cancelBtn=c.querySelector('#wpps-cis-cancel-edit');
	var list=c.querySelector('#wpps-cis-custom-list'),hidden=c.querySelector('#wpps-cis-custom-sizes-data');
	var themeNames=<?php echo wp_json_encode( $theme_names ); ?>;
	var RESERVED=['thumbnail','medium','medium_large','large'];
	var MAX=4096,MAX_SIZES=20;
	var editing=null,dirty=false;

	function getSizes(){try{var a=JSON.parse(hidden.value||'[]');return Array.isArray(a)?a:[];}catch(e){return[];}}
	function setSizes(s){dirty=true;hidden.value=JSON.stringify(s);render(s);}
	function escapeHtml(s){if(!s)return'';var d=document.createElement('div');d.textContent=s;return d.innerHTML;}
	function sanitize(v){return String(v).toLowerCase().replace(/[^a-z0-9_]/g,'').slice(0,50);}
	function render(sizes){
		list.innerHTML='';
		if(!sizes.length){list.innerHTML='<li class="wpps-cis-empty"><?php echo esc_js( __( 'None. Add one above.', 'wppowersuite-lite' ) ); ?></li>';return;}
		sizes.forEach(function(s){
			var d=(s.width&&s.height)?s.width+'×'+s.height:(s.width||s.height||'—');
			var li=document.createElement('li');
			li.dataset.name=s.name;li.dataset.width=String(s.width||0);li.dataset.height=String(s.height||0);li.dataset.crop=s.crop?'1':'0';
			li.innerHTML='<span>'+escapeHtml(s.name)+' ('+escapeHtml(d)+(s.crop?', crop':'')+')</span><span class="wpps-cis-item-actions"><button type="button" class="button button-small wpps-cis-edit"><?php echo esc_js( __( 'Edit', 'wppowersuite-lite' ) ); ?></button><button type="button" class="button button-small wpps-cis-delete"><?php echo esc_js( __( 'Delete', 'wppowersuite-lite' ) ); ?></button></span>';
			list.appendChild(li);
		});
		bindList();
	}
	function bindList(){
		list.querySelectorAll('.wpps-cis-edit').forEach(function(b){b.onclick=function(){var li=b.closest('li');if(li)startEdit(li.dataset.name,parseInt(li.dataset.width,10),parseInt(li.dataset.height,10),li.dataset.crop==='1');}});
		list.querySelectorAll('.wpps-cis-delete').forEach(function(b){b.onclick=function(){var li=b.closest('li');if(li&&confirm('<?php echo esc_js( __( 'Delete this size?', 'wppowersuite-lite' ) ); ?>'))setSizes(getSizes().filter(function(s){return s.name!==li.dataset.name;}));}});
	}
	function startEdit(name,w,h,crop){editing=name;nameIn.value=name;nameIn.disabled=true;widthIn.value=w||'';heightIn.value=h||'';cropIn.checked=!!crop;addBtn.textContent='<?php echo esc_js( __( 'Update', 'wppowersuite-lite' ) ); ?>';cancelBtn.style.display='inline-block';c.querySelector('#wpps-cis-add-form').scrollIntoView({behavior:'smooth',block:'start'});}
	function cancelEdit(){editing=null;nameIn.value='';nameIn.disabled=false;widthIn.value='800';heightIn.value='600';cropIn.checked=false;addBtn.textContent='<?php echo esc_js( __( 'Add', 'wppowersuite-lite' ) ); ?>';cancelBtn.style.display='none';}
	function doAdd(){
		var name=sanitize(nameIn.value),w=Math.min(MAX,Math.max(0,parseInt(widthIn.value,10)||0)),h=Math.min(MAX,Math.max(0,parseInt(heightIn.value,10)||0)),crop=cropIn.checked;
		if(!name){alert('<?php echo esc_js( __( 'Enter a size name.', 'wppowersuite-lite' ) ); ?>');return;}
		if(RESERVED.indexOf(name)!==-1){alert('<?php echo esc_js( __( 'Reserved name.', 'wppowersuite-lite' ) ); ?>');return;}
		if(themeNames&&themeNames.indexOf(name)!==-1&&!confirm('<?php echo esc_js( __( 'Name used by theme. Override?', 'wppowersuite-lite' ) ); ?>'))return;
		if(w<=0&&h<=0){alert('<?php echo esc_js( __( 'Set width or height.', 'wppowersuite-lite' ) ); ?>');return;}
		var sizes=getSizes();
		if(!editing&&sizes.length>=MAX_SIZES){alert('<?php echo esc_js( __( 'Maximum 20 custom sizes allowed.', 'wppowersuite-lite' ) ); ?>');return;}
		if(editing){if(name!==editing&&sizes.some(function(s){return s.name===name;})){alert('<?php echo esc_js( __( 'Name exists.', 'wppowersuite-lite' ) ); ?>');return;}sizes=sizes.map(function(s){return s.name===editing?{name:name,width:w,height:h,crop:crop}:s;});cancelEdit();}
		else{if(sizes.some(function(s){return s.name===name;})){alert('<?php echo esc_js( __( 'Name exists.', 'wppowersuite-lite' ) ); ?>');return;}sizes.push({name:name,width:w,height:h,crop:crop});}
		setSizes(sizes);
	}
	addBtn.onclick=doAdd;
	cancelBtn.onclick=cancelEdit;
	c.addEventListener('click',function(e){
		var p=e.target.closest('.wpps-cis-preset');if(p){cancelEdit();nameIn.value=p.dataset.name||'';widthIn.value=p.dataset.width||'';heightIn.value=p.dataset.height||'';cropIn.checked=p.dataset.crop==='1';c.querySelector('#wpps-cis-add-form').scrollIntoView({behavior:'smooth',block:'start'});return;}
		var r=e.target.closest('.wpps-cis-ratio');if(r){var w=parseInt(r.dataset.w,10)||1,h=parseInt(r.dataset.h,10)||1;widthIn.value=800;heightIn.value=Math.round(800*h/w);return;}
		var o=e.target.closest('.wpps-cis-open-regenerate');if(o){e.preventDefault();if(dirty&&!confirm('<?php echo esc_js( __( 'Unsaved changes. Switch anyway?', 'wppowersuite-lite' ) ); ?>'))return;if(window.wpPowerSuite&&typeof window.wpPowerSuite.openAdvancedSettings==='function')window.wpPowerSuite.openAdvancedSettings('regenerate-thumbnails');}
	});
	function syncBeforeSave(){var items=list.querySelectorAll('li:not(.wpps-cis-empty)'),arr=[];items.forEach(function(li){var n=(li.dataset.name||'').trim();if(n)arr.push({name:n,width:parseInt(li.dataset.width,10)||0,height:parseInt(li.dataset.height,10)||0,crop:li.dataset.crop==='1'});});hidden.value=JSON.stringify(arr);}
	if(window.wpPowerSuite){window.wpPowerSuite.syncModuleSettingsBeforeSave=window.wpPowerSuite.syncModuleSettingsBeforeSave||{};window.wpPowerSuite.syncModuleSettingsBeforeSave['custom-image-sizes']=syncBeforeSave;}
	document.addEventListener('wp-powersuite-settings-saved',function(e){if(e.detail&&e.detail.moduleId==='custom-image-sizes'){var fb=c.querySelector('#wpps-cis-saved-feedback');if(fb){fb.classList.add('is-visible');setTimeout(function(){fb.classList.remove('is-visible');},2000);}dirty=false;}});
	var modal=document.getElementById('wp-powersuite-modal');
	if(modal){function warn(ev){if(dirty&&!confirm('<?php echo esc_js( __( 'Unsaved changes. Close anyway?', 'wppowersuite-lite' ) ); ?>')){ev.preventDefault();ev.stopPropagation();}}
		modal.querySelector('.wp-powersuite-modal__close')&&modal.querySelector('.wp-powersuite-modal__close').addEventListener('click',warn,true);
		modal.querySelector('.wp-powersuite-modal__cancel')&&modal.querySelector('.wp-powersuite-modal__cancel').addEventListener('click',warn,true);}
	bindList();
})();
<?php \WP_PowerSuite\Core\InlineAssets::script( 'wpps-ia-modules-custom-image-sizes-admin-php-script-1', (string) ob_get_clean() ); ?>

