<?php
/**
 * Admin menu, pages and settings registration.
 *
 * @package AccessLens
 */

declare(strict_types=1);

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

/**
 * AccessLens_Admin
 */
class AccessLens_Admin {

	/**
	 * Register all hooks.
	 */
	public function register(): void {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'admin_notices', array( $this, 'render_onboarding_notice' ) );
		add_action( 'admin_notices', array( $this, 'render_review_notice' ) );
	}

	/**
	 * True if the current admin screen belongs to AccessLens.
	 */
	private function is_plugin_screen(): bool {
		$screen = get_current_screen();
		return $screen && 'toplevel_page_accesslens' === $screen->id;
	}

	/**
	 * Add top-level admin menu.
	 *
	 * Nota: no hay pagina de Ajustes. La URL del motor es una constante
	 * (ACCESSLENS_ENGINE_URL) fija por diseno, no un valor configurable.
	 */
	public function register_menu(): void {
		add_menu_page(
			__( 'AccessLens - Web Accessibility Audit', 'accesslens' ),
			__( 'AccessLens', 'accesslens' ),
			'manage_options',
			'accesslens',
			array( $this, 'render_dashboard' ),
			'dashicons-universal-access-alt',
			80
		);

		add_submenu_page(
			'accesslens',
			__( 'Dashboard', 'accesslens' ),
			__( 'Dashboard', 'accesslens' ),
			'manage_options',
			'accesslens',
			array( $this, 'render_dashboard' )
		);
	}

	/**
	 * Enqueue admin JS + CSS only on plugin pages.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_assets( string $hook ): void {
		$allowed_hooks = array( 'toplevel_page_accesslens' );
		if ( ! in_array( $hook, $allowed_hooks, true ) ) {
			return;
		}

		wp_enqueue_style(
			'accesslens-admin',
			ACCESSLENS_PLUGIN_URL . 'admin/css/admin.css',
			array(),
			ACCESSLENS_VERSION
		);

		wp_enqueue_script(
			'accesslens-admin',
			ACCESSLENS_PLUGIN_URL . 'admin/js/admin.js',
			array( 'jquery' ),
			ACCESSLENS_VERSION,
			true
		);

		$is_pro       = function_exists( 'accesslens_fs' ) && accesslens_fs()->is_paying();
		$scan_history = AccessLens_Options::get( 'accesslens_scan_history', array() );

		wp_localize_script(
			'accesslens-admin',
			'accessLensData',
			array(
				'ajaxUrl'     => admin_url( 'admin-ajax.php' ),
				'nonce'       => wp_create_nonce( 'accesslens_audit_nonce' ),
				'isPro'       => $is_pro,
				'upgradeUrl'  => function_exists( 'accesslens_fs' ) ? esc_url_raw( (string) accesslens_fs()->get_upgrade_url() ) : '',
				'scanHistory' => is_array( $scan_history ) ? array_values( $scan_history ) : array(),
				'i18n'        => array(
					'scanning'                => __( 'Scanning...', 'accesslens' ),
					'done'                    => __( 'Done', 'accesslens' ),
					'error'                   => __( 'Error', 'accesslens' ),
					'noResults'               => __( 'No results yet.', 'accesslens' ),
					'downloadReport'          => __( 'Download PDF report', 'accesslens' ),
					'pollError'               => __( 'Error checking scan status.', 'accesslens' ),
					'startError'              => __( 'Error starting the scan.', 'accesslens' ),
					'queued'                  => __( 'Queued', 'accesslens' ),
					'discovering'             => __( 'Discovering URLs', 'accesslens' ),
					'running'                 => __( 'Scanning', 'accesslens' ),
					'progress'                => __( 'Progress', 'accesslens' ),
					'reconnecting'            => __( 'Connection issue, retrying...', 'accesslens' ),
					'timeoutError'            => __( 'The scan is taking too long and the status check has been cancelled. It may still be running; try again in a few minutes.', 'accesslens' ),
					'generatingReport'        => __( 'Generating report... this may take 1-2 minutes.', 'accesslens' ),
					'reportError'             => __( 'Error generating the report.', 'accesslens' ),
					'upgradeLinkText'         => __( 'Upgrade to Pro', 'accesslens' ),
					'quotaPlanLabel'          => __( 'Plan', 'accesslens' ),
					'quotaUsedLabel'          => __( 'Scans used', 'accesslens' ),
					'quotaResetLabel'         => __( 'Resets', 'accesslens' ),
					'upsellTitle'             => __( 'This free scan covers 1 page.', 'accesslens' ),
					'upsellBody'              => __( 'AccessLens Pro audits up to 25 pages, prioritizes fixes with AI and generates your Accessibility Statement.', 'accesslens' ),
					'upsellPrice'             => __( 'EUR 149/year.', 'accesslens' ),
					'upsellCta'               => __( 'Upgrade to Pro', 'accesslens' ),
					'printFooter'             => __( 'Generated with AccessLens - partial automated detection (25-40% of WCAG criteria).', 'accesslens' ),
					'scopeIncomplete'         => __( 'Complete every option to see the diagnosis.', 'accesslens' ),
					'scopeVerdictLabel'       => __( 'Orientative diagnosis:', 'accesslens' ),
					'scopeVerdictNotDigital'  => __( 'Your main activity does not appear to be a digital service within the scope of the EAA. Consult a legal advisor to confirm.', 'accesslens' ),
					'scopeVerdictMicroExempt' => __( 'Possibly an exempt microenterprise under the EAA (Art. 4.5): fewer than 10 employees and revenue below EUR 2 million. Verify with your legal advisor, as some activities may still be obligated.', 'accesslens' ),
					'scopeVerdictInScope'     => __( 'Your company is likely within the scope of the EAA and must ensure the accessibility of its digital products and services as of 28 June 2025. Consult a specialist.', 'accesslens' ),
					/* translators: %d: number of pages analyzed */
					'resultsSummaryPages'      => __( '%d page(s) analyzed.', 'accesslens' ),
					/* translators: %d: number of violations detected */
					'resultsSummaryViolations' => __( '%d violation(s) detected in total.', 'accesslens' ),
					// Scan history / "Progress over time" card.
					/* translators: %1$s: date of the first scan, %2$s: initial critical count, %3$s: latest critical count */
					'historyTrend'             => __( 'Since %1$s: critical issues went from %2$s to %3$s.', 'accesslens' ),
					/* translators: %1$s: violation count of the oldest scan shown, %2$s: date of that scan, %3$s: violation count of the latest scan shown, %4$s: date of that scan */
					'historyChartAriaLabel'    => __( 'Scan history chart: from %1$s violations on %2$s to %3$s violations on %4$s.', 'accesslens' ),
					'historyColCritical'       => __( 'Critical', 'accesslens' ),
					'historyColSerious'        => __( 'Serious', 'accesslens' ),
					'historyColModerate'       => __( 'Moderate', 'accesslens' ),
					'historyColMinor'          => __( 'Minor', 'accesslens' ),
					'historyModeSingle'        => __( 'Single page', 'accesslens' ),
					'historyModeSitemap'       => __( 'Sitemap', 'accesslens' ),
					'historyModeCrawl'         => __( 'Full crawl', 'accesslens' ),
				),
			)
		);
	}

	/**
	 * Onboarding notice: solo para manage_options, solo si no hay un scan
	 * previo y el usuario no lo ha descartado. Se descarta via AJAX (ver
	 * AccessLens_Ajax::handle_dismiss_onboarding()).
	 */
	public function render_onboarding_notice(): void {
		if ( ! current_user_can( 'manage_options' ) || ! $this->is_plugin_screen() ) {
			return;
		}

		if ( AccessLens_Options::get( 'accesslens_onboarding_dismissed', false ) ) {
			return;
		}

		if ( false !== AccessLens_Options::get( 'accesslens_last_scan', false ) ) {
			return;
		}

		$dashboard_url = admin_url( 'admin.php?page=accesslens' );
		?>
		<div class="notice notice-info accesslens-onboarding-notice" id="accesslens-onboarding-notice">
			<p>
				<strong><?php esc_html_e( 'Welcome to AccessLens.', 'accesslens' ); ?></strong>
				<?php esc_html_e( 'Audit your site accessibility in a moment and start preparing your documentation for the European Accessibility Act (EAA).', 'accesslens' ); ?>
			</p>
			<p>
				<a href="<?php echo esc_url( $dashboard_url ); ?>#accesslens-scan-form" class="button button-primary">
					<?php esc_html_e( 'Run my first scan', 'accesslens' ); ?>
				</a>
				<button type="button" class="button button-link accesslens-dismiss-onboarding">
					<?php esc_html_e( 'Do not show again', 'accesslens' ); ?>
				</button>
			</p>
		</div>
		<?php
	}

	/**
	 * Review notice: dismissible-forever, solo cuando el usuario ha completado
	 * >= 3 scans y han pasado >= 7 dias desde la instalacion. Se descarta via
	 * AJAX (ver AccessLens_Ajax::handle_dismiss_review()).
	 */
	public function render_review_notice(): void {
		if ( ! current_user_can( 'manage_options' ) || ! $this->is_plugin_screen() ) {
			return;
		}

		if ( AccessLens_Options::get( 'accesslens_review_dismissed', false ) ) {
			return;
		}

		$scan_count   = absint( AccessLens_Options::get( 'accesslens_scan_count', 0 ) );
		$installed_at = absint( AccessLens_Options::get( 'accesslens_installed_at', 0 ) );

		if ( $scan_count < 3 || 0 === $installed_at || ( time() - $installed_at ) < ( 7 * DAY_IN_SECONDS ) ) {
			return;
		}
		?>
		<div class="notice notice-info accesslens-review-notice" id="accesslens-review-notice">
			<p>
				<?php esc_html_e( 'Enjoying AccessLens? A review on wordpress.org helps us a lot to keep improving the plugin.', 'accesslens' ); ?>
			</p>
			<p>
				<a href="https://wordpress.org/support/plugin/accesslens/reviews/#new-post" target="_blank" rel="noopener noreferrer" class="button button-primary accesslens-leave-review">
					<?php esc_html_e( 'Leave a review', 'accesslens' ); ?>
				</a>
				<button type="button" class="button button-link accesslens-dismiss-review">
					<?php esc_html_e( 'Do not ask again', 'accesslens' ); ?>
				</button>
			</p>
		</div>
		<?php
	}

	/**
	 * Render the dashboard page.
	 */
	public function render_dashboard(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'accesslens' ) );
		}
		require_once ACCESSLENS_PLUGIN_DIR . 'admin/views/dashboard.php';
	}
}
