<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Renders a consistent admin topbar for all Sifency plugin pages.
 *
 * This class is designed to be reusable. To use it, simply instantiate it
 * and call the render() method, passing the slug of the current active page.
 *
 * Example Usage:
 * $topbar = new Sifency_Admin_Topbar();
 * $topbar->render( 'theme-builder' );
 */
final class Sifency_Addons_Admin_Topbar {

	/**
	 * An array holding all the navigation menu items.
	 *
	 * @var array
	 */
	private $menu_items = array();

	/**
	 * An array holding all the info link items.
	 *
	 * @var array
	 */
	private $info_links = array();

	/**
	 * The slug of the currently active menu item.
	 *
	 * @var string
	 */
	private $active_slug = '';

	/**
	 * The current WordPress admin page query slug.
	 *
	 * @var string
	 */
	private $current_page_slug = '';

	/**
	 * Constructor. Populates the menu items and info links.
	 */
	public function __construct() {
		$this->setup_menu_items();
		$this->setup_info_links();
	}

	/**
	 * Defines the primary navigation menu items for the topbar.
	 * Each item is an array with 'slug', 'label', 'url', and 'icon'.
	 */
	private function setup_menu_items() {
		$base_page_slug = 'sifency-theme-builder';
		$theme          = wp_get_theme();
		if ( $theme->parent() ) {
			$theme = $theme->parent();
		}
		$theme_name = $theme->get( 'Name' );
		$theme_slug = sanitize_title( $theme_name );

		$is_core_active                           = class_exists( 'Sifency_Essential' );
		$sifency_addons_selective_environment_var = false;

		if ( class_exists( 'Sifency_Addons_Theme_Builder_Master' ) && method_exists( 'Sifency_Addons_Theme_Builder_Master', 'sifency_addons_selective_environment' ) ) {
			$sifency_addons_selective_environment_var = Sifency_Addons_Theme_Builder_Master::sifency_addons_selective_environment();
		}

		$this->menu_items = array();

		$this->menu_items['dashboard'] = array(
			'label' => __( 'Dashboard', 'sifency-addons' ),
			'url'   => admin_url( 'admin.php?page=sifency-addons' ),
			'icon'  => 'dashicons-admin-tools',
		);

		if ( function_exists( 'sifency_addons_get_theme_core_class' ) &&
			class_exists( sifency_addons_get_theme_core_class() ) &&
			( class_exists( 'Sifency_Essential' ) || class_exists( 'Sifency_Essentials' ) || is_plugin_active( 'sifency-essential/sifency-essential.php' ) )
		) {
			$this->menu_items['theme-options'] = array(
				'label' => sprintf( /* translators: Theme Options */ __( '%s Options', 'sifency-addons' ), $theme_name ),
				'url'   => admin_url( 'admin.php?page=' . $theme_slug . '-options' ),
				'icon'  => 'dashicons-admin-tools',
			);

			$this->menu_items['template-builder'] = array(
				'label' => sprintf( /* translators: Template Builder */ __( '%s Template Builder', 'sifency-addons' ), $theme_name ),
				'url'   => admin_url( 'edit.php?post_type=sifency_template' ),
				'icon'  => 'dashicons-admin-tools',
			);

		}

		$this->menu_items['widgets'] = array(
			'label' => __( 'Widgets', 'sifency-addons' ),
			'url'   => admin_url( 'admin.php?page=sifency-addons-widgets' ),
			'icon'  => 'dashicons-screenoptions',
		);

		$this->menu_items['theme-builder'] = array(
			'label' => __( 'Theme Builder', 'sifency-addons' ),
			'url'   => admin_url( 'admin.php?page=' . $base_page_slug ),
			'icon'  => 'dashicons-admin-customizer',
		);

		$this->menu_items['settings'] = array(
			'label' => __( 'Settings', 'sifency-addons' ),
			'url'   => admin_url( 'admin.php?page=sifency-settings' ),
			'icon'  => 'dashicons-admin-generic',
		);

		$this->menu_items['template-maker'] = array(
			'label' => __( 'Template Maker', 'sifency-addons' ),
			'url'   => admin_url( 'admin.php?page=sifency-templates-shortcode' ),
			'icon'  => 'dashicons-layout',
		);

		$this->menu_items['prebuild-website'] = array(
			'label' => __( 'Prebuild Website', 'sifency-addons' ),
			'url'   => admin_url( 'admin.php?page=sifency-prebuild-website' ),
			'icon'  => 'dashicons-admin-site-alt3',
		);

		$this->menu_items['extentions'] = array(
			'label' => __( 'Plugins', 'sifency-addons' ),
			'url'   => admin_url( 'admin.php?page=sifency-extentions' ),
			'icon'  => 'dashicons-admin-plugins',
		);

		$this->menu_items['themes'] = array(
			'label' => __( 'Theme', 'sifency-addons' ),
			'url'   => admin_url( 'admin.php?page=sifency-themes' ),
			'icon'  => 'dashicons-admin-appearance',
		);

		$this->menu_items['PRO']       = array(
			'label' => __( 'Why Pro', 'sifency-addons' ),
			'url'   => admin_url( 'admin.php?page=sifency-why-pro' ),
			'icon'  => 'dashicons-info',
		);
		$this->menu_items['ai-studio'] = array(
			'label'        => __( 'AI Studio', 'sifency-addons' ),
			'url'          => admin_url( 'admin.php?page=sifency-ai' ),
			'icon'         => 'dashicons-lightbulb',
			'active_slugs' => array( 'sifency-ai' ),
		);

		if ( $is_core_active || $sifency_addons_selective_environment_var ) {
			unset( $this->menu_items['themes'] );
			unset( $this->menu_items['prebuild-website'] );
			unset( $this->menu_items['PRO'] );
		}

		if ( class_exists( 'Sifency_Addons_Theme_Builder_Master' ) && method_exists( 'Sifency_Addons_Theme_Builder_Master', 'is_sync_valid' ) && Sifency_Addons_Theme_Builder_Master::is_sync_valid() ) {
			unset( $this->menu_items['PRO'] );
		}

		$this->menu_items = apply_filters( 'sifency_addons_admin_topbar_menu_items', $this->menu_items );
	}

	/**
	 * Defines the secondary info links for the topbar.
	 */
	private function setup_info_links() {
		$this->info_links = array(
			'features' => array(
				'label'  => __( '✨ New Features', 'sifency-addons' ),
				'url'    => 'https://sifency.com/sifency-addons/new-features',
				'target' => '_blank',
			),
			'docs'     => array(
				'label'  => __( '📘 Docs', 'sifency-addons' ),
				'url'    => 'https://sifency.com/docs/sifency-addons',
				'target' => '_blank',
			),
			'support'  => array(
				'label'  => __( '💬 Support', 'sifency-addons' ),
				'url'    => 'https://wordpress.org/support/plugin/sifency-addons',
				'target' => '_blank',
			),
		);

		$this->info_links = apply_filters( 'sifency_addons_admin_topbar_info_links', $this->info_links );
	}

	/**
	 * Checks whether a topbar menu item matches the current admin screen.
	 *
	 * @param string $slug The menu item array key.
	 * @param array  $item The menu item data.
	 * @return bool
	 */
	private function is_menu_item_active( $slug, $item ) {
		$active_slugs   = ! empty( $item['active_slugs'] ) && is_array( $item['active_slugs'] ) ? $item['active_slugs'] : array();
		$active_slugs[] = $slug;

		if ( ! empty( $item['url'] ) ) {
			$url_query = wp_parse_url( $item['url'], PHP_URL_QUERY );

			if ( $url_query ) {
				$url_args = array();
				wp_parse_str( $url_query, $url_args );

				if ( ! empty( $url_args['page'] ) ) {
					$active_slugs[] = sanitize_key( $url_args['page'] );
				}

				if ( ! empty( $url_args['post_type'] ) ) {
					$active_slugs[] = sanitize_key( $url_args['post_type'] );
				}
			}
		}

		$current_slugs = array_filter(
			array(
				$this->active_slug,
				$this->current_page_slug,
				isset( $_GET['post_type'] ) ? sanitize_key( wp_unslash( $_GET['post_type'] ) ) : '',
			)
		);

		return (bool) array_intersect( $current_slugs, array_unique( $active_slugs ) );
	}

	/**
	 * Renders the complete HTML for the topbar.
	 *
	 * @param string $active_slug The unique slug of the current page's menu item.
	 */
	public function render( $active_slug = '' ) {
		$this->active_slug       = sanitize_key( $active_slug );
		$this->current_page_slug = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';

		$logo_url = defined( 'sifency_addons_URL' ) ? sifency_addons_URL . 'assets/images/logo.svg' : '';
		$version  = defined( 'sifency_addons_VERSION' ) ? sifency_addons_VERSION : '1.0';
		$pro_link = 'https://sifency.com/sifency-addons';
		?>
		<div class="sifency-admin-topbar">
			<div class="sifency-topbar-inner">
				<div class="sifency-topbar-left">
					<div class="sifency-admin-header">
						<div class="sifency-header-left">
							<div class="sifency-logo">
								<img src="<?php echo esc_url( SIFENCY_ADDONS_URL . 'assets/images/logo.png' ); ?>"
									alt="<?php echo esc_attr__( 'Sifency Logo', 'sifency-addons' ); ?>">
							</div>
							<?php if ( ! Sifency_Addons_Theme_Builder_Master::sifency_addons_selective_environment() ) : ?>
								<h1 class="sifency-title"><?php esc_html_e( 'Sifency Addons', 'sifency-addons' ); ?></h1>
								<?php
							else :
								$theme      = wp_get_theme();
								$theme_name = $theme->parent() ? $theme->parent()->get( 'Name' ) : $theme->get( 'Name' );
								?>
								<h1 class="sifency-title"><?php echo esc_html( sprintf( /* translators: %s: active theme name */ __( '%s Theme', 'sifency-addons' ), $theme_name ) ); ?></h1>
							<?php endif; ?>
						</div>
						<div class="sifency-header-right">
							<span class="sifency-version">
								<?php if ( ! Sifency_Addons_Theme_Builder_Master::sifency_addons_selective_environment() ) : ?>
									<?php
										printf(
											/* translators: %s: Plugin version number. */
											esc_html__( 'Version %s', 'sifency-addons' ),
											esc_html( SIFENCY_ADDONS_VERSION )
										);
									?>
								<?php else : ?>
									<?php
										printf(
											/* translators: %s: Plugin version number. */
											esc_html__( 'Theme Version %s', 'sifency-addons' ),
											esc_html( $theme->get( 'Version' ) )
										);
									?>
								<?php endif; ?>
							</span>
						</div>
					</div>
					<?php if ( $logo_url ) : ?>
					<img src="<?php echo esc_url( $logo_url ); ?>" alt="Sifency" class="sifency-topbar-logo">
					<?php endif; ?>
				</div>

				<div class="sifency-topbar-right">
					<div class="sifency-topbar-info">
						<?php foreach ( $this->info_links as $link ) : ?>
						<a href="<?php echo esc_url( $link['url'] ); ?>" class="sifency-info-link sifency-admin-btn text_underline_animation"
							<?php
							if ( ! empty( $link['target'] ) ) {
								echo 'target="' . esc_attr( $link['target'] ) . '" rel="noopener"';}
							?>
							>
							<span><?php echo esc_html( $link['label'] ); ?></span>
						</a>
						<?php endforeach; ?>

						<?php if ( ! Sifency_Addons_Theme_Builder_Master::sync_environment_state() ) : ?>
						<a href="<?php echo esc_url( $pro_link ); ?>" class="sifency-upgrade-btn sifency-admin-btn"
							target="_blank" rel="noopener">
							<?php esc_html_e( 'Upgrade to Pro', 'sifency-addons' ); ?>
						</a>
						<?php endif; ?>

					</div>

					<nav class="sifency-topbar-menu">
						<?php foreach ( $this->menu_items as $slug => $item ) : ?>
							<?php $is_active = $this->is_menu_item_active( $slug, $item ) ? ' is-active' : ''; ?>
						<a href="<?php echo esc_url( $item['url'] ); ?>"
							class="sifency-admin-btn text_underline_animation menu-item<?php echo esc_attr( $is_active ); ?>">
							<?php if ( ! empty( $item['icon'] ) ) : ?>
							<span class="dashicons <?php echo esc_attr( $item['icon'] ); ?>"></span>
							<?php endif; ?>
							<span class="menu-label"><?php echo esc_html( $item['label'] ); ?></span>
						</a>
						<?php endforeach; ?>
					</nav>

				</div>
			</div>
		</div>
		<button id="sifency-toggle-fullwidth" class="sifency-fullscreen-btn">
			<span class="icon-expand">⤢</span>
			<span class="icon-compress">⤡</span>
		</button>
		<?php
	}
}
