<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

new Sifency_Admin_Notices();

final class Sifency_Admin_Notices {

	public function __construct() {
		add_action( 'admin_notices', array( $this, 'display_notices' ) );
	}

	public function display_notices() {
		if ( ! $this->is_correct_screen() ) {
			return;
		}

		$this->display_export_notices();
		$this->display_import_notices();
		$this->display_reset_notices();
	}

	/*
	 ================================
	 * Export Notices
	 * ================================ */
	private function display_export_notices() {
		$results = $this->get_safe_results( 'export_results', 'sifency_export_nonce' );

		if ( empty( $results ) ) {
			return;
		}

		if ( ! empty( $results['success'] ) ) {
			$this->render_notice(
				'success',
				'<strong>' . esc_html__( 'Export Complete!', 'sifency-addons' ) . '</strong><br>' .
				$this->format_list( esc_html__( 'Successfully generated:', 'sifency-addons' ), $results['success'], 'code' )
			);
		}

		if ( ! empty( $results['failed'] ) ) {
			$this->render_notice(
				'error',
				'<strong>' . esc_html__( 'Export Failed', 'sifency-addons' ) . '</strong><br>' .
				$this->format_list( esc_html__( 'Could not generate:', 'sifency-addons' ), $results['failed'], 'code' )
			);
		}
	}

	/*
	 ================================
	 * Import Notices
	 * ================================ */
	private function display_import_notices() {
		$results = $this->get_safe_results( 'import_results', 'sifency_import_nonce' );

		if ( empty( $results ) ) {
			return;
		}

		if ( ! empty( $results['success'] ) ) {
			$this->render_notice(
				'success',
				'<strong>' . esc_html__( 'Import Complete!', 'sifency-addons' ) . '</strong><br>' .
				$this->format_list( esc_html__( 'Successfully imported:', 'sifency-addons' ), $results['success'] )
			);
		}

		if ( ! empty( $results['failed'] ) ) {
			$this->render_notice(
				'warning',
				'<strong>' . esc_html__( 'Import Incomplete', 'sifency-addons' ) . '</strong><br>' .
				$this->format_list( esc_html__( 'The following steps failed:', 'sifency-addons' ), $results['failed'], 'strong' ) .
				'<br>' . esc_html__( 'This can happen due to server timeouts or missing files.', 'sifency-addons' )
			);
		}
	}

	/*
	 ================================
	 * Reset Notices
	 * ================================ */
	private function display_reset_notices() {

		if (
			empty( $_GET['reset_result'] ) || // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			empty( $_GET['_wpnonce'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		) {
			return;
		}

		if (
			! wp_verify_nonce(
				sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ),
				'sifency_reset_nonce'
			)
		) {
			return;
		}

		$result = sanitize_key( wp_unslash( $_GET['reset_result'] ) );

		if ( 'success' === $result ) {
			$this->render_notice(
				'success',
				'<strong>' . esc_html__( 'Reset Complete!', 'sifency-addons' ) . '</strong> ' .
				esc_html__( 'All specified theme data has been reset to default.', 'sifency-addons' )
			);
		} else {
			$this->render_notice(
				'error',
				'<strong>' . esc_html__( 'Reset Failed', 'sifency-addons' ) . '</strong> ' .
				esc_html__( 'The reset process could not be completed.', 'sifency-addons' )
			);
		}
	}

	/*
	 ================================
	 * Helpers
	 * ================================ */
	private function get_safe_results( $key, $nonce_action ) {

		if (
			empty( $_GET[ $key ] ) || // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			empty( $_GET['_wpnonce'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		) {
			return array();
		}

		if (
			! wp_verify_nonce(
				sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ),
				$nonce_action
			)
		) {
			return array();
		}

		$raw  = sanitize_text_field( wp_unslash( $_GET[ $key ] ) );
		$json = base64_decode( $raw, true );

		if ( false === $json ) {
			return array();
		}

		$data = json_decode( $json, true );

		return is_array( $data ) ? $data : array();
	}

	private function is_correct_screen() {
		if ( ! function_exists( 'get_current_screen' ) ) {
			return false;
		}
		$screen = get_current_screen();
		return ( is_object( $screen ) && $screen->id === Sifency_Demo_Helper::get_options_screen_id() );
	}

	private function render_notice( $type, $message ) {
		printf(
			'<div class="notice notice-%s is-dismissible"><p>%s</p></div>',
			esc_attr( $type ),
			wp_kses_post( $message )
		);
	}

	private function format_list( $intro_text, $items, $tag = '' ) {
		$friendly_names = Sifency_Demo_Helper::get_friendly_names();
		$html           = esc_html( $intro_text ) . ' <ul>';

		foreach ( $items as $item ) {
			$display_name   = esc_html( $friendly_names[ $item ] ?? ucwords( str_replace( array( '_', '-' ), ' ', $item ) ) );
			$formatted_item = $tag ? sprintf( '<%1$s>%2$s</%1$s>', tag_escape( $tag ), $display_name ) : $display_name;
			$html          .= '<li>' . $formatted_item . '</li>';
		}

		$html .= '</ul>';

		return $html;
	}
}
