<?php
/**
 * Theme module.
 *
 * Sits next to the Plugins module under the Vendors group. Lists every
 * installed theme, calls out the active theme + its parent, flags Kadence
 * (parent) and Kadence-based child themes as the BW-recommended setup, and
 * offers one-click delete for everything else.
 *
 * Ideal state: exactly two themes installed —
 *   - `kadence` (parent)
 *   - one Kadence-based child (Template = 'kadence'), which is active
 *
 * No persisted module-level settings — pure status display.
 *
 * @package BW_Dev
 */

defined( 'ABSPATH' ) || exit;

class BW_Dev_Module_Theme implements BW_Dev_Module_Interface {

	const KADENCE_PARENT_SLUG = 'kadence';

	public function slug(): string {
		return 'theme';
	}

	public function label(): string {
		return __( 'Theme', 'bw-dev' );
	}

	public function group(): string {
		return 'vendors';
	}

	public function default_settings(): array {
		return array();
	}

	public function sanitize( array $data ): array {
		unset( $data );
		return array();
	}

	public function register(): void {
		// No hooks — this module is a passive status display, like the Plugins one.
	}

	/* ---------------------------------------------------------------------
	 * Helpers
	 * ------------------------------------------------------------------- */

	/**
	 * Per-theme classification: which roles it plays in the current setup.
	 * Returned keys are all booleans except 'slug' / 'parent_slug'.
	 */
	private function classify( WP_Theme $theme, WP_Theme $active ): array {
		$slug             = $theme->get_stylesheet();
		$template         = $theme->get_template();
		$is_active        = $slug === $active->get_stylesheet();
		$active_parent    = $active->get_template();
		$is_active_parent = ( $slug === $active_parent && $slug !== $active->get_stylesheet() );
		$is_kadence       = ( $slug === self::KADENCE_PARENT_SLUG );
		$is_kadence_child = ( $template === self::KADENCE_PARENT_SLUG && $slug !== self::KADENCE_PARENT_SLUG );
		return array(
			'slug'              => $slug,
			'parent_slug'       => $template,
			'is_active'         => $is_active,
			'is_active_parent'  => $is_active_parent,
			'is_in_use'         => $is_active || $is_active_parent,
			'is_kadence'        => $is_kadence,
			'is_kadence_child'  => $is_kadence_child,
			'is_recommended'    => $is_kadence || $is_kadence_child,
		);
	}

	/**
	 * Evaluate whether the install matches the BW-ideal setup.
	 *
	 * @param array<string,WP_Theme> $themes Map from wp_get_themes().
	 * @param WP_Theme               $active Result of wp_get_theme().
	 * @return array{ ideal:bool, message:string, level:string }
	 */
	private function evaluate_state( array $themes, WP_Theme $active ): array {
		$has_kadence       = isset( $themes[ self::KADENCE_PARENT_SLUG ] );
		$kadence_children  = array();
		foreach ( $themes as $slug => $theme ) {
			if ( $theme->get_template() === self::KADENCE_PARENT_SLUG && $slug !== self::KADENCE_PARENT_SLUG ) {
				$kadence_children[] = $slug;
			}
		}
		$active_is_kadence_based = ( $active->get_template() === self::KADENCE_PARENT_SLUG );
		$count                   = count( $themes );
		$child_count             = count( $kadence_children );

		if ( ! $has_kadence ) {
			return array(
				'ideal'   => false,
				'level'   => 'warning',
				'message' => __( 'The Kadence parent theme is not installed. The BW-ideal setup is Kadence + one Kadence-based child theme.', 'bw-dev' ),
			);
		}
		if ( ! $active_is_kadence_based ) {
			return array(
				'ideal'   => false,
				'level'   => 'warning',
				'message' => __( 'The active theme is not a Kadence child. Switch to a Kadence-based child theme to match the BW-ideal setup.', 'bw-dev' ),
			);
		}
		if ( 2 === $count && 1 === $child_count ) {
			return array(
				'ideal'   => true,
				'level'   => 'success',
				'message' => __( 'Ideal setup: Kadence parent + one Kadence-based child active. No extras to clean up.', 'bw-dev' ),
			);
		}
		return array(
			'ideal'   => false,
			'level'   => 'info',
			'message' => sprintf(
				/* translators: %d: number of themes installed */
				_n(
					'%d theme installed. The ideal is two — Kadence parent + one Kadence-based child. Extra themes can be deleted below.',
					'%d themes installed. The ideal is two — Kadence parent + one Kadence-based child. Extra themes can be deleted below.',
					$count,
					'bw-dev'
				),
				$count
			),
		);
	}

	/* ---------------------------------------------------------------------
	 * Settings tab
	 * ------------------------------------------------------------------- */

	public function render_tab(): void {
		$active     = wp_get_theme();
		$themes     = wp_get_themes();
		$state      = $this->evaluate_state( $themes, $active );
		$can_delete = current_user_can( 'delete_themes' );
		$accent     = 'success' === $state['level'] ? '#00a32a' : ( 'warning' === $state['level'] ? '#d63638' : '#dba617' );
		?>
		<p class="description">
			<?php esc_html_e( 'Every theme installed on this site. The BW-ideal setup is two themes: Kadence (parent) plus one Kadence-based child theme that is active. Anything else can usually be deleted from here.', 'bw-dev' ); ?>
		</p>

		<div style="background:#fff;border-left:4px solid <?php echo esc_attr( $accent ); ?>;padding:12px 16px;margin:14px 0;max-width:820px;">
			<strong>
				<?php
				echo 'success' === $state['level'] ? '&#x2713; ' : '';
				esc_html_e( 'Setup status', 'bw-dev' );
				?>
			</strong>
			<p style="margin:6px 0 0;"><?php echo esc_html( $state['message'] ); ?></p>
		</div>

		<table class="widefat striped" style="margin-top:14px;">
			<thead>
				<tr>
					<th style="width:90px;"><?php esc_html_e( 'Preview', 'bw-dev' ); ?></th>
					<th><?php esc_html_e( 'Theme', 'bw-dev' ); ?></th>
					<th><?php esc_html_e( 'Type', 'bw-dev' ); ?></th>
					<th style="width:140px;"><?php esc_html_e( 'Status', 'bw-dev' ); ?></th>
					<th style="width:130px;"><?php esc_html_e( 'Action', 'bw-dev' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $themes as $slug => $theme ) : ?>
					<?php $this->render_theme_row( $theme, $active, $can_delete ); ?>
				<?php endforeach; ?>
			</tbody>
		</table>

		<p class="description" style="margin-top:14px;">
			<?php esc_html_e( 'WordPress will refuse to delete the active theme or its active parent — the Delete buttons for those are hidden as a courtesy. To switch themes, use Appearance → Themes first, then come back here.', 'bw-dev' ); ?>
		</p>
		<?php
	}

	private function render_theme_row( WP_Theme $theme, WP_Theme $active, bool $can_delete ): void {
		$info       = $this->classify( $theme, $active );
		$slug       = $info['slug'];
		$name       = (string) $theme->display( 'Name', false );
		$version    = (string) $theme->display( 'Version', false );
		$author     = (string) $theme->display( 'Author', false );
		$screenshot = (string) $theme->get_screenshot();

		// Type label.
		if ( $info['is_kadence'] ) {
			$type = __( 'Kadence (parent)', 'bw-dev' );
		} elseif ( $info['is_kadence_child'] ) {
			$type = __( 'Kadence child', 'bw-dev' );
		} elseif ( '' !== $info['parent_slug'] && $info['parent_slug'] !== $slug ) {
			$type = sprintf(
				/* translators: %s: parent theme slug */
				__( 'Child of %s', 'bw-dev' ),
				$info['parent_slug']
			);
		} else {
			$type = __( 'Standalone parent', 'bw-dev' );
		}

		// Status badge.
		if ( $info['is_active'] ) {
			$badge = $this->badge( __( 'Active', 'bw-dev' ), '#00a32a' );
		} elseif ( $info['is_active_parent'] ) {
			$badge = $this->badge( __( 'Active parent', 'bw-dev' ), '#2271b1' );
		} elseif ( $info['is_recommended'] ) {
			$badge = $this->badge( __( 'Recommended', 'bw-dev' ), '#2271b1' );
		} else {
			$badge = $this->badge( __( 'Other', 'bw-dev' ), '#646970' );
		}

		// Action.
		if ( $info['is_in_use'] ) {
			$action = '<span style="color:#646970;">&mdash;</span>';
		} elseif ( ! $can_delete ) {
			$action = '<span style="color:#646970;font-size:11px;">' . esc_html__( 'No permission', 'bw-dev' ) . '</span>';
		} else {
			$delete_url = wp_nonce_url(
				self_admin_url( 'themes.php?action=delete&stylesheet=' . rawurlencode( $slug ) ),
				'delete-theme_' . $slug
			);
			$confirm = sprintf(
				/* translators: %s: theme name */
				__( 'Permanently delete the theme "%s" and all its files? This cannot be undone.', 'bw-dev' ),
				$name
			);
			$button_class = $info['is_recommended'] ? 'button button-secondary' : 'button button-secondary';
			$action = sprintf(
				'<a href="%s" class="%s" onclick="return confirm(%s);" aria-label="%s">%s</a>',
				esc_url( $delete_url ),
				esc_attr( $button_class ),
				esc_js( wp_json_encode( $confirm ) ),
				/* translators: %s: theme name */
				esc_attr( sprintf( __( 'Delete theme %s', 'bw-dev' ), $name ) ),
				esc_html__( 'Delete', 'bw-dev' )
			);
		}

		?>
		<tr>
			<td>
				<?php if ( '' !== $screenshot ) : ?>
					<img src="<?php echo esc_url( $screenshot ); ?>" alt="" style="width:80px;height:auto;border:1px solid #c3c4c7;" />
				<?php else : ?>
					<span style="display:inline-block;width:80px;height:50px;background:#f0f0f1;text-align:center;line-height:50px;color:#646970;font-size:11px;border:1px solid #c3c4c7;">no image</span>
				<?php endif; ?>
			</td>
			<td>
				<strong><?php echo esc_html( $name ); ?></strong>
				<?php if ( '' !== $version ) : ?>
					<span style="color:#646970;font-size:11px;"> v<?php echo esc_html( $version ); ?></span>
				<?php endif; ?>
				<br />
				<span style="color:#646970;font-size:11px;">
					<?php echo esc_html( $slug ); ?>
					<?php if ( '' !== $author ) : ?>
						&mdash; <?php echo wp_kses( $author, array( 'a' => array( 'href' => array(), 'title' => array() ) ) ); ?>
					<?php endif; ?>
				</span>
			</td>
			<td><?php echo esc_html( $type ); ?></td>
			<td><?php echo $badge; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped above. ?></td>
			<td><?php echo $action; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped above. ?></td>
		</tr>
		<?php
	}

	private function badge( string $text, string $color ): string {
		return '<span style="display:inline-block;padding:2px 8px;border-radius:3px;background:' . esc_attr( $color ) . ';color:#fff;font-size:11px;font-weight:600;">' . esc_html( $text ) . '</span>';
	}

	public function uninstall(): void {
		// No persisted state.
	}
}
