<?php
/**
 * Admin header view.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Controllers\Admin\DashboardAdminController;
use Awesomemotive\Rewardswp\Controllers\Admin\ReferralsAdminController;
use Awesomemotive\Rewardswp\Controllers\Admin\ReportsAdminController;
use Awesomemotive\Rewardswp\Controllers\Admin\EmailsAdminController;
use Awesomemotive\Rewardswp\Controllers\Admin\MembersAdminController;
use Awesomemotive\Rewardswp\Controllers\Admin\RewardsAdminController;
use Awesomemotive\Rewardswp\Controllers\Admin\SettingsAdminController;
use Awesomemotive\Rewardswp\Controllers\Admin\ToolsAdminController;
use Awesomemotive\Rewardswp\Helpers\IconHelper;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Controllers\Admin\PointsAdminController;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;
use function Awesomemotive\Rewardswp\Helpers\get_upgrade_url;


/**
 * Admin Header View.
 *
 * @since 1.0.0
 */
class AdminHeaderView extends AbstractView implements ViewInterface {
	/**
	 * Icon helper instance.
	 *
	 * @since 1.0.0
	 *
	 * @var IconHelper
	 */
	private IconHelper $icon_helper;

	/**
	 * Construct.
	 *
	 * @since 1.0.3
	 *
	 * @param IconHelper $icon_helper
	 */
	public function __construct( IconHelper $icon_helper ) {
		$this->icon_helper = $icon_helper;
	}

	/**
	 * Render the template.
	 *
	 * @since 1.0.0
	 *
	 * @param array $args {
	 *     @type string      $page_title          The page title. Default ''.
	 *     @type string|false $page_title_url      URL for the page title breadcrumb link. Default false.
	 *     @type bool        $show_upgrade_notice Whether to show the upgrade notice. Default false.
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		$screen = get_current_screen();

		$args = wp_parse_args(
			$args,
			[
				'page_title'          => $this->get_page_title(),
				'page_title_url'      => $this->get_page_title_url(),
				'show_upgrade_notice' => false,
			]
		);

		$current_page = sanitize_text_field( filter_input( INPUT_GET, 'page' ) );

		$header_classes = 'rewardswp-container max-[601px]:relative max-[601px]:top-[46px] ml-[-20px] z-10 bg-white text-[#141b38] transition-shadow duration-250 shadow-gray-800/10';

		// Add sticky classes for non-settings/emails pages and non-member detail view.
		// This is a GET request in admin area for navigation purposes only, nonce verification is not required.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$get_action = isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : '';
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$get_member_id         = isset( $_GET['member_id'] ) ? absint( $_GET['member_id'] ) : 0;
		$is_member_detail_view = 'view_member' === $get_action && $get_member_id > 0;

		$non_sticky_pages = [
			SettingsAdminController::MENU_SLUG,
			EmailsAdminController::MENU_SLUG,
			ToolsAdminController::MENU_SLUG,
			ReportsAdminController::MENU_SLUG,
		];

		$header_classes .= ( in_array( $current_page, $non_sticky_pages, true ) || $is_member_detail_view ) ? '' : ' sticky top-[32px] ';
		?>

		<?php if ( $args['show_upgrade_notice'] ) : ?>
			<div
				x-data="{
					showBanner: true,
					dismissNotice() {
						this.showBanner = false;
						const params = new URLSearchParams();
						params.append('action', rewardswpMainVars.dismissNoticeAction);
						params.append('nonce', rewardswpMainVars.nonce);
						fetch(rewardswpMainVars.ajaxUrl, {
							method: 'POST',
							body: params
						}).catch(error => console.error('Error dismissing notice:', error));
					}
				}"
				x-show="showBanner"
				class="rewardswp-container rewardswp-upgrade-bar relative ml-[-20px] z-10 bg-[#00aa63] pl-5 pr-12 py-2 text-white text-sm flex items-center justify-center"
				x-cloak
			>
				<span>
					<?php
					printf(
						/* translators: %1$s is "You're using", %2$s is the plan name (semibold), %3$s is ". To unlock more growth consider" */
						'%1$s <span class="font-semibold">%2$s</span>%3$s',
						esc_html__( "You're using", 'rewardswp' ),
						esc_html__( 'RewardsWP Lite', 'rewardswp' ),
						esc_html__( '. To unlock more features consider', 'rewardswp' )
					);
					?>

						<a href="<?php echo esc_url( get_upgrade_url( 'upgrade_to_pro', 'lite-upgrade-bar' ) ); ?>" target="_blank" class="text-white font-semibold">
							<?php
							printf(
								'<span class="underline underline-offset-2 hover:no-underline">%1$s</span>',
								esc_html__( 'upgrading to Pro', 'rewardswp' )
							);
							?>
						</a>
						<?php
							echo ' ' . esc_html__( 'for 50% off.', 'rewardswp' );
						?>

				</span>
				<button
					x-on:click="dismissNotice()"
					type="button"
					class="absolute right-4 top-1/2 -translate-y-1/2 p-1 cursor-pointer"
					aria-label="<?php esc_attr_e( 'Dismiss notice', 'rewardswp' ); ?>"
				>
					<?php echo wp_kses( $this->icon_helper->get_icon( 'modal-close', 'size-4 text-white transition-colors duration-200' ), svg_kses() ); ?>
				</button>
			</div>
		<?php endif; ?>

		<div id="rewardswp-admin-header-sentinel" class="absolute top-0 left-0 right-0"></div>
		<div id="rewardswp-admin-header" class="<?php echo esc_attr( $header_classes ); ?>">
			<div class="mx-auto <?php echo in_array( $screen->id, [ 'rewardswp_page_rewardswp-settings', 'rewardswp_page_rewardswp-emails', 'rewardswp_page_rewardswp-tools' ], true ) ? '' : ''; ?>">
				<div class="flex items-center justify-between p-5 px-8">

					<div class="gap-1.5 flex items-center">
						<?php echo wp_kses( $this->icon_helper->get_icon( 'logo-mark', 'w-10 h-10' ), svg_kses() ); ?>
						<span class="text-xl font-bold text-gray-700"><?php esc_html_e( 'RewardsWP', 'rewardswp' ); ?></span>

						<?php if ( $args['page_title'] ) : ?>
							<span class="spacer inline-flex w-[20px] h-[2px] rotate-[-75deg] bg-[#d0d1d7]"></span>
							<?php if ( $args['page_title_url'] ) : ?>
								<a href="<?php echo esc_url( $args['page_title_url'] ); ?>" class="text-base text-gray-500 no-underline hover:text-gray-900 transition-colors"><?php echo esc_html( $args['page_title'] ); ?></a>
							<?php else : ?>
								<span class="text-base"><?php echo esc_html( $args['page_title'] ); ?></span>
							<?php endif; ?>
						<?php endif; ?>

					</div>

					<div class="flex items-center gap-4 text-slate-600">
						<button
							x-data
							type="button"
							class="cursor-pointer relative inline-flex h-10 w-10 items-center justify-center rounded-full bg-gray-100 transition focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 hover:text-slate-900"
							x-on:click.prevent="(window.rewardswpNotifications && window.rewardswpNotifications.open) ? window.rewardswpNotifications.open() : window.dispatchEvent(new CustomEvent('rewardswp:open-notifications'))"
						>
							<span class="sr-only"><?php esc_html_e( 'Open notifications', 'rewardswp' ); ?></span>
							<?php echo wp_kses( $this->icon_helper->get_icon( 'inbox', 'h-5 w-5' ), svg_kses() ); ?>
							<span
								x-cloak
								x-show="$store.notificationsDrawer && $store.notificationsDrawer.activeNotifications && $store.notificationsDrawer.activeNotifications.length > 0"
								x-text="$store.notificationsDrawer.activeNotifications.length"
								class="absolute -top-1 -right-1 flex h-5 min-w-5 items-center justify-center rounded-full bg-red-500 px-1 text-xs font-semibold text-white"
							></span>
						</button>
						<a
							href="https://affiliatewp.com/rewardswp/docs/"
							target="_blank"
							rel="noopener noreferrer"
							class="relative inline-flex h-10 w-10 items-center justify-center rounded-full bg-gray-100 transition focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 hover:text-slate-900"
							title="<?php esc_attr_e( 'Documentation', 'rewardswp' ); ?>"
						>
							<span class="sr-only"><?php esc_html_e( 'View documentation', 'rewardswp' ); ?></span>
							<?php echo wp_kses( $this->icon_helper->get_icon( 'circle-question-mark', 'h-5 w-5' ), svg_kses() ); ?>
						</a>
					</div>

				</div>
			</div>

		</div>

		<?php
	}

	/**
	 * Gets the page title URL for breadcrumb linking.
	 *
	 * Returns a URL when the current view is a detail/sub-page (e.g., viewing
	 * a single member), so the page title acts as a back link to the list view.
	 * Returns false on list pages where no back link is needed.
	 *
	 * @since 1.4.0
	 *
	 * @return string|false URL string or false if not on a detail page.
	 */
	private function get_page_title_url() {
		$current_page = sanitize_text_field( filter_input( INPUT_GET, 'page' ) );

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$action = isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : '';

		// Member detail view: link back to members list.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$member_id = isset( $_GET['member_id'] ) ? absint( $_GET['member_id'] ) : 0;

		if ( MembersAdminController::MENU_SLUG === $current_page && 'view_member' === $action && $member_id > 0 ) {
			return admin_url( 'admin.php?page=' . MembersAdminController::MENU_SLUG );
		}

		// Emails page: always link back to emails list.
		// The email editor uses Alpine.js SPA navigation (pushState), so PHP can't
		// detect edit mode from the initial request. Always linking is harmless on
		// the list view and provides navigation back when editing.
		if ( EmailsAdminController::MENU_SLUG === $current_page ) {
			return admin_url( 'admin.php?page=' . EmailsAdminController::MENU_SLUG );
		}

		return false;
	}

	/**
	 * Gets the page title.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	private function get_page_title(): string {
		$current_page = sanitize_text_field(
			filter_input( INPUT_GET, 'page' )
		);

		switch ( $current_page ) {
			case PointsAdminController::MENU_SLUG:
				$page_title = esc_html__( 'Points', 'rewardswp' );
				break;
			case DashboardAdminController::MENU_SLUG:
				$page_title = esc_html__( 'Dashboard', 'rewardswp' );
				break;
			case MembersAdminController::MENU_SLUG:
				$page_title = esc_html__( 'Members', 'rewardswp' );
				break;
			case ReferralsAdminController::MENU_SLUG:
				$page_title = esc_html__( 'Referrals', 'rewardswp' );
				break;
			case RewardsAdminController::MENU_SLUG:
				$page_title = esc_html__( 'Rewards', 'rewardswp' );
				break;
			case EmailsAdminController::MENU_SLUG:
				$page_title = esc_html__( 'Emails', 'rewardswp' );
				break;
			case SettingsAdminController::MENU_SLUG:
				$page_title = esc_html__( 'Settings', 'rewardswp' );
				break;
			case ReportsAdminController::MENU_SLUG:
				$page_title = esc_html__( 'Reports', 'rewardswp' );
				break;
			case ToolsAdminController::MENU_SLUG:
				$page_title = esc_html__( 'Tools', 'rewardswp' );
				break;
			default:
				$page_title = false;
				break;
		}

		return $page_title;
	}
}
