<?php
/**
 * WP PowerSuite Admin Page View
 *
 * Main admin page template for WP PowerSuite.
 * This is a clean HTML wrapper - no assets loaded yet.
 *
 * @package WP_PowerSuite\Admin\Views
 * @since 1.0.0
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Variables available in this view:
 *
 * @var string $plugin_name Plugin name
 * @var string $page_title  Page title
 */

?>
<?php
use WP_PowerSuite\Admin\AdminIcons;
use WP_PowerSuite\Admin\PageHero;
use WP_PowerSuite\Core\ConflictDetector;
use WP_PowerSuite\Core\ModuleCategories;
use WP_PowerSuite\Core\ModuleRegistry;
use WP_PowerSuite\Core\NetworkScope;
use WP_PowerSuite\Core\OptionStore;

$registry = ModuleRegistry::getInstance();
// Use cached metadata for faster page load (cache refreshes every hour automatically)
// Only force refresh if explicitly requested via query parameter
$force_refresh = isset( $_GET['refresh_modules'] ) && sanitize_text_field( wp_unslash( $_GET['refresh_modules'] ) ) === '1';
$registry->init( $force_refresh );

$option_store = OptionStore::getInstance();
$all_modules = $registry->getAllModules();
$enabled_modules = $option_store->getEnabledModules();
$favorites = $option_store->getFavorites();
$module_order = $option_store->getModuleOrder();
$categories_discovered = $registry->getCategories();
$categories            = ModuleCategories::sort( $categories_discovered );

$view_mode        = $option_store->getViewMode();
$description_mode = $option_store->getDescriptionMode();

// Until the user stars/unstars, open the Favorites tab by default (see data-bootstrap-category on .wp-powersuite-admin).
$bootstrap_category = '';
if ( $option_store->favoritesUseRecommendedDefaults() ) {
	$bootstrap_category = '__favorites';
}

// License status for premium module gating
$license_valid = function_exists( 'wp_powersuite_is_license_valid' ) && wp_powersuite_is_license_valid();
$license_page_url = admin_url( 'admin.php?page=powersuite-license' );

// Conflict map for all modules (for Conflict Detector UI)
$conflict_detector = ConflictDetector::getInstance();
$conflicts_map = $conflict_detector->getAllConflictsMap();

// When license is invalid, premium modules are disabled (not loaded by ModuleManager)
$enabled_for_display = $enabled_modules;
if ( ! $license_valid ) {
	$enabled_for_display = array_values( array_filter( $enabled_modules, function ( $id ) use ( $all_modules ) {
		return empty( $all_modules[ $id ]['is_pro'] ?? false );
	} ) );
}

// Map module IDs to admin page slugs for custom pages (must match add_submenu_page slugs)
$custom_page_slugs = [
	'basic-forms'              => 'powersuite-basic-forms',
	'ai-alt-text-generator'    => 'powersuite-ai-alt-text',
	'code-snippet'              => 'powersuite-code-snippet',
	'customizer-reset'         => 'themes.php?page=wpps-customizer-reset',
	'admin-columns-customizer'  => 'powersuite-admin-columns-customizer',
	'admin-color-customizer'    => 'powersuite-admin-color-customizer',
	'admin-menu-organizer'      => 'powersuite-admin-menu-organizer',
	'temporary-login'           => 'powersuite-temporary-login',
	'magic-login'               => 'powersuite-magic-login',
	'coming-soon-maintenance'   => 'powersuite-coming-soon-maintenance',
	'options-page-builder'      => 'powersuite-options-page-builder',
	'cpt-builder'               => 'powersuite-cpt-builder',
	'custom-fields'             => 'powersuite-custom-fields',
	'redirect-manager'          => 'powersuite-redirect-manager',
	'custom-wp-emails'          => 'powersuite-custom-wp-emails',
	'email-logs'                => 'powersuite-email-logs',
	'email-smtp'                => 'powersuite-email-delivery',
	'database-cleanup'          => 'powersuite-database-cleanup',
	'login-page-customizor'     => 'powersuite-login-page-customizor',
];

// Hidden reorder pages opened from list tables — never show the card link icon.
$hide_card_link_modules = [
	'custom-post-order',
	'custom-taxonomy-order',
];

$modules_data = [];
foreach ( $all_modules as $module_id => $module_meta ) {
	$is_pro      = ! empty( $module_meta['is_pro'] );
	$is_freemium = ! empty( $module_meta['is_freemium'] );
	$enabled  = in_array( $module_id, $enabled_for_display, true );
	$page_slug = $custom_page_slugs[ $module_id ] ?? null;
	// Override: modules with a custom page slug always have has_custom_page (avoids stale cache showing gear)
	$has_custom_page = ( ! empty( $module_meta['has_custom_page'] ) || ( $page_slug !== null ) )
		&& ! in_array( $module_id, $hide_card_link_modules, true );
	$custom_url = '';
	if ( $has_custom_page && $page_slug ) {
		$custom_url = strpos( $page_slug, '?' ) !== false
			? NetworkScope::adminUrl( $page_slug )
			: NetworkScope::adminUrl( 'admin.php', [ 'page' => $page_slug ] );
	}
	$modules_data[ $module_id ] = [
		'id'          => $module_id,
		'name'        => $module_meta['name'] ?? '',
		'description' => $module_meta['description'] ?? '',
		'category'    => $module_meta['category'] ?? 'uncategorized',
		'version'     => $module_meta['version'] ?? '1.0.0',
		'author'      => $module_meta['author'] ?? '',
		'enabled'     => $enabled,
		'favorite'    => in_array( $module_id, $favorites, true ),
		'is_pro'      => $is_pro,
		'is_freemium' => $is_freemium,
		'has_advanced_settings' => ! empty( $module_meta['has_advanced_settings'] ),
		'has_custom_page'       => $has_custom_page,
		'custom_page_url'       => $custom_url,
		'dependencies'          => isset( $module_meta['dependencies'] ) && is_array( $module_meta['dependencies'] ) ? array_values( array_map( 'sanitize_key', $module_meta['dependencies'] ) ) : [],
		'conflicts'   => $conflicts_map[ $module_id ] ?? [],
		'enable_confirm' => isset( $module_meta['enable_confirm'] ) && is_string( $module_meta['enable_confirm'] ) ? $module_meta['enable_confirm'] : '',
	];
}

$module_count         = count( $all_modules );
$enabled_stat_count   = count( $enabled_for_display );
$favorite_stat_count  = count( $favorites );
?>
<div class="wrap wpps-admin-wrap">
	<?php
	// WordPress common.js moves admin notices to after .wp-header-end (or first h1/h2).
	// Placing wp-header-end first ensures notices appear above our header, outside WP PowerSuite containers.
	?>
	<hr class="wp-header-end" style="margin:0; padding:0; border:none; height:0; overflow:hidden;">

	<?php
	$hero_icon_url = PageHero::default_icon_url();
	PageHero::render(
		[
			'eyebrow'         => __( 'Control Center', 'wp-powersuite' ),
			'title'           => $plugin_name,
			'tagline'         => __( 'Discover, enable, and configure modules—all from one place.', 'wp-powersuite' ),
			'status'          => class_exists( 'WPPS_License_Manager', false ) && ! $license_valid
				? __( 'License inactive', 'wp-powersuite' )
				: __( 'Premium', 'wp-powersuite' ),
			'status_inactive' => class_exists( 'WPPS_License_Manager', false ) && ! $license_valid,
			'logo_url'        => $hero_icon_url,
			'icon'            => $hero_icon_url === '' ? 'dashicons-grid-view' : '',
			'actions'         => PageHero::nav_actions( 'modules' ),
			'stats'           => [
				[
					'value' => number_format_i18n( $enabled_stat_count ),
					'label' => __( 'Enabled', 'wp-powersuite' ),
				],
				[
					'value' => number_format_i18n( $module_count ),
					'label' => __( 'Modules', 'wp-powersuite' ),
				],
				[
					'value' => number_format_i18n( $favorite_stat_count ),
					'label' => __( 'Favorites', 'wp-powersuite' ),
				],
			],
		]
	);
	?>

	<?php $view_mode_class = ( $view_mode === 'list' ) ? 'list' : 'grid'; ?>
	<div class="wp-powersuite-admin wp-powersuite-admin--view-<?php echo esc_attr( $view_mode_class ); ?>" data-modules='<?php echo esc_attr( wp_json_encode( $modules_data ) ); ?>' data-enabled='<?php echo esc_attr( wp_json_encode( $enabled_for_display ) ); ?>' data-favorites='<?php echo esc_attr( wp_json_encode( $favorites ) ); ?>' data-module-order='<?php echo esc_attr( wp_json_encode( $module_order ) ); ?>' data-categories='<?php echo esc_attr( wp_json_encode( $categories ) ); ?>' data-view-mode="<?php echo esc_attr( $view_mode ); ?>" data-description-mode="<?php echo esc_attr( $description_mode ); ?>" data-license-valid="<?php echo esc_attr( $license_valid ? '1' : '0' ); ?>" data-license-page-url="<?php echo esc_attr( $license_page_url ); ?>" data-bootstrap-category="<?php echo esc_attr( $bootstrap_category ); ?>">
		<div class="wp-powersuite-admin__toolbar">
			<div class="wp-powersuite-admin__search">
				<label for="wp-powersuite-search" class="screen-reader-text"><?php esc_html_e( 'Search modules', 'wp-powersuite' ); ?></label>
				<input type="search" id="wp-powersuite-search" class="wp-powersuite-search" placeholder="<?php esc_attr_e( 'Search modules...', 'wp-powersuite' ); ?>" />
			</div>

			<div class="wp-powersuite-admin__filters">
				<label for="wp-powersuite-filter-status" class="screen-reader-text"><?php esc_html_e( 'Filter by status', 'wp-powersuite' ); ?></label>
				<select id="wp-powersuite-filter-status" class="wp-powersuite-filter">
					<option value=""><?php esc_html_e( 'All Status', 'wp-powersuite' ); ?></option>
					<option value="enabled"><?php esc_html_e( 'Enabled', 'wp-powersuite' ); ?></option>
					<option value="disabled"><?php esc_html_e( 'Disabled', 'wp-powersuite' ); ?></option>
				</select>

				<label for="wp-powersuite-filter-tier" class="screen-reader-text"><?php esc_html_e( 'Filter by tier', 'wp-powersuite' ); ?></label>
				<select id="wp-powersuite-filter-tier" class="wp-powersuite-filter">
					<option value=""><?php esc_html_e( 'All Tiers', 'wp-powersuite' ); ?></option>
					<option value="pro"><?php esc_html_e( 'Pro', 'wp-powersuite' ); ?></option>
					<option value="free"><?php esc_html_e( 'Free', 'wp-powersuite' ); ?></option>
				</select>

			</div>

			<div class="wp-powersuite-admin__sort">
				<label for="wp-powersuite-sort" class="screen-reader-text"><?php esc_html_e( 'Sort modules', 'wp-powersuite' ); ?></label>
				<select id="wp-powersuite-sort" class="wp-powersuite-sort">
					<option value="enabled-first" selected><?php esc_html_e( 'Sort: Enabled First', 'wp-powersuite' ); ?></option>
					<option value="disabled-first"><?php esc_html_e( 'Sort: Disabled First', 'wp-powersuite' ); ?></option>
					<option value="name-asc"><?php esc_html_e( 'Sort: A - Z', 'wp-powersuite' ); ?></option>
					<option value="name-desc"><?php esc_html_e( 'Sort: Z - A', 'wp-powersuite' ); ?></option>
				</select>
			</div>

			<div class="wp-powersuite-admin__layout-controls">
				<div class="wp-powersuite-admin__layout-options">
					<select id="wp-powersuite-grid-columns" class="wp-powersuite-layout-toggle" aria-label="<?php esc_attr_e( 'Grid columns', 'wp-powersuite' ); ?>">
						<option value="1"><?php esc_html_e( '1 Column', 'wp-powersuite' ); ?></option>
						<option value="2"><?php esc_html_e( '2 Columns', 'wp-powersuite' ); ?></option>
						<option value="3" selected><?php esc_html_e( '3 Columns', 'wp-powersuite' ); ?></option>
						<option value="4"><?php esc_html_e( '4 Columns', 'wp-powersuite' ); ?></option>
						<option value="5"><?php esc_html_e( '5 Columns', 'wp-powersuite' ); ?></option>
					</select>
				</div>
			</div>

			<div class="wp-powersuite-admin__view-toggle" role="group" aria-label="<?php esc_attr_e( 'Module layout', 'wp-powersuite' ); ?>">
				<button type="button" class="wp-powersuite-view-toggle<?php echo $view_mode_class === 'grid' ? ' is-active' : ''; ?>" data-view="grid" title="<?php esc_attr_e( 'Grid View', 'wp-powersuite' ); ?>" aria-pressed="<?php echo $view_mode_class === 'grid' ? 'true' : 'false'; ?>" aria-label="<?php esc_attr_e( 'Grid view', 'wp-powersuite' ); ?>">
					<span class="dashicons dashicons-grid-view" aria-hidden="true"></span>
				</button>
				<button type="button" class="wp-powersuite-view-toggle<?php echo $view_mode_class === 'list' ? ' is-active' : ''; ?>" data-view="list" title="<?php esc_attr_e( 'List View', 'wp-powersuite' ); ?>" aria-pressed="<?php echo $view_mode_class === 'list' ? 'true' : 'false'; ?>" aria-label="<?php esc_attr_e( 'List view', 'wp-powersuite' ); ?>">
					<span class="dashicons dashicons-list-view" aria-hidden="true"></span>
				</button>
				<?php
				$desc_icons = [ 'show' => 'dashicons-visibility', 'truncate' => 'dashicons-editor-contract', 'hide' => 'dashicons-hidden' ];
				$desc_icon  = $desc_icons[ $description_mode ] ?? 'dashicons-visibility';
				?>
				<div id="wp-powersuite-description-mode-wrap" class="wp-powersuite-admin__description-mode">
					<span class="wp-powersuite-description-mode-label"><?php esc_html_e( 'Desc:', 'wp-powersuite' ); ?></span>
					<button type="button" class="wp-powersuite-description-mode-btn is-active" data-mode="<?php echo esc_attr( $description_mode ); ?>" title="<?php esc_attr_e( 'Description mode (click to cycle)', 'wp-powersuite' ); ?>">
						<span class="wp-powersuite-description-mode-icon dashicons <?php echo esc_attr( $desc_icon ); ?>"></span>
					</button>
				</div>
			</div>
		</div>

		<!-- Category Filter Buttons -->
		<div class="wp-powersuite-admin__category-filters">
			<div class="wp-powersuite-admin__category-buttons" role="group" aria-label="<?php esc_attr_e( 'Filter modules by category', 'wp-powersuite' ); ?>">
				<button type="button" class="button button-secondary wp-powersuite-category-filter" data-category="" aria-pressed="<?php echo $bootstrap_category === '' ? 'true' : 'false'; ?>">
					<?php esc_html_e( 'All', 'wp-powersuite' ); ?>
				</button>
				<button type="button" class="button button-secondary wp-powersuite-category-filter" data-category="__favorites" aria-pressed="<?php echo $bootstrap_category === '__favorites' ? 'true' : 'false'; ?>">
					<?php esc_html_e( 'Favorites', 'wp-powersuite' ); ?>
				</button>
				<?php foreach ( $categories as $category ) : ?>
					<button type="button" class="button button-secondary wp-powersuite-category-filter" data-category="<?php echo esc_attr( $category ); ?>" aria-pressed="<?php echo $bootstrap_category === $category ? 'true' : 'false'; ?>">
						<?php 
						// If category contains a space, use it as-is; otherwise replace hyphens with spaces and capitalize
						$display_category = strpos( $category, ' ' ) !== false 
							? $category 
							: ucwords( str_replace( '-', ' ', $category ) );
						echo esc_html( $display_category ); 
						?>
					</button>
				<?php endforeach; ?>
			</div>
			<button type="button" class="button button-primary wp-powersuite-refresh-page" title="<?php esc_attr_e( 'Refresh page to see changes', 'wp-powersuite' ); ?>" style="display: none;">
				<?php echo AdminIcons::refresh_svg(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG markup from trusted helper. ?>
				<?php esc_html_e( 'Refresh', 'wp-powersuite' ); ?>
			</button>
		</div>

		<div class="wp-powersuite-admin__modules" id="wp-powersuite-modules">
			<div id="wp-powersuite-modules-status" class="screen-reader-text" aria-live="polite" aria-atomic="true"></div>
			<noscript>
				<div class="notice notice-warning">
					<p><?php esc_html_e( 'JavaScript is required for search, filters, and toggling modules. Below is a read-only list of available modules.', 'wp-powersuite' ); ?></p>
				</div>
			</noscript>
			<div class="wp-powersuite-nojs-fallback">
				<table class="widefat striped wp-powersuite-nojs-table">
					<thead>
						<tr>
							<th scope="col"><?php esc_html_e( 'Module', 'wp-powersuite' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Category', 'wp-powersuite' ); ?></th>
							<th scope="col"><?php esc_html_e( 'Status', 'wp-powersuite' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $modules_data as $module_row ) : ?>
							<?php
							$display_category = strpos( (string) $module_row['category'], ' ' ) !== false
								? (string) $module_row['category']
								: ucwords( str_replace( '-', ' ', (string) $module_row['category'] ) );
							?>
							<tr>
								<td>
									<strong><?php echo esc_html( (string) $module_row['name'] ); ?></strong>
									<?php if ( ! empty( $module_row['is_freemium'] ) ) : ?>
										<span class="wpps-freemium-badge"><?php esc_html_e( 'Free + Pro', 'wp-powersuite' ); ?></span>
									<?php elseif ( ! empty( $module_row['is_pro'] ) ) : ?>
										<span class="wpps-pro-badge"><?php esc_html_e( 'Pro', 'wp-powersuite' ); ?></span>
									<?php endif; ?>
								</td>
								<td><?php echo esc_html( $display_category ); ?></td>
								<td><?php echo ! empty( $module_row['enabled'] ) ? esc_html__( 'Enabled', 'wp-powersuite' ) : esc_html__( 'Disabled', 'wp-powersuite' ); ?></td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>
			<div class="wp-powersuite-loading">
				<span class="spinner is-active"></span>
				<p><?php esc_html_e( 'Loading modules...', 'wp-powersuite' ); ?></p>
			</div>
			<div id="wp-powersuite-modules-list" class="wp-powersuite-modules-list wp-powersuite-view-<?php echo esc_attr( $view_mode_class ); ?>"></div>
		</div>

		<div class="wp-powersuite-admin__empty" id="wp-powersuite-empty" style="display: none;">
			<p><?php esc_html_e( 'No modules found matching your criteria.', 'wp-powersuite' ); ?></p>
		</div>
	</div>

	<!-- License Required Modal -->
	<div id="wp-powersuite-license-modal" class="wp-powersuite-modal wp-powersuite-license-modal" style="display: none;" aria-hidden="true">
		<div class="wp-powersuite-modal__overlay" tabindex="-1"></div>
		<div class="wp-powersuite-modal__content wp-powersuite-modal__content--sm" role="dialog" aria-modal="true" aria-labelledby="wp-powersuite-license-modal-title">
			<div class="wp-powersuite-modal__header">
				<h2 id="wp-powersuite-license-modal-title" class="wp-powersuite-modal__title">
					<span class="dashicons dashicons-lock"></span>
					<?php esc_html_e( 'License Required', 'wp-powersuite' ); ?>
				</h2>
				<button type="button" class="wp-powersuite-modal__close wp-powersuite-license-modal__close" aria-label="<?php esc_attr_e( 'Close', 'wp-powersuite' ); ?>">
					<span class="dashicons dashicons-no-alt"></span>
				</button>
			</div>
			<div class="wp-powersuite-modal__body">
				<p class="wp-powersuite-license-modal__message"><?php esc_html_e( 'A valid license is required to enable premium modules. Activate your license to unlock all premium features.', 'wp-powersuite' ); ?></p>
			</div>
			<div class="wp-powersuite-modal__footer">
				<button type="button" class="button wp-powersuite-license-modal__close"><?php esc_html_e( 'Cancel', 'wp-powersuite' ); ?></button>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=powersuite-license' ) ); ?>" class="button button-primary wp-powersuite-license-modal__activate"><?php esc_html_e( 'Activate License', 'wp-powersuite' ); ?></a>
			</div>
		</div>
	</div>

	<!-- Advanced Settings Modal -->
	<div id="wp-powersuite-modal" class="wp-powersuite-modal" style="display: none;" aria-hidden="true">
		<div class="wp-powersuite-modal__overlay" tabindex="-1"></div>
		<div class="wp-powersuite-modal__content" role="dialog" aria-modal="true" aria-labelledby="wp-powersuite-modal-title">
			<div class="wp-powersuite-modal__header">
				<h2 id="wp-powersuite-modal-title" class="wp-powersuite-modal__title">
					<span class="dashicons dashicons-admin-settings"></span>
					<?php esc_html_e( 'Advanced Settings', 'wp-powersuite' ); ?>
					<span class="wp-powersuite-modal__module-name"></span>
				</h2>
				<button type="button" class="wp-powersuite-modal__close" aria-label="<?php esc_attr_e( 'Close', 'wp-powersuite' ); ?>">
					<span class="dashicons dashicons-no-alt"></span>
				</button>
			</div>
			<div class="wp-powersuite-modal__body">
				<div class="wp-powersuite-modal__loading" style="display: none;">
					<span class="spinner is-active"></span>
					<p><?php esc_html_e( 'Loading settings...', 'wp-powersuite' ); ?></p>
				</div>
				<div class="wp-powersuite-modal__settings"></div>
			</div>
			<div class="wp-powersuite-modal__footer">
				<button type="button" class="button wp-powersuite-modal__cancel">
					<?php esc_html_e( 'Cancel', 'wp-powersuite' ); ?>
				</button>
				<button type="button" class="button button-primary wp-powersuite-modal__refresh wp-powersuite-refresh-page" title="<?php esc_attr_e( 'Refresh page to see changes', 'wp-powersuite' ); ?>" style="display: none;">
					<?php echo AdminIcons::refresh_svg(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG markup from trusted helper. ?>
					<?php esc_html_e( 'Refresh', 'wp-powersuite' ); ?>
				</button>
				<button type="button" class="button button-primary wp-powersuite-modal__save">
					<?php esc_html_e( 'Save Settings', 'wp-powersuite' ); ?>
				</button>
			</div>
		</div>
	</div>
</div>

