<?php
namespace Elementor_Icon_Vault;

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

/**
 * Adds the plugin's settings page and handles the "Uninstall" action,
 * which removes all plugin data from the database and deactivates the
 * plugin in one click.
 */
class Admin_Settings {

	const PAGE_SLUG = 'icon-vault-for-elementor';

	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
		add_action( 'admin_post_eiv_uninstall', array( $this, 'handle_uninstall' ) );
	}

	public function add_settings_page() {
		add_options_page(
			__( 'Icon Vault for Elementor', 'icon-vault-for-elementor' ),
			__( 'Icon Vault', 'icon-vault-for-elementor' ),
			'manage_options',
			self::PAGE_SLUG,
			array( $this, 'render_settings_page' )
		);
	}

	public function render_settings_page() {

		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$settings = get_option( EIV_OPTION_KEY, array() );
		$disabled = isset( $settings['disabled_libraries'] ) ? (array) $settings['disabled_libraries'] : array();

		if ( isset( $_POST['eiv_save_settings'] ) && check_admin_referer( 'eiv_save_settings' ) ) {
			$submitted = isset( $_POST['eiv_enabled_libraries'] ) ? (array) $_POST['eiv_enabled_libraries'] : array();
			$submitted = array_map( 'sanitize_key', $submitted );

			$new_disabled = array();
			foreach ( array_keys( Icon_Library_Loader::get_libraries() ) as $key ) {
				if ( ! in_array( $key, $submitted, true ) ) {
					$new_disabled[] = $key;
				}
			}

			$settings['disabled_libraries'] = $new_disabled;
			update_option( EIV_OPTION_KEY, $settings );
			$disabled = $new_disabled;
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved.', 'icon-vault-for-elementor' ) . '</p></div>';
		}

		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Icon Vault for Elementor', 'icon-vault-for-elementor' ); ?></h1>
			<p><?php esc_html_e( 'Adds free icon libraries to every Elementor icon picker, with full color and style control support.', 'icon-vault-for-elementor' ); ?></p>

			<form method="post">
				<?php wp_nonce_field( 'eiv_save_settings' ); ?>
				<table class="form-table" role="presentation">
					<tr>
						<th scope="row"><?php esc_html_e( 'Icon libraries', 'icon-vault-for-elementor' ); ?></th>
						<td>
							<?php foreach ( Icon_Library_Loader::get_libraries() as $key => $lib ) : ?>
								<label style="display:block;margin-bottom:6px;">
									<input type="checkbox" name="eiv_enabled_libraries[]" value="<?php echo esc_attr( $key ); ?>" <?php checked( ! in_array( $key, $disabled, true ) ); ?> />
									<?php echo esc_html( $lib['label'] ); ?>
								</label>
							<?php endforeach; ?>
						</td>
					</tr>
				</table>
				<?php submit_button( __( 'Save Settings', 'icon-vault-for-elementor' ), 'primary', 'eiv_save_settings' ); ?>
			</form>

			<hr />

			<h2 style="color:#b32d2e;"><?php esc_html_e( 'Uninstall', 'icon-vault-for-elementor' ); ?></h2>
			<p>
				<?php esc_html_e( 'This will permanently delete all Icon Vault for Elementor settings from the database and deactivate the plugin. This cannot be undone.', 'icon-vault-for-elementor' ); ?>
			</p>
			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
				  onsubmit="return confirm('<?php echo esc_js( __( 'This will delete all Icon Vault for Elementor data and deactivate the plugin. Continue?', 'icon-vault-for-elementor' ) ); ?>');">
				<input type="hidden" name="action" value="eiv_uninstall" />
				<?php wp_nonce_field( 'eiv_uninstall_action', 'eiv_uninstall_nonce' ); ?>
				<button type="submit" class="button button-secondary" style="border-color:#b32d2e;color:#b32d2e;">
					<?php esc_html_e( 'Delete Data & Deactivate Plugin', 'icon-vault-for-elementor' ); ?>
				</button>
			</form>
		</div>
		<?php
	}

	/**
	 * Delete all plugin data from the database and deactivate the plugin.
	 */
	public function handle_uninstall() {

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to do this.', 'icon-vault-for-elementor' ) );
		}

		// Require POST specifically: destructive actions must never run on a GET
		// request, which browsers, security scanners, or prefetchers can trigger
		// without the user's intent.
		if ( ! isset( $_SERVER['REQUEST_METHOD'] ) || 'POST' !== $_SERVER['REQUEST_METHOD'] ) {
			wp_die( esc_html__( 'Invalid request method.', 'icon-vault-for-elementor' ) );
		}

		if (
			! isset( $_POST['eiv_uninstall_nonce'] ) ||
			! wp_verify_nonce( sanitize_key( $_POST['eiv_uninstall_nonce'] ), 'eiv_uninstall_action' )
		) {
			wp_die( esc_html__( 'Security check failed.', 'icon-vault-for-elementor' ) );
		}

		// Delete all plugin data from the database.
		delete_option( EIV_OPTION_KEY );

		// Deactivate the plugin.
		if ( ! function_exists( 'deactivate_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}
		deactivate_plugins( plugin_basename( EIV_PLUGIN_FILE ) );

		wp_safe_redirect(
			add_query_arg(
				'eiv_uninstalled',
				'1',
				admin_url( 'plugins.php' )
			)
		);
		exit;
	}
}
