<?php
/**
 * Admin Class
 *
 * @package ResponsiveMobileSelect\Admin
 * @since 2.0.0
 */

namespace ResponsiveMobileSelect\Admin;

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

use ResponsiveMobileSelect\Core\Settings;

/**
 * Admin-Integration (Menü, Assets, AJAX, Page-Render).
 * Strikt per Site – keine Netzwerk-Eingriffe.
 */
class Admin {

	/**
	 * Page-Slug für die Einstellungsseite.
	 *
	 * @var string
	 */
	const PAGE_SLUG = 'responsive-menu';

	/**
	 * Settings-Instanz (optional vom Plugin durchgereicht).
	 *
	 * @var \ResponsiveMobileSelect\Core\Settings|null
	 */
	protected $settings;

	/**
	 * Konstruktor – nimmt optional eine Settings-Instanz entgegen.
	 *
	 * Wichtig: Keine Hooks hier registrieren, damit Plugin::init() -> $admin->init()
	 * weiterhin funktioniert (und Doppel-Registrierungen vermieden werden).
	 *
	 * @param \ResponsiveMobileSelect\Core\Settings|null $settings Settings (optional).
	 */
	public function __construct( $settings = null ) {
		if ( $settings instanceof Settings ) {
			$this->settings = $settings;
		}
	}

	/**
	 * Kompatibilitätsmethode: wird vom Core-Plugin explizit aufgerufen.
	 * Hier registrieren wir alle Admin-Hooks.
	 */
	public function init() {
		add_action( 'admin_menu', array( $this, 'add_admin_page' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );

		// AJAX: Speichern & Reset.
		add_action( 'wp_ajax_rms_save_settings', array( $this, 'ajax_save_settings' ) );
		add_action( 'wp_ajax_rms_reset_settings', array( $this, 'ajax_reset_settings' ) );
	}

	/**
	 * Submenü „Responsive Mobile Select“ unter „Design“.
	 */
	public function add_admin_page() {
		add_theme_page(
			__( 'Responsive Mobile Select Menu', 'responsive-mobile-select-menu' ),
			__( 'Mobile Select Menu', 'responsive-mobile-select-menu' ),
			'manage_options',
			self::PAGE_SLUG,
			array( $this, 'render_admin_page' )
		);
	}

	/**
	 * Assets nur auf unserer Admin-Seite laden.
	 *
	 * @param string $hook_suffix Aktuelles Admin-Hook.
	 */
	public function enqueue_admin_assets( $hook_suffix ) {
		// Nur auf unserer Unterseite unter „Design":
		if ( 'appearance_page_' . self::PAGE_SLUG !== $hook_suffix ) {
			return;
		}

		// Admin CSS laden.
		wp_enqueue_style(
			'responsive-mobile-select-menu-admin',
			RESPONSIVE_MOBILE_SELECT_PLUGIN_URL . 'admin/css/admin.css',
			array(),
			RESPONSIVE_MOBILE_SELECT_VERSION
		);

		// (Optional) Styles – wenn vorhanden.
		wp_enqueue_style( 'wp-components' );

		// Admin-Script.
		wp_enqueue_script(
			'responsive-mobile-select-menu-admin',
			RESPONSIVE_MOBILE_SELECT_PLUGIN_URL . 'admin/js/admin.js',
			array( 'jquery', 'wp-components' ),
			RESPONSIVE_MOBILE_SELECT_VERSION,
			true
		);

		// Daten für JS.
		wp_localize_script(
			'responsive-mobile-select-menu-admin',
			'rmsAdmin',
			array(
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'rms_settings' ),
				'i18n'     => array(
					'confirm_reset' => __( 'Reset settings to defaults?', 'responsive-mobile-select-menu' ),
					'saved'         => __( 'Settings saved.', 'responsive-mobile-select-menu' ),
					'error'         => __( 'Error saving settings.', 'responsive-mobile-select-menu' ),
				),
			)
		);
	}

	/**
	 * Render der Admin-Seite.
	 */
	public function render_admin_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// Wenn die Settings-Instanz vom Core gereicht wurde, nutze sie; sonst frisch laden.
		$settings = $this->settings instanceof Settings ? $this->settings : new Settings();
		$data     = $settings->all(); // Array der aktuellen Werte.

		$page_slug = self::PAGE_SLUG;

		require RESPONSIVE_MOBILE_SELECT_PLUGIN_DIR . 'admin/views/admin-page.php';
	}

	/**
	 * AJAX: Einstellungen speichern.
	 * Erwartet eine flache Payload (Feldnamen wie im Formular),
	 * verarbeitet zentral via Settings::update_from_form() und save().
	 */
	public function ajax_save_settings() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'forbidden' ), 403 );
		}

		check_ajax_referer( 'rms_settings', 'nonce' );

		// Rohdaten (ohne action/nonce).
		$raw = $_POST; // phpcs:ignore WordPress.Security.NonceVerification.Missing
		unset( $raw['action'], $raw['nonce'] );

		$settings = $this->settings instanceof Settings ? $this->settings : new Settings();
		$settings->update_from_form( $raw );

		$ok = $settings->save();

		if ( $ok ) {
			wp_send_json_success(
				array(
					'saved' => true,
				)
			);
		}

		wp_send_json_error( array( 'saved' => false ) );
	}

	/**
	 * AJAX: Einstellungen auf Defaults zurücksetzen.
	 */
	public function ajax_reset_settings() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'forbidden' ), 403 );
		}

		check_ajax_referer( 'rms_settings', 'nonce' );

		$settings = $this->settings instanceof Settings ? $this->settings : new Settings();
		$settings->reset_to_defaults();
		$ok = $settings->save();

		if ( $ok ) {
			wp_send_json_success( array( 'reset' => true ) );
		}

		wp_send_json_error( array( 'reset' => false ) );
	}
}
