<?php
/**
 * Adds "Settings", "OpenAI API key" and "View Details" links to the plugin's
 * row on the WordPress Plugins list screen.
 *
 * @package WPLens
 */

namespace WPLens\Admin;

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

final class PluginLinks {

	/**
	 * WordPress.org plugin slug — must match the slug the plugin is hosted under.
	 */
	private const WPORG_SLUG = 'lens-ai-visibility-monitor';

	public function register(): void {
		add_filter( 'plugin_action_links_' . WPLENS_PLUGIN_BASENAME, array( $this, 'action_links' ) );
		add_filter( 'plugin_row_meta', array( $this, 'row_meta' ), 10, 2 );
	}

	/**
	 * Prepend Settings + OpenAI API key links to the row's action links.
	 *
	 * @param array<int|string, string> $links
	 * @return array<int|string, string>
	 */
	public function action_links( $links ): array {
		if ( ! is_array( $links ) ) {
			$links = array();
		}

		$custom = array(
			'lens_settings' => sprintf(
				'<a href="%s">%s</a>',
				esc_url( admin_url( 'admin.php?page=lens-settings' ) ),
				esc_html__( 'Settings', 'lens-ai-visibility-monitor' )
			),
			'lens_openai_key' => sprintf(
				'<a href="%s" style="color:#117a3a;font-weight:600;">%s</a>',
				esc_url( admin_url( 'admin.php?page=lens-settings#lens-openai-key' ) ),
				esc_html__( 'OpenAI API key', 'lens-ai-visibility-monitor' )
			),
		);

		// Put ours first so "Settings" appears before "Deactivate".
		return array_merge( $custom, $links );
	}

	/**
	 * Add "View Details" (WP.org modal) and "Support" links to the meta row
	 * (the second line under the plugin description).
	 *
	 * @param array<int, string> $links
	 * @param string             $file  Plugin file path relative to /plugins/.
	 * @return array<int, string>
	 */
	public function row_meta( $links, $file ): array {
		if ( WPLENS_PLUGIN_BASENAME !== $file ) {
			return is_array( $links ) ? $links : array();
		}

		$view_details_url = add_query_arg(
			array(
				'tab'       => 'plugin-information',
				'plugin'    => self::WPORG_SLUG,
				'TB_iframe' => 'true',
				'width'     => 772,
				'height'    => 800,
			),
			self_admin_url( 'plugin-install.php' )
		);

		$extras = array(
			'lens_view_details' => sprintf(
				'<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s">%s</a>',
				esc_url( $view_details_url ),
				esc_attr__( 'More information about Lens - AI Visibility Monitor', 'lens-ai-visibility-monitor' ),
				esc_html__( 'View Details', 'lens-ai-visibility-monitor' )
			),
			'lens_support' => sprintf(
				'<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
				esc_url( 'https://wordpress.org/support/plugin/' . self::WPORG_SLUG . '/' ),
				esc_html__( 'Support', 'lens-ai-visibility-monitor' )
			),
		);

		return array_merge( is_array( $links ) ? $links : array(), $extras );
	}
}
