<?php

namespace MDCE\Admin;

use MDCE\Settings;
use MDCE\PostTypes;

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

class Admin {

	private Settings  $settings;
	private PostTypes $post_types;

	public function __construct( Settings $settings, PostTypes $post_types ) {
		$this->settings   = $settings;
		$this->post_types = $post_types;
	}

	public function register(): void {
		add_action( 'admin_menu',            [ $this, 'add_settings_page' ] );
		add_action( 'admin_init',            [ $this, 'handle_save' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
	}

	public function enqueue_assets( string $hook ): void {
		if ( 'toplevel_page_content-expiry-md' !== $hook ) {
			return;
		}
		wp_enqueue_style( 'mdce-settings', MDCE_PLUGIN_URL . 'assets/css/settings.css', [], MDCE_VERSION );
	}

	public function add_settings_page(): void {
		add_menu_page(
			__( 'Content Expiry', 'monkeydesign-content-expiry' ),
			__( 'Content Expiry', 'monkeydesign-content-expiry' ),
			'manage_options',
			'content-expiry-md',
			[ $this, 'render_settings_page' ],
			'dashicons-clock',
			58
		);

		add_submenu_page(
			'content-expiry-md',
			__( 'General Settings', 'monkeydesign-content-expiry' ),
			__( 'General Settings', 'monkeydesign-content-expiry' ),
			'manage_options',
			'content-expiry-md',
			[ $this, 'render_settings_page' ]
		);
	}

	public function render_settings_page(): void {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$settings        = $this->settings;
		$available_types = $this->post_types->get_available();
		$supported_types = (array) $this->settings->get( 'post_types' );
		$default_action  = (string) $this->settings->get( 'default_action' );

		require MDCE_PLUGIN_DIR . 'admin/views/settings-page.php';
	}

	public function handle_save(): void {
		if ( ! isset( $_POST['spe_settings_nonce'] ) ) {
			return;
		}
		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['spe_settings_nonce'] ) ), 'spe_save_settings' ) ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- sanitization handled inside Settings::save()
		$this->settings->save( $_POST );

		do_action( 'mdce_settings_save' );

		add_settings_error(
			'mdce_settings',
			'mdce_saved',
			__( 'Settings saved.', 'monkeydesign-content-expiry' ),
			'success'
		);
	}
}
