<?php
/**
 * Admin UI integration.
 *
 * @package Live_Traffic_Analytics
 */

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

/**
 * Handles admin menu registration and asset loading.
 */
class WPLTA_Admin {

	/**
	 * Singleton instance.
	 *
	 * @var WPLTA_Admin|null
	 */
	private static $instance = null;

	/**
	 * Get instance.
	 *
	 * @return WPLTA_Admin
	 */
	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Register hooks.
	 */
	private function __construct() {
		add_action( 'admin_menu', array( $this, 'register_admin_menu' ) );
		add_action( 'admin_init', array( $this, 'maybe_skip_connect_screen' ), 1 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'wp_ajax_wplta_dashboard_refresh', array( $this, 'handle_dashboard_refresh' ) );
		add_action( 'wp_ajax_wplta_activate_license', array( $this, 'handle_activate_license' ) );
		add_action( 'wp_ajax_wplta_save_settings', array( $this, 'handle_save_settings' ) );
		add_action( 'wp_ajax_wplta_get_storage_usage', array( $this, 'handle_get_storage_usage' ) );
		add_action( 'wp_ajax_wplta_reset_data', array( $this, 'handle_reset_data' ) );
		// Priority 5 so this runs before Freemius' own admin_notices hook (priority 10),
		// removing its stored "activated/upgraded" sticky notices before they render.
		add_action( 'admin_notices', array( $this, 'suppress_freemius_upgrade_notices' ), 5 );
	}

	/**
	 * Return how much DB storage the plugin's own tables are using, for the
	 * Settings tab's "Database usage" card.
	 *
	 * @return void
	 */
	public function handle_get_storage_usage() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error(
				array( 'message' => __( 'You are not allowed to view this.', 'live-traffic-analytics' ) ),
				403
			);
		}

		check_ajax_referer( 'wplta_admin_dashboard' );

		wp_send_json_success( WPLTA_Repository::get_storage_usage() );
	}

	/**
	 * Permanently delete all tracked analytics data (activity, sessions, page
	 * stats) from the Settings tab's "Reset data" action. Requires
	 * manage_options and a valid nonce -- irreversible once run.
	 *
	 * @return void
	 */
	public function handle_reset_data() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error(
				array( 'message' => __( 'You are not allowed to delete this data.', 'live-traffic-analytics' ) ),
				403
			);
		}

		check_ajax_referer( 'wplta_admin_dashboard' );

		WPLTA_Repository::reset_all_data();

		wp_send_json_success( WPLTA_Repository::get_storage_usage() );
	}

	/**
	 * Activate the most recently used license for this Freemius account, with
	 * a single click and no popup/manual key entry -- mirrors how "Deactivate
	 * License" already works. Freemius remembers previously-used license keys
	 * per account (this is the same list its own native "Activate License"
	 * dialog offers as a pre-selected option).
	 *
	 * @return void
	 */
	public function handle_activate_license() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error(
				array( 'message' => __( 'You are not allowed to manage the license.', 'live-traffic-analytics' ) ),
				403
			);
		}

		check_ajax_referer( 'wplta_admin_dashboard' );

		if ( ! function_exists( 'wplta_fs' ) ) {
			wp_send_json_error(
				array( 'message' => __( 'Licensing is unavailable on this site.', 'live-traffic-analytics' ) )
			);
		}

		$fs          = wplta_fs();
		$license_key = isset( $_POST['license_key'] ) ? sanitize_text_field( wp_unslash( $_POST['license_key'] ) ) : '';

		// If the user pasted a key in the dashboard field, activate that exact key.
		// Otherwise fall back to the most recent license Freemius remembers for
		// this account (one-click re-activation after a deactivate).
		if ( '' === $license_key ) {
			$licenses = $fs->get_available_premium_licenses();

			if ( empty( $licenses ) ) {
				wp_send_json_error(
					array(
						'message' => __( 'Please enter your license key to activate.', 'live-traffic-analytics' ),
					)
				);
			}

			$license                = reset( $licenses );
			$_POST['license_id']    = $license->id;
			$_REQUEST['license_id'] = $license->id;
		} else {
			$_POST['license_key']    = $license_key;
			$_REQUEST['license_key'] = $license_key;
		}

		// Reuse Freemius' own AJAX handler so the exact same activation logic,
		// permission checks, and response shape as its native dialog are used --
		// just driven from our own License-tab UI instead of the popup. Freemius'
		// handler reads the nonce and the license key/id from $_REQUEST (and its
		// own 'activate_license' nonce, not our dashboard nonce), so both $_POST
		// and $_REQUEST must carry the values it expects.
		$security             = $fs->get_ajax_security( 'activate_license' );
		$_POST['security']    = $security;
		$_REQUEST['security'] = $security;

		$fs->_activate_license_ajax_action(); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals -- Freemius SDK method call, not a declaration.
	}

	/**
	 * This plugin ships as a single package (no separate "premium" zip), so
	 * Freemius' post-activation notices that ask the user to "download the
	 * latest PRO version and upload/activate it" don't apply and would only
	 * confuse users. Remove them before they render.
	 *
	 * @return void
	 */
	public function suppress_freemius_upgrade_notices() {
		if ( ! function_exists( 'wplta_fs' ) ) {
			return;
		}

		wplta_fs()->remove_sticky(
			array( 'plan_upgraded', 'trial_started', 'premium_activated' )
		);
	}

	/**
	 * Bypass Freemius' first-time "connect" screen so the plugin's own
	 * dashboard opens immediately after activation. Users can still activate
	 * a license anytime from the dashboard's License tab.
	 *
	 * @return void
	 */
	public function maybe_skip_connect_screen() {
		if ( ! function_exists( 'wplta_fs' ) ) {
			return;
		}

		$fs = wplta_fs();

		if ( $fs->is_activation_mode() && ! wplta_is_pro() ) {
			$fs->skip_connection();
		}
	}

	/**
	 * Register plugin admin page.
	 *
	 * @return void
	 */
	public function register_admin_menu() {
		add_menu_page(
			__( 'Live Traffic Analytics', 'live-traffic-analytics' ),
			__( 'Traffic Analytics', 'live-traffic-analytics' ),
			'manage_options',
			'wplta-dashboard',
			array( $this, 'render_dashboard_page' ),
			'dashicons-chart-area',
			25
		);
	}

	/**
	 * Render the React app root.
	 *
	 * @return void
	 */
	public function render_dashboard_page() {
		echo '<div class="wrap">';
		/*
		 * WordPress core's admin JS relocates admin notices to right after the
		 * ".wp-header-end" marker. Without one, it falls back to the first
		 * "h1"/"h2" inside ".wrap", which would drag notices (e.g. Freemius'
		 * "plan upgraded" notice) into the middle of the React app. Providing
		 * the marker keeps notices at the top of the page where they belong.
		 */
		echo '<hr class="wp-header-end" />';
		echo '<div id="live-traffic-analytics-app"></div>';
		$this->render_license_controls();
		echo '</div>';
	}

	/**
	 * Render Freemius' hidden deactivation form so the dashboard's License tab
	 * "Deactivate License" button can submit it without leaving the SPA.
	 *
	 * Note: license *activation* no longer renders Freemius' popup dialog here --
	 * the License tab activates the account's remembered license directly via the
	 * wplta_activate_license AJAX action (see handle_activate_license()).
	 *
	 * @return void
	 */
	private function render_license_controls() {
		if ( ! function_exists( 'wplta_fs' ) ) {
			return;
		}

		$fs = wplta_fs();

		if ( ! wplta_is_pro() ) {
			return;
		}

		// Freemius' official deactivate-license form, kept hidden — the dashboard's
		// "Deactivate License" button finds and submits this exact form via JS so the
		// correct Freemius nonce/action is always used.
		$deactivate_vars = array(
			'slug'       => $fs->get_slug(),
			'freemius'   => $fs,
			'blog_id'    => '',
			'install_id' => '',
			'class'      => 'wplta-deactivate-license-btn',
		);

		echo '<div class="screen-reader-text" aria-hidden="true">';
		echo fs_get_template( 'account/partials/deactivate-license-button.php', $deactivate_vars ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo '</div>';
	}

	/**
	 * Build the Single Site checkout URL with the onboarding coupon appended,
	 * so the checkout page can auto-apply the discount.
	 *
	 * @return string
	 */
	private function get_single_site_checkout_url_with_coupon() {
		if ( wplta_is_pro() || ! function_exists( 'wplta_get_single_site_checkout_url' ) ) {
			return '';
		}

		$url = wplta_get_single_site_checkout_url();

		if ( empty( $url ) ) {
			return '';
		}

		$coupon = WPLTA_Settings::get_onboarding_coupon();

		if ( '' !== $coupon ) {
			$url = add_query_arg( 'coupon', rawurlencode( $coupon ), $url );
		}

		return $url;
	}

	/**
	 * Save dashboard refresh / tracking heartbeat settings from the
	 * dashboard's own Settings tab.
	 *
	 * @return void
	 */
	public function handle_save_settings() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error(
				array( 'message' => __( 'You are not allowed to change settings.', 'live-traffic-analytics' ) ),
				403
			);
		}

		check_ajax_referer( 'wplta_admin_dashboard' );

		$dashboard_refresh = WPLTA_Settings::sanitize_interval(
			isset( $_POST['dashboard_refresh_ms'] ) ? absint( wp_unslash( $_POST['dashboard_refresh_ms'] ) ) : 0,
			WPLTA_Settings::DEFAULT_DASHBOARD_REFRESH
		);

		$tracking_heartbeat = WPLTA_Settings::sanitize_interval(
			isset( $_POST['tracking_heartbeat_ms'] ) ? absint( wp_unslash( $_POST['tracking_heartbeat_ms'] ) ) : 0,
			WPLTA_Settings::DEFAULT_TRACKING_HEARTBEAT
		);

		update_option( WPLTA_Settings::OPTION_DASHBOARD_REFRESH, $dashboard_refresh );
		update_option( WPLTA_Settings::OPTION_TRACKING_HEARTBEAT, $tracking_heartbeat );

		wp_send_json_success(
			array(
				'dashboard_refresh_ms'  => $dashboard_refresh,
				'tracking_heartbeat_ms' => $tracking_heartbeat,
				'refresh_label'         => sprintf(
					/* translators: %s: refresh interval label. */
					__( 'Auto-refresh every %s', 'live-traffic-analytics' ),
					WPLTA_Settings::format_interval_label( $dashboard_refresh )
				),
			)
		);
	}

	/**
	 * Enqueue admin assets.
	 *
	 * @param string $hook_suffix Current page hook.
	 * @return void
	 */
	public function enqueue_assets( $hook_suffix ) {
		if ( 'toplevel_page_wplta-dashboard' !== $hook_suffix || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$asset_file = WPLTA_PLUGIN_DIR . 'build/index.asset.php';
		$assets     = file_exists( $asset_file ) ? require $asset_file : array(
			'dependencies' => array( 'react', 'react-dom', 'react-jsx-runtime' ),
			'version'      => WPLTA_VERSION,
		);
		$user       = wp_get_current_user();

		wp_enqueue_script(
			'wplta-dashboard',
			WPLTA_PLUGIN_URL . 'build/index.js',
			array_unique( array_merge( $assets['dependencies'], array( 'jquery' ) ) ),
			$assets['version'],
			true
		);

		if ( function_exists( 'fs_enqueue_local_style' ) ) {
			// Styles for Freemius' license activation/deactivation dialog rendered on this page.
			fs_enqueue_local_style( 'fs_common', '/admin/common.css' );
			fs_enqueue_local_style( 'fs_dialog_boxes', '/admin/dialog-boxes.css' );
		}

			wp_enqueue_style(
				'wplta-dashboard',
				WPLTA_PLUGIN_URL . 'build/index.css',
				array(),
				$assets['version']
			);

			$interval_options = array();
			foreach ( WPLTA_Settings::get_interval_options() as $value => $label ) {
				$interval_options[] = array(
					'value' => $value,
					'label' => $label,
				);
			}

			wp_localize_script(
				'wplta-dashboard',
				'wpltaAdmin',
				array(
				'restUrl'           => esc_url_raw( rest_url( 'wplta/v1/admin' ) ),
				'ajaxUrl'           => admin_url( 'admin-ajax.php' ),
				'nonce'             => wp_create_nonce( 'wp_rest' ),
				'ajaxNonce'         => wp_create_nonce( 'wplta_admin_dashboard' ),
				'pluginUrl'         => WPLTA_PLUGIN_URL,
				'pluginName'        => __( 'Live Traffic Analytics', 'live-traffic-analytics' ),
				'adminName'         => $user->display_name,
				'adminAvatar'       => get_avatar_url( $user->ID ),
				'refreshEvery'      => WPLTA_Settings::get_dashboard_refresh_ms(),
				'refreshLabel'      => sprintf(
					/* translators: %s: refresh interval label. */
					__( 'Auto-refresh every %s', 'live-traffic-analytics' ),
					WPLTA_Settings::format_interval_label( WPLTA_Settings::get_dashboard_refresh_ms() )
				),
				'activeWindowLabel' => WPLTA_Settings::get_active_window_hint(),
				'isPro'             => function_exists( 'wplta_is_pro' ) && wplta_is_pro(),
				'upgradeUrl'        => function_exists( 'wplta_fs' ) ? wplta_fs()->get_upgrade_url() : '',
				'onboardingCoupon'    => WPLTA_Settings::get_onboarding_coupon(),
				'singleSiteCheckoutUrl' => $this->get_single_site_checkout_url_with_coupon(),
				'intervalOptions'   => $interval_options,
				'settings'          => array(
					'dashboardRefreshMs'  => WPLTA_Settings::get_dashboard_refresh_ms(),
					'trackingHeartbeatMs' => WPLTA_Settings::get_tracking_heartbeat_ms(),
				),
			)
		);
	}

	/**
	 * Return dashboard payload via admin AJAX.
	 *
	 * @return void
	 */
	public function handle_dashboard_refresh() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error(
				array(
					'message' => __( 'You are not allowed to view analytics.', 'live-traffic-analytics' ),
				),
				403
			);
		}

		check_ajax_referer( 'wplta_admin_dashboard' );

		wp_send_json_success(
			WPLTA_Repository::get_admin_dashboard_payload()
		);
	}
}
