<?php
/**
 * Admin menu wiring + asset enqueueing.
 *
 * @package WPLens
 */

namespace WPLens\Admin;

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

final class Menu {

	private const HANDLE_CSS       = 'lens-admin';
	private const HANDLE_JS        = 'lens-admin';
	private const HANDLE_CHART     = 'lens-chartjs';
	private const HANDLE_DASHBOARD = 'lens-dashboard';
	private const HANDLE_CRAWLERS  = 'lens-crawlers';
	private const HANDLE_SCANS     = 'lens-scans';
	private const HANDLE_CITATIONS = 'lens-citations';
	private const HANDLE_SETTINGS  = 'lens-settings';
	private const HANDLE_WELCOME   = 'lens-welcome';

	public function register(): void {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
	}

	public function register_menu(): void {
		add_menu_page(
			__( 'Lens', 'lens-ai-visibility-monitor' ),
			__( 'Lens', 'lens-ai-visibility-monitor' ),
			'manage_options',
			'lens-ai-visibility-monitor',
			array( $this, 'render_dashboard' ),
			'dashicons-visibility',
			58
		);

		add_submenu_page( 'lens-ai-visibility-monitor', __( 'Dashboard', 'lens-ai-visibility-monitor' ),   __( 'Dashboard', 'lens-ai-visibility-monitor' ),   'manage_options', 'lens-ai-visibility-monitor', array( $this, 'render_dashboard' ) );
		add_submenu_page( 'lens-ai-visibility-monitor', __( 'AI Crawlers', 'lens-ai-visibility-monitor' ), __( 'AI Crawlers', 'lens-ai-visibility-monitor' ), 'manage_options', 'lens-crawlers',              array( $this, 'render_crawlers' ) );
		add_submenu_page( 'lens-ai-visibility-monitor', __( 'Scans', 'lens-ai-visibility-monitor' ),      __( 'Scans', 'lens-ai-visibility-monitor' ),      'edit_posts',     'lens-scans',                 array( $this, 'render_scans' ) );
		add_submenu_page( 'lens-ai-visibility-monitor', __( 'Citations', 'lens-ai-visibility-monitor' ),  __( 'Citations', 'lens-ai-visibility-monitor' ),  'manage_options', 'lens-citations',             array( $this, 'render_citations' ) );
		add_submenu_page( 'lens-ai-visibility-monitor', __( 'Reports', 'lens-ai-visibility-monitor' ),    __( 'Reports', 'lens-ai-visibility-monitor' ),    'manage_options', 'lens-reports',               array( $this, 'render_reports' ) );
		add_submenu_page( 'lens-ai-visibility-monitor', __( 'Settings', 'lens-ai-visibility-monitor' ),   __( 'Settings', 'lens-ai-visibility-monitor' ),   'manage_options', 'lens-settings',              array( $this, 'render_settings' ) );

		// Hidden welcome page (shown via direct link after activation).
		add_submenu_page( '', __( 'Welcome to Lens', 'lens-ai-visibility-monitor' ), __( 'Welcome', 'lens-ai-visibility-monitor' ), 'manage_options', 'lens-welcome', array( $this, 'render_welcome' ) );
	}

	public function enqueue_assets( string $hook ): void {
		if ( false === strpos( $hook, 'lens-' ) && false === strpos( $hook, 'lens-ai-visibility-monitor' ) ) {
			return;
		}

		$base_url = WPLENS_PLUGIN_URL . 'assets/';
		$ver      = WPLENS_VERSION;

		// Shared CSS + JS
		wp_enqueue_style(  self::HANDLE_CSS, $base_url . 'css/admin.css', array(), $ver );
		wp_enqueue_script( self::HANDLE_JS,  $base_url . 'js/admin.js',   array(), $ver, true );

		wp_localize_script(
			self::HANDLE_JS,
			'lensConfig',
			array(
				'ajaxUrl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( Ajax::NONCE_ACTION ),
				'i18n'    => array(
					'noResults'    => __( 'No results.', 'lens-ai-visibility-monitor' ),
					'errorGeneric' => __( 'Something went wrong.', 'lens-ai-visibility-monitor' ),
					'close'        => __( 'Dismiss', 'lens-ai-visibility-monitor' ),
					'confirmDelete'=> __( 'Are you sure?', 'lens-ai-visibility-monitor' ),
					'scanning'     => __( 'Scanning…', 'lens-ai-visibility-monitor' ),
					'scanComplete' => __( 'Scan complete.', 'lens-ai-visibility-monitor' ),
					'queryAdded'   => __( 'Query added.', 'lens-ai-visibility-monitor' ),
					'queryDeleted' => __( 'Query removed.', 'lens-ai-visibility-monitor' ),
					'testing'      => __( 'Testing…', 'lens-ai-visibility-monitor' ),
					'running'      => __( 'Running…', 'lens-ai-visibility-monitor' ),
				),
			)
		);

		// Chart.js — only on pages that draw charts (saves ~200KB on Settings).
		$needs_chart = in_array( $hook, $this->chart_hooks(), true );

		if ( $needs_chart ) {
			wp_enqueue_script( self::HANDLE_CHART, $base_url . 'vendor/chartjs/chart.umd.js', array(), '4.5.1', true );
		}

		// Page-specific scripts
		if ( $this->is_hook( $hook, 'lens-ai-visibility-monitor' ) ) {
			wp_enqueue_script( self::HANDLE_DASHBOARD, $base_url . 'js/dashboard.js', array( self::HANDLE_JS, self::HANDLE_CHART ), $ver, true );
		} elseif ( $this->is_hook( $hook, 'lens-crawlers' ) ) {
			wp_enqueue_script( self::HANDLE_CRAWLERS, $base_url . 'js/crawlers.js', array( self::HANDLE_JS ), $ver, true );
		} elseif ( $this->is_hook( $hook, 'lens-scans' ) ) {
			wp_enqueue_script( self::HANDLE_SCANS, $base_url . 'js/scans.js', array( self::HANDLE_JS ), $ver, true );
		} elseif ( $this->is_hook( $hook, 'lens-citations' ) ) {
			wp_enqueue_script( self::HANDLE_CITATIONS, $base_url . 'js/citations.js', array( self::HANDLE_JS, self::HANDLE_CHART ), $ver, true );
		} elseif ( $this->is_hook( $hook, 'lens-settings' ) ) {
			wp_enqueue_script( self::HANDLE_SETTINGS, $base_url . 'js/settings.js', array( self::HANDLE_JS ), $ver, true );
		} elseif ( $this->is_hook( $hook, 'lens-welcome' ) ) {
			wp_enqueue_script( self::HANDLE_WELCOME, $base_url . 'js/welcome.js', array( self::HANDLE_JS ), $ver, true );
		}
	}

	private function chart_hooks(): array {
		// Hooks generated for top-level + citations
		return array(
			'toplevel_page_lens-ai-visibility-monitor',
			'lens_page_lens-citations',
		);
	}

	private function is_hook( string $hook, string $slug ): bool {
		return false !== strpos( $hook, '_page_' . $slug ) || $hook === 'toplevel_page_' . $slug;
	}

	// ----- Page renderers ---------------------------------------------------

	public function render_dashboard(): void {
		if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have permission.', 'lens-ai-visibility-monitor' ) ); }
		include WPLENS_PLUGIN_DIR . 'includes/admin/views/dashboard.php';
	}

	public function render_crawlers(): void {
		if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have permission.', 'lens-ai-visibility-monitor' ) ); }
		// Wipe handler kept here so it works without JS.
		if ( isset( $_POST['wplens_wipe_logs'] ) ) {
			check_admin_referer( 'wplens_wipe_logs' );
			( new \WPLens\Crawler\LogRepository() )->truncate();
			add_settings_error( 'lens-ai-visibility-monitor', 'logs-wiped', __( 'Crawler logs wiped.', 'lens-ai-visibility-monitor' ), 'updated' );
		}
		include WPLENS_PLUGIN_DIR . 'includes/admin/views/crawlers.php';
	}

	public function render_scans(): void {
		if ( ! current_user_can( 'edit_posts' ) ) { wp_die( esc_html__( 'You do not have permission.', 'lens-ai-visibility-monitor' ) ); }
		include WPLENS_PLUGIN_DIR . 'includes/admin/views/scans.php';
	}

	public function render_citations(): void {
		if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have permission.', 'lens-ai-visibility-monitor' ) ); }
		include WPLENS_PLUGIN_DIR . 'includes/admin/views/citations.php';
	}

	public function render_reports(): void {
		if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have permission.', 'lens-ai-visibility-monitor' ) ); }
		if ( isset( $_POST['wplens_send_test'] ) ) {
			check_admin_referer( 'wplens_send_test' );
			$settings = \WPLens\Utils\Options::all();
			if ( ! empty( $settings['reporting']['recipients'] ) ) {
				$builder = new \WPLens\Reports\HtmlReportBuilder();
				$html    = $builder->build_weekly();
				$sender  = new \WPLens\Reports\EmailSender();
				$ok      = $sender->send_weekly_report( $settings['reporting']['recipients'], $html );
				add_settings_error( 'lens-ai-visibility-monitor', $ok ? 'report-sent' : 'report-failed', $ok ? __( 'Test report sent.', 'lens-ai-visibility-monitor' ) : __( 'Could not send test report.', 'lens-ai-visibility-monitor' ), $ok ? 'updated' : 'error' );
			} else {
				add_settings_error( 'lens-ai-visibility-monitor', 'no-recipients', __( 'Add at least one recipient first.', 'lens-ai-visibility-monitor' ) );
			}
		}
		include WPLENS_PLUGIN_DIR . 'includes/admin/views/reports.php';
	}

	public function render_settings(): void {
		if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have permission.', 'lens-ai-visibility-monitor' ) ); }
		include WPLENS_PLUGIN_DIR . 'includes/admin/views/settings.php';
	}

	public function render_welcome(): void {
		if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have permission.', 'lens-ai-visibility-monitor' ) ); }
		include WPLENS_PLUGIN_DIR . 'includes/admin/views/welcome.php';
	}
}
