<?php
/* Exit if accessed directly */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
use sgpb\AdminHelper;
use sgpb\SubscriptionPopup;

// Check if file URL is provided
if (empty($fileURL)) {
    // Handle the case where the file URL is not provided
	echo 'ERROR-'.esc_html__('File URL is missing.', 'popup-builder');
    wp_die();
}

$fileImportPath = get_attached_file( $fileURLID );	


// Download file content from the URL
$fileContent = AdminHelper::sgpbCustomReadfile($fileImportPath);

// Check if file content is empty or invalid
if (empty($fileContent)) {
    // Handle the case where the file content is empty or invalid  
	echo 'ERROR-'.esc_html__('Failed to retrieve valid file content from the URL.', 'popup-builder');
    wp_die();
}

//Decrypt the data when reading it back from the CSV
$fileContent = AdminHelper::decrypt_data( $fileContent );

if( $fileContent == false )
{
	//try old method of read csv data 
	$fileContent = AdminHelper::sgpbCustomReadfile($fileImportPath);
}

// Parse CSV file content into an array
$csvFileArray = array_map('str_getcsv', explode("\n", $fileContent));

if( is_array( $csvFileArray ) && count( $csvFileArray ) < 2)
{
	$settingsLink = '<a href="'.esc_url( admin_url( 'edit.php?post_type=popupbuilder&page=sgpbSettings' ) ).'" target="_blank">'.esc_html__('HERE', 'popup-builder').'</a>';
	/* translators: %s: link (with the text "HERE") to the plugin settings page. */
	$error_message_import = '<p>ERROR-'.sprintf( esc_html__('Failed to parse CSV file content. Please make sure that you put exactly the same token for both old and new sites at %s.', 'popup-builder'), $settingsLink ).'</p>';
	echo  wp_kses($error_message_import, AdminHelper::allowed_html_tags());
    wp_die();
}
// Check if the CSV parsing was successful
if ($csvFileArray === false || count($csvFileArray) === 0) {
    // Handle the case where CSV parsing failed or resulted in an empty array   
	echo 'ERROR-'.esc_html__('Failed to parse CSV file content.', 'popup-builder');
    wp_die();
}

$ourFieldsArgs = array(
	'class' => 'js-sg-select2 sgpb-our-fields-keys select__select'
);

$formData =  array('' => __('Select Field', 'popup-builder')) + AdminHelper::getSubscriptionColumnsById($formId);
?>

<div id="importSubscribersSecondStep">
	<h1 id="importSubscriberHeader"><?php esc_html_e('Match Your Fields', 'popup-builder'); ?></h1>
	<div id="importSubscriberBody">
		<div class="formItem sgpb-justify-content-around">
			<div class="formItem__title">
				<?php esc_html_e('Available fields', 'popup-builder'); ?>
			</div>
			<div class="formItem__title">
				<?php esc_html_e('Our list fields', 'popup-builder'); ?>
			</div>
		</div>
		<?php foreach($csvFileArray[0] as $index => $current): ?>
			<?php if (empty($current) || $current == 'popup'): ?>
				<?php continue; ?>
			<?php endif; ?>
			<div class="formItem sgpb-justify-content-between">
				<div class="subFormItem__title">
					<?php echo esc_html($current); ?>
				</div>
				<div>
					<?php
					$ourFieldsArgs['data-index'] = $index;
					echo wp_kses(AdminHelper::createSelectBox($formData, '', $ourFieldsArgs), AdminHelper::allowed_html_tags());
					?>
				</div>
			</div>
		<?php endforeach;?>
		<input type="hidden" class="sgpb-to-import-popup-id" value="<?php echo esc_attr($formId)?>">
		<input type="hidden" class="sgpb-imported-file-url" value="<?php echo esc_attr($fileURL)?>">
		<input type="hidden" class="sgpb-imported-file-id" value="<?php echo esc_attr($fileURLID)?>">
	</div>

	<div id="importSubscriberFooter">
		<input type="button" value="<?php esc_html_e('Save', 'popup-builder'); ?>" class="sgpb-btn sgpb-btn-blue sgpb-save-subscriber" data-ajaxnonce="popupBuilderAjaxNonce">
	</div>

</div>

