<?php

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

new Sifency_Action_Handler();

/**
 * Hooks into `admin_init` to catch and route all import/export/reset actions.
 */
final class Sifency_Action_Handler {

	public function __construct() {
		add_action( 'admin_init', array( $this, 'handle_actions' ) );
	}

	/**
	 * Catches GET requests and delegates them to the appropriate handler class.
	 */
	public function handle_actions() {
		$results          = null;
		$redirect_url_key = null;

		if ( isset( $_GET['export-suite-action'] ) ) {
			$action = sanitize_key( $_GET['export-suite-action'] );
			check_admin_referer( "export_{$action}_nonce" );

			$exporter = new Sifency_Exporter();
			$results  = ( 'export_all' === $action ) ? $exporter->generate_all_files() : $exporter->generate_file( $action );

			$redirect_url_key = 'export_results';
		} elseif ( isset( $_GET['import-suite-action'] ) ) {
			$action = sanitize_key( $_GET['import-suite-action'] );
			check_admin_referer( "import_{$action}_nonce" );

			$importer = new Sifency_Importer();
			$results  = ( 'import_all' === $action ) ? $importer->run_all_imports() : $importer->run_import( $action );

			$redirect_url_key = 'import_results';
		} elseif ( isset( $_GET['download-suite-action'] ) ) {
			$action = sanitize_key( $_GET['download-suite-action'] );
			check_admin_referer( "download_{$action}_nonce" );

			$downloader = new Sifency_File_Downloader();
			$downloader->download_file( $action );
		} elseif ( isset( $_GET['reset-suite-action'] ) ) {
			$action = sanitize_key( $_GET['reset-suite-action'] );
			check_admin_referer( "reset_{$action}_nonce" );

			$resetter = new Sifency_Resetter();
			$result   = ( 'reset_settings' === $action ) ? $resetter->reset_theme_data() : false;
			$results  = $result ? 'success' : 'failed';

			$redirect_url_key = 'reset_result';
		} else {
			return;
		}

		$this->redirect_after_action( $results, $redirect_url_key );
	}

	/**
	 * Handles the final redirection after an action is performed.
	 *
	 * @param mixed  $results The results of the action.
	 * @param string $query_key The query key for the results (e.g., 'import_results').
	 */
	private function redirect_after_action( $results, $query_key ) {
		$base_redirect_url = remove_query_arg( array( 'export-suite-action', 'import-suite-action', 'download-suite-action', 'reset-suite-action', '_wpnonce', 'current_tab', $query_key ) );

		if ( ! empty( $results ) ) {
			$value             = is_array( $results ) ? urlencode( serialize( $results ) ) : $results;
			$base_redirect_url = add_query_arg( $query_key, $value, $base_redirect_url );
		}

		$final_redirect_url = $base_redirect_url;
		if ( ! empty( $_GET['current_tab'] ) ) {
			$tab_id             = sanitize_key( $_GET['current_tab'] );
			$final_redirect_url = add_query_arg( 'tab', $tab_id, $base_redirect_url );
		}

		wp_safe_redirect( $final_redirect_url );
		exit;
	}
}
