<?php
defined( 'ABSPATH' ) || exit;

class BW_WebP_Admin {

	const PAGE_SLUG = 'bw-webp';

	private BW_WebP_Settings $settings;
	private BW_WebP_Manifest $manifest;
	private BW_WebP_Rewrite $rewrite;

	public function __construct( BW_WebP_Settings $settings, BW_WebP_Manifest $manifest, BW_WebP_Rewrite $rewrite ) {
		$this->settings = $settings;
		$this->manifest = $manifest;
		$this->rewrite  = $rewrite;
	}

	public function register_hooks(): void {
		add_action( 'admin_menu',            array( $this, 'menu' ) );
		add_action( 'admin_init',            array( $this, 'maybe_save' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'assets' ) );
	}

	public function menu(): void {
		add_options_page(
			__( 'BW WebP', 'bw-webp' ),
			__( 'BW WebP', 'bw-webp' ),
			'manage_options',
			self::PAGE_SLUG,
			array( $this, 'render' )
		);
	}

	public function maybe_save(): void {
		if ( empty( $_POST['bw_webp_save'] ) ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Insufficient permissions.', 'bw-webp' ) );
		}
		check_admin_referer( 'bw_webp_save_settings' );

		$input = wp_unslash( $_POST['bw_webp'] ?? array() );
		$this->settings->update( is_array( $input ) ? $input : array() );

		if ( ! empty( $this->settings->get()['enable_rewrite'] ) ) {
			$this->rewrite->install();
		} else {
			$this->rewrite->remove();
		}

		add_settings_error( 'bw_webp', 'saved', __( 'Settings saved.', 'bw-webp' ), 'updated' );
	}

	public function assets( string $hook ): void {
		if ( 'settings_page_' . self::PAGE_SLUG !== $hook ) {
			return;
		}
		wp_enqueue_script(
			'bw-webp-admin',
			BW_WEBP_URL . 'assets/js/admin.js',
			array(),
			BW_WEBP_VERSION,
			true
		);
		wp_localize_script(
			'bw-webp-admin',
			'BWWebP',
			array(
				'rest'  => esc_url_raw( rest_url( BW_WebP_Rest::NAMESPACE . '/' ) ),
				'nonce' => wp_create_nonce( 'wp_rest' ),
				'i18n'  => array(
					'starting' => __( 'Starting…', 'bw-webp' ),
					'done'     => __( 'Done', 'bw-webp' ),
					'failed'   => __( 'Failed', 'bw-webp' ),
				),
			)
		);
		wp_enqueue_style( 'bw-webp-admin', BW_WEBP_URL . 'assets/css/admin.css', array(), BW_WEBP_VERSION );
	}

	public function render(): void {
		$cfg       = $this->settings->get();
		$counts    = $this->manifest->counts();
		$available = BW_WebP_Converter_Factory::available();
		$failures  = $this->manifest->recent_failures( 20 );
		$htaccess  = $this->rewrite->htaccess_writable();

		try {
			$active = BW_WebP_Converter_Factory::detect( $cfg['converter'] )->name();
		} catch ( Throwable $e ) {
			$active = null;
		}

		include BW_WEBP_DIR . 'admin/views/settings.php';
	}
}
