<?php

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

require_once dirname(__FILE__) . '/includes/lib/mo-saml-options-enum.php';
add_action('admin_init', 'mo_hsso_miniorange_import_export');

/**
 * Returns the option enum class names used for configuration export.
 *
 * @return array<string, string>
 */
function mo_hsso_get_tab_class_names() {
	$tab_class_names = array(
		'SSO_Login'         => 'mo_hsso_options_enum_sso_loginMoSAML',
		'Identity_Provider' => 'mo_hsso_options_enum_identity_providerMoSAML',
		'Service_Provider'  => 'mo_hsso_options_enum_service_providerMoSAML',
		'Attribute_Mapping' => 'mo_hsso_options_enum_attribute_mappingMoSAML',
		'Role_Mapping'      => 'mo_hsso_options_enum_role_mappingMoSAML',
	);

	if ( get_option( 'MO_SAML_TEST_STATUS' ) != 1 ) {
		$tab_class_names['Test_Configuration'] = 'mo_hsso_options_test_configuration';
	}

	return $tab_class_names;
}

/**
 * Send a JSON file download using the WordPress Filesystem API.
 *
 * @param string $json_string JSON file contents.
 * @param string $filename    Download filename.
 */
function mo_hsso_send_json_file_download( $json_string, $filename = 'miniorange-saml-config.json' ) {
	if ( ob_get_length() ) {
		ob_clean();
	}

	$temp_file = wp_tempnam( 'mo-hsso-export' );
	if ( ! $temp_file ) {
		exit;
	}

	global $wp_filesystem;

	if ( empty( $wp_filesystem ) ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		WP_Filesystem();
	}

	if ( empty( $wp_filesystem ) || ! $wp_filesystem->put_contents( $temp_file, $json_string, FS_CHMOD_FILE ) ) {
		wp_delete_file( $temp_file );
		exit;
	}

	nocache_headers();
	header( 'Content-Type: application/json; charset=utf-8' );
	header( 'Content-Disposition: attachment; filename=' . sanitize_file_name( $filename ) );

	$download_body = $wp_filesystem->get_contents( $temp_file );
	$wp_filesystem->delete( $temp_file );

	if ( false !== $download_body ) {
		echo wp_kses_post( $download_body );
	}

	exit;
}

/**
 *Function iterates through the enum to create array of values and converts to JSON and lets user download the file
 */
function mo_hsso_miniorange_import_export($test_config_screen = false, $json_in_string = false)
{

	if ($test_config_screen) {
		$_POST['option'] = 'mo_hsso_export';
	}

	$posted_option = isset( $_POST['option'] ) ? sanitize_text_field( wp_unslash( $_POST['option'] ) ) : '';
	if ( '' === $posted_option ) {
		return;
	}

	if ( 'mo_hsso_export' === $posted_option ) {
		if ( $test_config_screen && $json_in_string ) {
			$export_referer = check_admin_referer( 'mo_hsso_contact_us_query_option' );
		} else {
			$export_referer = check_admin_referer( 'mo_hsso_export' );
		}
		if ( $export_referer ) {
			$tab_class_name = mo_hsso_get_tab_class_names();
			$configuration_array = array();
			foreach ($tab_class_name as $key => $value) {
				$configuration_array[$key] = mo_hsso_get_configuration_array($value);
			}
			$configuration_array["Version_dependencies"] = mo_hsso_get_version_informations();
			$json_string = wp_json_encode( $configuration_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );

			if ( $json_in_string ) {
				return $json_string;
			}

			mo_hsso_send_json_file_download( $json_string );
		}
	} elseif ( 'mo_hsso_keep_settings_on_deletion' === $posted_option && check_admin_referer( 'mo_hsso_keep_settings_on_deletion' ) ) {

		$keep_settings_intact = isset( $_POST['mo_hsso_keep_settings_intact'] ) ? sanitize_text_field( wp_unslash( $_POST['mo_hsso_keep_settings_intact'] ) ) : '';
		if ( '' !== $keep_settings_intact ) {
			update_option('mo_hsso_keep_settings_on_deletion', 'true');
		} else {
			update_option('mo_hsso_keep_settings_on_deletion', '');
		}
	}

	return;
}

function mo_hsso_get_configuration_array($class_name)
{
	$class_object = call_user_func($class_name . '::getConstants');
	$mo_array = array();
	foreach ($class_object as $key => $value) {
		$mo_option_exists = get_option($value);

		if ($mo_option_exists) {
			$mo_option_exists = maybe_unserialize($mo_option_exists);
			$mo_array[$key] = $mo_option_exists;
		}
	}

	return $mo_array;
}

function mo_hsso_get_version_informations()
{
	$array_version = array();
	$array_version["Plugin_version"] = mo_hsso_options_plugin_constants::Version;
	$array_version["PHP_version"] = phpversion();
	$array_version["Wordpress_version"] = get_bloginfo('version');
	$array_version["OPEN_SSL"] = mo_hsso_is_openssl_installed();
	$array_version["CURL"] = mo_hsso_is_curl_installed();
	$array_version["ICONV"] = mo_hsso_is_iconv_installed();
	$array_version["DOM"] = mo_hsso_is_dom_installed();

	return $array_version;
}
