<?php
/**
 * Admin settings page.
 *
 * @package MacaHold
 */

defined( 'ABSPATH' ) || exit;

/**
 * Admin UI and settings handling.
 */
class Maca_Hold_Admin_Page {

	/**
	 * Admin menu slug.
	 */
	private const MENU_SLUG = 'maca-hold';

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'load-toplevel_page_maca-hold', array( $this, 'prepare_admin_page' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_plugins_screen_scripts' ) );
		add_action( 'wp_ajax_maca_hold_toggle_maintenance', array( $this, 'ajax_toggle_maintenance' ) );
		add_action( 'admin_post_maca_hold_save_settings', array( $this, 'handle_save' ) );
		add_action( 'admin_post_maca_hold_export_settings', array( $this, 'handle_export' ) );
		add_action( 'admin_post_maca_hold_import_settings', array( $this, 'handle_import' ) );
		add_action( 'admin_post_maca_hold_dismiss_setup', array( $this, 'handle_dismiss_setup' ) );
		add_action( 'admin_post_maca_hold_regenerate_token', array( $this, 'handle_regenerate_token' ) );
		add_action( 'wp_ajax_maca_hold_set_background', array( $this, 'ajax_set_background' ) );
		add_action( 'admin_bar_menu', array( $this, 'admin_bar_indicator' ), 100 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_bar_assets' ) );
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_admin_bar_assets' ) );
		add_action( 'admin_notices', array( $this, 'render_setup_notice' ) );
		add_filter( 'plugin_action_links_' . plugin_basename( MACA_HOLD_FILE ), array( $this, 'plugin_action_links' ) );
	}

	/**
	 * Register top-level admin menu page.
	 *
	 * @return void
	 */
	public function register_menu() {
		$page_title = Maca_Hold_I18n::get_plugin_name();

		add_menu_page(
			$page_title,
			$page_title,
			'manage_options',
			self::MENU_SLUG,
			array( $this, 'render_page' ),
			'dashicons-lock',
			81
		);
	}

	/**
	 * Ensure WordPress has a page title before admin-header.php runs.
	 *
	 * @return void
	 */
	public function prepare_admin_page() {
		global $title;

		$title = Maca_Hold_I18n::get_plugin_name();
	}

	/**
	 * Get the plugin settings page URL.
	 *
	 * @param array<string, string> $args Optional query arguments.
	 * @return string
	 */
	public static function get_page_url( array $args = array() ) {
		$url = admin_url( 'admin.php?page=' . self::MENU_SLUG );

		if ( ! empty( $args ) ) {
			$url = add_query_arg( $args, $url );
		}

		return $url;
	}

	/**
	 * Registered admin tabs for the settings screen.
	 *
	 * @return array<string, string> Tab slug => label.
	 */
	public static function get_admin_tabs() {
		/**
		 * Filter admin tabs on the maca Hold settings screen.
		 *
		 * @param array<string, string> $tabs Tab slug => label.
		 */
		return apply_filters(
			'maca_hold_admin_tabs',
			array(
				'general'  => __( 'Settings', 'maca-hold' ),
				'advanced' => __( 'Advanced', 'maca-hold' ),
			)
		);
	}

	/**
	 * Current admin tab slug.
	 *
	 * @return string
	 */
	public static function get_current_tab() {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Tab navigation only.
		$tab  = isset( $_GET['tab'] ) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'general';
		$tabs = self::get_admin_tabs();

		return isset( $tabs[ $tab ] ) ? $tab : 'general';
	}

	/**
	 * Enqueue admin assets on plugin page.
	 *
	 * @param string $hook Current admin hook.
	 * @return void
	 */
	/**
	 * Scripts on the Plugins screen (deactivation feedback modal).
	 *
	 * @param string $hook Current admin page hook.
	 * @return void
	 */
	public function enqueue_plugins_screen_scripts( $hook ) {
		if ( 'plugins.php' !== $hook ) {
			return;
		}

		require_once MACA_HOLD_PATH . 'includes/deactivation-feedback.php';

		wp_enqueue_style(
			'maca-hold-admin-plugins',
			MACA_HOLD_URL . 'assets/css/admin-plugins.css',
			array(),
			MACA_HOLD_VERSION
		);

		wp_enqueue_script(
			'maca-hold-admin-plugins',
			MACA_HOLD_URL . 'assets/js/admin-plugins.js',
			array(),
			MACA_HOLD_VERSION,
			true
		);

		$reasons = array();
		foreach ( maca_hold_deactivation_feedback_reasons() as $id => $label ) {
			$reasons[] = array(
				'id'    => $id,
				'label' => $label,
			);
		}

		wp_localize_script(
			'maca-hold-admin-plugins',
			'macaHoldPlugins',
			array(
				'pluginSlug'         => plugin_basename( MACA_HOLD_FILE ),
				'ajaxUrl'            => admin_url( 'admin-ajax.php' ),
				'nonce'              => wp_create_nonce( 'maca_hold_deactivation_feedback' ),
				'modalTitle'         => __( 'Before you deactivate maca Hold', 'maca-hold' ),
				'modalIntro'         => __( 'Help us improve — what is the main reason you are deactivating?', 'maca-hold' ),
				'detailsPlaceholder' => __( 'Tell us a bit more (optional)', 'maca-hold' ),
				'cancelLabel'        => __( 'Cancel', 'maca-hold' ),
				'skipLabel'          => __( 'Skip and deactivate', 'maca-hold' ),
				'submitLabel'        => __( 'Send feedback and deactivate', 'maca-hold' ),
				'reasons'            => $reasons,
			)
		);
	}

	/**
	 * Enqueue admin assets on plugin page.
	 *
	 * @param string $hook Current admin hook.
	 * @return void
	 */
	public function enqueue_assets( $hook ) {
		if ( 'toplevel_page_maca-hold' !== $hook ) {
			return;
		}

		wp_enqueue_style(
			'maca-hold-admin',
			MACA_HOLD_URL . 'assets/css/admin.css',
			array(),
			MACA_HOLD_VERSION
		);

		wp_enqueue_script(
			'maca-hold-admin',
			MACA_HOLD_URL . 'assets/js/admin.js',
			array(),
			MACA_HOLD_VERSION,
			true
		);

		wp_localize_script(
			'maca-hold-admin',
			'macaHoldAdmin',
			array_merge(
				Maca_Hold_I18n::get_admin_script_strings(),
				array(
					'ajaxUrl'                     => admin_url( 'admin-ajax.php' ),
					'nonce'                       => wp_create_nonce( 'maca_hold_admin' ),
					'toggleConfirm'               => Maca_Hold_Maintenance_Scope::get_toggle_confirm_messages(),
					'maintenanceActivated'        => __( 'Maintenance mode activated.', 'maca-hold' ),
					'maintenanceDeactivated'      => __( 'Maintenance mode deactivated. The site is public.', 'maca-hold' ),
					'maintenanceActiveStatus'     => __( 'Maintenance mode is active. Visitors receive HTTP 503.', 'maca-hold' ),
					'maintenanceInactiveStatus'   => __( 'Maintenance mode is inactive. The site is public.', 'maca-hold' ),
					'scheduleControlsMaintenance' => __( 'Scheduled maintenance is enabled. Turn off the schedule in settings to use this switch.', 'maca-hold' ),
					'toggleError'                 => __( 'Could not update maintenance mode.', 'maca-hold' ),
					'maintenanceActiveLabel'      => __( 'Maintenance active', 'maca-hold' ),
					'sitePublicLabel'             => __( 'Site public', 'maca-hold' ),
					'pagesMaintenanceLabel'       => __( 'Pages under maintenance', 'maca-hold' ),
				)
			)
		);
	}

	/**
	 * Add quick settings link on plugins screen.
	 *
	 * @param array<int, string> $links Plugin action links.
	 * @return array<int, string>
	 */
	public function plugin_action_links( $links ) {
		$url = self::get_page_url();

		array_unshift(
			$links,
			sprintf(
				'<a href="%s">%s</a>',
				esc_url( $url ),
				esc_html__( 'Settings', 'maca-hold' )
			)
		);

		return $links;
	}

	/**
	 * Enqueue admin bar status lamp styles.
	 *
	 * @return void
	 */
	public function enqueue_admin_bar_assets() {
		if ( ! is_admin_bar_showing() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		wp_enqueue_style(
			'maca-hold-admin-bar',
			MACA_HOLD_URL . 'assets/css/admin-bar.css',
			array(),
			MACA_HOLD_VERSION
		);
	}

	/**
	 * Render admin bar status lamp for administrators.
	 *
	 * @param WP_Admin_Bar $admin_bar Admin bar instance.
	 * @return void
	 */
	public function admin_bar_indicator( $admin_bar ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$is_active = Maca_Hold_Settings::is_active();
		$lamp_class = Maca_Hold_Maintenance_Scope::is_maintenance_visible() ? 'maca-hold-lamp--on' : 'maca-hold-lamp--off';
		$status_text = Maca_Hold_Maintenance_Scope::get_admin_bar_status_text();

		$node_title = sprintf(
			'<span class="maca-hold-admin-bar-title"><span class="maca-hold-lamp %1$s" aria-hidden="true"></span><span class="maca-hold-admin-bar-label">%2$s</span><span class="maca-hold-admin-bar-state">%3$s</span></span>',
			esc_attr( $lamp_class ),
			esc_html( Maca_Hold_I18n::get_plugin_name() ),
			esc_html( $status_text )
		);

		$admin_bar->add_node(
			array(
				'id'    => 'maca-hold-status',
				'title' => $node_title,
				'href'  => self::get_page_url(),
				'meta'  => array(
					'class' => Maca_Hold_Maintenance_Scope::is_maintenance_visible() ? 'maca-hold-admin-bar-active' : 'maca-hold-admin-bar-inactive',
					'title' => $status_text,
				),
			)
		);
	}

	/**
	 * First-run setup notice.
	 *
	 * @return void
	 */
	public function render_setup_notice() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$settings = Maca_Hold_Settings::get();
		if ( ! empty( $settings['setup_dismissed'] ) ) {
			return;
		}

		$dismiss_url = wp_nonce_url(
			admin_url( 'admin-post.php?action=maca_hold_dismiss_setup' ),
			'maca_hold_dismiss_setup'
		);

		echo '<div class="notice notice-info is-dismissible maca-hold-setup-notice">';
		echo '<p><strong>' . esc_html( sprintf(
			/* translators: %s: plugin name */
			__( '%s is ready.', 'maca-hold' ),
			Maca_Hold_I18n::get_plugin_name()
		) ) . '</strong> ';
		echo esc_html__( 'Add your IP to the whitelist, save the secret bypass link, then enable maintenance mode when you are ready.', 'maca-hold' );
		echo '</p>';
		echo '<p><a class="button button-primary" href="' . esc_url( self::get_page_url() ) . '">';
		echo esc_html__( 'Open settings', 'maca-hold' ) . '</a> ';
		echo '<a class="button button-secondary" href="' . esc_url( $dismiss_url ) . '">';
		echo esc_html__( 'Dismiss', 'maca-hold' ) . '</a></p>';
		echo '</div>';
	}

	/**
	 * Render settings page.
	 *
	 * @return void
	 */
	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'maca-hold' ) );
		}

		global $title;

		if ( ! is_string( $title ) || '' === $title ) {
			$title = Maca_Hold_I18n::get_plugin_name();
		}

		$settings     = Maca_Hold_Settings::get();
		$is_active    = Maca_Hold_Settings::is_active();
		$current_tab  = self::get_current_tab();
		$tabs         = self::get_admin_tabs();
		$preview_url  = wp_nonce_url( add_query_arg( 'maca_hold_preview', '1', home_url( '/' ) ), 'maca_hold_preview' );
		$bypass_url   = add_query_arg( 'maca_hold', $settings['secret_token'], home_url( '/' ) );
		$roles        = wp_roles()->roles;
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Admin flash message after redirect.
		$message      = isset( $_GET['maca_hold_message'] ) ? sanitize_key( wp_unslash( $_GET['maca_hold_message'] ) ) : '';
		$schedule_sum = Maca_Hold_Scheduler::get_summary( $settings );
		$backgrounds  = Maca_Hold_Backgrounds::get_available();

		echo '<div class="wrap maca-hold-admin">';
		echo '<h1>' . esc_html( Maca_Hold_I18n::get_plugin_name() ) . '</h1>';
		include MACA_HOLD_PATH . 'admin/views/partials/maintenance-toggle.php';
		include MACA_HOLD_PATH . 'admin/views/partials/nav-tabs.php';

		if ( 'general' === $current_tab ) {
			include MACA_HOLD_PATH . 'admin/views/settings-page.php';
		} elseif ( 'advanced' === $current_tab ) {
			$pages = get_pages(
				array(
					'sort_column' => 'post_title',
					'sort_order'  => 'ASC',
				)
			);
			include MACA_HOLD_PATH . 'admin/views/advanced-page.php';
		} else {
			/**
			 * Render a custom maca Hold admin tab.
			 *
			 * Dynamic hook: maca_hold_render_admin_tab_{$tab}
			 */
			do_action( 'maca_hold_render_admin_tab_' . $current_tab );
		}

		echo '</div>';
	}

	/**
	 * Toggle maintenance mode immediately via AJAX.
	 *
	 * @return void
	 */
	public function ajax_toggle_maintenance() {
		check_ajax_referer( 'maca_hold_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error(
				array(
					'message' => __( 'You do not have permission to perform this action.', 'maca-hold' ),
				),
				403
			);
		}

		$enable   = isset( $_POST['enabled'] ) && '1' === sanitize_text_field( wp_unslash( $_POST['enabled'] ) );
		$settings = Maca_Hold_Settings::get();

		if ( ! empty( $settings['schedule_enabled'] ) ) {
			wp_send_json_error(
				array(
					'message' => __( 'Scheduled maintenance is enabled. Turn off the schedule in settings to use this switch.', 'maca-hold' ),
				)
			);
		}

		$settings['enabled'] = $enable;
		Maca_Hold_Settings::update( $settings );

		$is_active = Maca_Hold_Settings::is_active();

		wp_send_json_success(
			array(
				'enabled'             => $enable,
				'is_active'           => $is_active,
				'maintenance_visible' => Maca_Hold_Maintenance_Scope::is_maintenance_visible(),
				'message'             => Maca_Hold_Maintenance_Scope::get_toggle_feedback_message( $enable ),
				'status_text'         => Maca_Hold_Maintenance_Scope::get_status_text(),
				'admin_bar_status'    => Maca_Hold_Maintenance_Scope::get_admin_bar_status_text(),
			)
		);
	}

	/**
	 * Save settings form.
	 *
	 * @return void
	 */
	public function handle_save() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'maca-hold' ) );
		}

		check_admin_referer( 'maca_hold_save_settings' );

		$incoming = wp_unslash( $_POST );
		$current  = Maca_Hold_Settings::get();
		$is_advanced = ! empty( $incoming['maca_hold_advanced_save'] );

		if ( $is_advanced ) {
			$settings = array_merge( $current, Maca_Hold_Settings::from_advanced_post( $incoming ) );
		} else {
			$settings = array_merge( $current, Maca_Hold_Settings::from_post( $incoming ) );
		}

		Maca_Hold_Settings::update( $settings );

		$redirect_args = array(
			'maca_hold_message' => 'saved',
		);

		if ( $is_advanced ) {
			$redirect_args['tab'] = 'advanced';
		}

		wp_safe_redirect(
			self::get_page_url( $redirect_args )
		);
		exit;
	}

	/**
	 * Export settings as JSON download.
	 *
	 * @return void
	 */
	public function handle_export() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'maca-hold' ) );
		}

		check_admin_referer( 'maca_hold_export_settings' );

		$settings = Maca_Hold_Settings::get();
		$payload  = wp_json_encode( $settings, JSON_PRETTY_PRINT );

		if ( false === $payload ) {
			wp_die( esc_html__( 'Could not export settings.', 'maca-hold' ) );
		}

		nocache_headers();
		header( 'Content-Type: application/json; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename=maca-hold-settings.json' );
		echo $payload; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		exit;
	}

	/**
	 * Import settings from uploaded JSON.
	 *
	 * @return void
	 */
	public function handle_import() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'maca-hold' ) );
		}

		check_admin_referer( 'maca_hold_import_settings' );

		if ( empty( $_FILES['maca_hold_import_file']['tmp_name'] ) ) {
			wp_die( esc_html__( 'No file uploaded.', 'maca-hold' ) );
		}

		$tmp_name = isset( $_FILES['maca_hold_import_file']['tmp_name'] )
			? sanitize_text_field( wp_unslash( $_FILES['maca_hold_import_file']['tmp_name'] ) )
			: '';

		if ( '' === $tmp_name || ! is_uploaded_file( $tmp_name ) ) {
			wp_die( esc_html__( 'Invalid upload.', 'maca-hold' ) );
		}

		$raw  = file_get_contents( $tmp_name ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
		$data = json_decode( $raw, true );

		if ( ! is_array( $data ) ) {
			wp_die( esc_html__( 'Invalid settings file.', 'maca-hold' ) );
		}

		Maca_Hold_Settings::update( $data );

		wp_safe_redirect(
			self::get_page_url(
				array(
					'maca_hold_message' => 'imported',
				)
			)
		);
		exit;
	}

	/**
	 * Dismiss setup notice.
	 *
	 * @return void
	 */
	public function handle_dismiss_setup() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'maca-hold' ) );
		}

		check_admin_referer( 'maca_hold_dismiss_setup' );

		$settings                    = Maca_Hold_Settings::get();
		$settings['setup_dismissed'] = true;
		Maca_Hold_Settings::update( $settings );

		wp_safe_redirect( self::get_page_url() );
		exit;
	}

	/**
	 * Regenerate secret bypass token.
	 *
	 * @return void
	 */
	public function handle_regenerate_token() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to perform this action.', 'maca-hold' ) );
		}

		check_admin_referer( 'maca_hold_regenerate_token' );

		$settings                    = Maca_Hold_Settings::get();
		$settings['secret_token']    = Maca_Hold_Settings::generate_secret_token();
		Maca_Hold_Settings::update( $settings );

		wp_safe_redirect(
			self::get_page_url(
				array(
					'maca_hold_message' => 'token_regenerated',
				)
			)
		);
		exit;
	}

	/**
	 * Save background image immediately when selected in admin.
	 *
	 * @return void
	 */
	public function ajax_set_background() {
		check_ajax_referer( 'maca_hold_admin', 'nonce' );

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error(
				array(
					'message' => __( 'You do not have permission to perform this action.', 'maca-hold' ),
				),
				403
			);
		}

		$background_slug = isset( $_POST['background_image'] )
			? Maca_Hold_Backgrounds::sanitize( sanitize_text_field( wp_unslash( $_POST['background_image'] ) ) )
			: '';

		$settings                     = Maca_Hold_Settings::get();
		$settings['background_image'] = $background_slug;
		Maca_Hold_Settings::update( $settings );

		$settings = Maca_Hold_Settings::get();

		wp_send_json_success(
			array(
				'background_image' => $settings['background_image'],
				'message'          => __( 'Background updated.', 'maca-hold' ),
			)
		);
	}
}
