<?php

/**
 * @package CsvImporterPlusforACF
 * Mapping Form
 */

?>

<?php

// make sure we don't expose any info if called directly
if (!defined('ABSPATH')) exit; // Exit if accessed directly

use League\Csv\Reader;
use League\Csv\Exception;
use League\Csv\SyntaxError;
use CIPFA\base\CIPFA_BaseController;
use CIPFA\base\CIPFA_PostProcessor;

// Verify nonce before processing the CSV file upload
if (isset($_POST['cipfa_nonce_field'])) {
   $cipfa_nonce = sanitize_text_field(wp_unslash($_POST['cipfa_nonce_field']));
   if (!wp_verify_nonce($cipfa_nonce, 'cipfa_nonce')) {
      wp_die(esc_html__('Nonce verification failed. Please try again.', 'csv-importer-plus-for-acf'));
   }
} else {
   wp_die(esc_html__('Nonce field is missing.', 'csv-importer-plus-for-acf'));
}

if (isset($_FILES['csv_file']) && isset($_FILES['csv_file']['tmp_name'])) {

   // Handle the file upload
   $cipfa_upload_overrides = array('test_form' => false);
   $cipfa_movefile = wp_handle_upload($_FILES['csv_file'], $cipfa_upload_overrides);

   if ($cipfa_movefile && !isset($cipfa_movefile['error'])) {
      // File uploaded successfully
      $cipfa_target_file = $cipfa_movefile['file'];
      update_option('cipfa_csv_file_path', $cipfa_target_file);
   } else {
      // Handle upload error
      /* translators: %s is the upload error message */
      echo '<div class="error"><p>' . sprintf(esc_html__('Error uploading file: %s', 'csv-importer-plus-for-acf'), esc_html($cipfa_movefile['error'])) . '</p></div>';
      return;
   }
} else {
   echo '<div class="error"><p>' . esc_html__('No CSV file uploaded.', 'csv-importer-plus-for-acf') . '</p></div>';
   return;
}

try {
   $cipfa_csv_file = get_option('cipfa_csv_file_path');

   // Create a CSV Reader instance
   $cipfa_csv = Reader::createFromPath($cipfa_csv_file, 'r');

   // Header
   $cipfa_csv->setHeaderOffset(0);

   // Get the header row
   $cipfa_header_row = $cipfa_csv->getHeader();

   // Check for empty headers
   $cipfa_empty_headers = array_filter($cipfa_header_row, function ($header) {
      return trim($header) === '';
   });

   if (!empty($cipfa_empty_headers)) {
      throw new SyntaxError('Empty column names found. Please provide unique names for all columns.');
   }

   // Check for duplicate columns
   $cipfa_header_counts = array_count_values($cipfa_header_row);
   $cipfa_duplicates = array_filter($cipfa_header_counts, function ($count) {
      return $count > 1;
   });

   if (!empty($cipfa_duplicates)) {
      throw new SyntaxError('The CSV file contains duplicate column names. Please ensure all column names are unique and try again. Duplicate column names found: ' . implode(', ', array_keys($cipfa_duplicates)));
   }
} catch (SyntaxError $e) {
   echo '<div class="cipfa"><div class="mt-6 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">';
   echo '<strong class="font-bold">' . esc_html__('Error:', 'csv-importer-plus-for-acf') . '</strong> ';
   echo '<p>' . esc_html($e->getMessage()) . '</p>';
   echo '</div></div>';
   exit;
} catch (Exception $e) {
   echo '<div class="cipfa"><div class="mt-6 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">';
   echo '<strong class="font-bold">' . esc_html__('Error:', 'csv-importer-plus-for-acf') . '</strong> ';
   echo '<span>' . esc_html($e->getMessage()) . '</span>';
   echo '</div></div>';
   exit;
}
// Retrieve the filtered post types
$cipfa_filtered_post_types = CIPFA_BaseController::cipfa_get_filtered_post_types();
// Get selected post type
$post_type = isset($_POST['post_type']) ? sanitize_text_field(wp_unslash($_POST['post_type'])) : 'post';
if (isset($cipfa_filtered_post_types[$post_type])) {
   // Get taxonomies for the validated post type
   $cipfa_taxonomies = get_object_taxonomies($post_type, 'objects');
   // Filter for custom taxonomies only
   $cipfa_custom_taxonomies = array_filter($cipfa_taxonomies, function ($taxonomy) {
      return $taxonomy->_builtin === false;
   });
}
$cipfa_is_options_page = (strpos($post_type, 'acf_option_') === 0);
// Get chunck size
$cipfa_chunk_size = isset($_POST['chunk_size']) ? intval($_POST['chunk_size']) : 10;
// Get update check
$cipfa_edit_existing = isset($_POST['edit_existing']) ? ($_POST['edit_existing'] == '1') : false;
// Get cache check
$cipfa_flush_cache = isset($_POST['flush_cache']) ? ($_POST['flush_cache'] == '1') : false;
// Get log check
$cipfa_enable_log = isset($_POST['enable_log']) ? ($_POST['enable_log'] == '1') : false;
//check if ACF exists
if (class_exists('ACF')) {
   // Get ACF field groups associated with the selected post type
   $cipfa_acf_field_groups = acf_get_field_groups(array('post_type' => $post_type));
}
// Trim and clean all column names in the header row
$cipfa_header_row = array_map('CIPFA\base\CIPFA_FileHandler::cipfa_clean_column_name', $cipfa_header_row);
// Count occurrences of each column name
$cipfa_column_counts = array_count_values($cipfa_header_row);
// Determine unique column names
$cipfa_unique_column_names = array_filter($cipfa_column_counts, function ($count) {
   return $count === 1;
});
?>
<!-- Display CSV mapping form -->
<div class="cipfa">
   <div class="max-w-3xl mx-auto mt-8 p-8 bg-white rounded-lg shadow-lg" id="importer-form-container">
      <h2 class="text-2xl mb-1 text-center font-semibold" id="id_map_text"><?php echo esc_html__('Map CSV Columns to Post Fields and ACF Fields', 'csv-importer-plus-for-acf') ?></h2>
      <p class="text-center mb-8">
         <?php
         echo esc_html__('For', 'csv-importer-plus-for-acf') . ' ';
         echo '<span class="text-green-700 font-medium">' . esc_html__('auto-mapping', 'csv-importer-plus-for-acf') . '</span>';
         ?>
         (<a href="https://csvimporterplusforacf.com/auto-mapping-csv-column-guidelines/" target="_blank" title="<?php echo esc_attr__('follow the CSV column guidelines', 'csv-importer-plus-for-acf'); ?>">
            <?php echo esc_html__('follow the CSV column guidelines', 'csv-importer-plus-for-acf'); ?>
         </a>).
      </p>
      <form id="mapping-form" method="post">
         <input type="hidden" name="post_type" value="<?php echo esc_attr($post_type); ?>" />
         <input type="hidden" name="chunk_size" value="<?php echo esc_attr($cipfa_chunk_size); ?>" />
         <input type="hidden" name="edit_existing" value="<?php echo esc_attr($cipfa_edit_existing); ?>" />
         <input type="hidden" name="flush_cache" value="<?php echo esc_attr($cipfa_flush_cache); ?>" />
         <input type="hidden" name="enable_log" value="<?php echo esc_attr($cipfa_enable_log); ?>" />
         <?php wp_nonce_field('cipfa_nonce', 'cipfa_nonce_field'); ?>
         <input type="hidden" name="action" value="cipfa_data">
         <div class="mapping-table">
            <table class="w-full divide-y divide-gray-200">
               <thead class="bg-gray-50">
                  <tr>
                     <th scope="col" class="px-2 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-1/3">
                        <?php echo esc_html__('CSV Column', 'csv-importer-plus-for-acf') ?>
                     </th>
                     <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        <?php echo esc_html__('Mapping Option', 'csv-importer-plus-for-acf') ?>
                     </th>
                     <th scope="col" class="px-2 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        <?php echo esc_html__('Help', 'csv-importer-plus-for-acf') ?>
                     </th>
                  </tr>
               </thead>
               <tbody class="bg-white divide-gray-200">
                  <?php foreach ($cipfa_header_row as $cipfa_index => $cipfa_column_name) : ?>
                     <?php
                     $cipfa_column_name = CIPFA\base\CIPFA_FileHandler::cipfa_clean_column_name($cipfa_column_name);
                     ?>
                     <tr class="border-none relative">
                        <td class="px-2 py-4 whitespace-nowrap">
                           <div class="text-sm text-gray-900 px-4"><?php echo esc_html($cipfa_column_name); ?></div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                           <?php $cipfa_tip_num = 1; ?>
                           <select name="mapping[<?php echo esc_attr($cipfa_column_name); ?>]" class="block w-full border-gray-200 focus:border-indigo-500 focus:ring-indigo-500 rounded-md mapping-box" data-tooltip-target="<?php echo esc_attr($cipfa_index); ?>_tooltip">
                              <option value=""><?php echo esc_html__('Select Field', 'csv-importer-plus-for-acf') ?></option>
                              <?php if (!$cipfa_is_options_page) : ?>
                                 <?php $cipfa_excluded_types = array('attachment', 'page', 'product'); ?>
                                 <?php if ($post_type && !in_array($post_type, $cipfa_excluded_types)) : ?>
                                    <optgroup label="Post Fields">
                                       <?php
                                       if ($cipfa_edit_existing) { ?>
                                          <option value="post_id" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_id');
                                                                  endif; ?> data-type="post"><?php echo esc_html__('Post ID', 'csv-importer-plus-for-acf') ?></option>
                                       <?php } ?>
                                       <option value="post_title" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_title');
                                                                  endif; ?> data-type="post"><?php echo esc_html__('Title', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_slug" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_slug');
                                                                  endif; ?> data-type="post"><?php echo esc_html__('Post Slug', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_date" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_date');
                                                                  endif; ?> data-type="post"><?php echo esc_html__('Published Date', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_content" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_content');
                                                                     endif; ?> data-type="post"><?php echo esc_html__('Content', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_excerpt" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_excerpt');
                                                                     endif; ?> data-type="post"><?php echo esc_html__('Excerpt', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="featured_image" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_featured_image');
                                                                        endif; ?> data-type="post"><?php echo esc_html__('Featured Image', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_category" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_categories');
                                                                     endif; ?> data-type="post"><?php echo esc_html__('Categories', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="tags" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_tags');
                                                            endif; ?> data-type="post"><?php echo esc_html__('Tags', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_author" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_author_usernames');
                                                                     endif; ?> data-type="post"><?php echo esc_html__('Author Usernames', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_author_email" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_author_emails');
                                                                           endif; ?> data-type="post"><?php echo esc_html__('Author Emails', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="author_password" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_author_passwords');
                                                                        endif; ?> data-type="post"><?php echo esc_html__('Author Passwords', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_status" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_status');
                                                                     endif; ?> data-type="post"><?php echo esc_html__('Post Status', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_password" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_password');
                                                                     endif; ?> data-type="post"><?php echo esc_html__('Post Password', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="comments" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_comments');
                                                                  endif; ?> data-type="post"><?php echo esc_html__('Comments (enable/disable)', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="pings" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'post_pings');
                                                               endif; ?> data-type="post"><?php echo esc_html__('Pings (enable/disable)', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="menu_order" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'menu_order');
                                                                  endif; ?> data-type="post"><?php echo esc_html__('Post\'s Order', 'csv-importer-plus-for-acf') ?></option>
                                    </optgroup>
                                 <?php elseif ($post_type == 'page') : ?>
                                    <optgroup label="Page Fields">
                                       <?php
                                       if ($cipfa_edit_existing) { ?>
                                          <option value="post_id" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_id');
                                                                  endif; ?> data-type="page"><?php echo esc_html__('Page ID', 'csv-importer-plus-for-acf') ?></option>
                                       <?php } ?>
                                       <option value="post_title" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_title');
                                                                  endif; ?> data-type="page"><?php echo esc_html__('Title', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="page_slug" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_slug');
                                                                  endif; ?> data-type="page"><?php echo esc_html__('Page Slug', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_date" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_date');
                                                                  endif; ?> data-type="page"><?php echo esc_html__('Published Date', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_content" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_content');
                                                                     endif; ?> data-type="page"><?php echo esc_html__('Content', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_excerpt" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_excerpt');
                                                                     endif; ?> data-type="page"><?php echo esc_html__('Excerpt', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="featured_image" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_featured_image');
                                                                        endif; ?> data-type="page"><?php echo esc_html__('Featured Image', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_parent" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_parent');
                                                                     endif; ?> data-type="page"><?php echo esc_html__('Page\'s Parent', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="menu_order" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'menu_order');
                                                                  endif; ?> data-type="page"><?php echo esc_html__('Page\'s Order', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="page_template" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_template');
                                                                     endif; ?> data-type="page"><?php echo esc_html__('Page\'s Template', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_author" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_author_usernames');
                                                                     endif; ?> data-type="page"><?php echo esc_html__('Author Usernames', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_author_email" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_author_email');
                                                                           endif; ?> data-type="page"><?php echo esc_html__('Author Emails', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="author_password" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_author_password');
                                                                        endif; ?> data-type="page"><?php echo esc_html__('Author Passwords', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_status" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_status');
                                                                     endif; ?> data-type="page"><?php echo esc_html__('Page Status', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="post_password" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_password');
                                                                     endif; ?> data-type="page"><?php echo esc_html__('Page Password', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="comments" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'page_comments');
                                                                  endif; ?> data-type="page"><?php echo esc_html__('Comments (enable/disable)', 'csv-importer-plus-for-acf') ?></option>
                                    </optgroup>
                                 <?php elseif ($post_type == 'product') : ?>
                                    <!-- WooCommerce Fields -->
                                    <?php if (class_exists('WooCommerce')) { ?>
                                       <optgroup label="WooCommerce Fields">
                                          <?php
                                          if ($cipfa_edit_existing) { ?>
                                             <option value="product_id" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_id');
                                                                        endif; ?> data-type="product"><?php echo esc_html__('Product ID', 'csv-importer-plus-for-acf') ?></option>
                                          <?php } ?>
                                          <option value="product_name" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_name');
                                                                        endif; ?> data-type="product">
                                             <?php echo esc_html__('Product Name', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_description" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_description');
                                                                              endif; ?> data-type="product">
                                             <?php echo esc_html__('Product Description', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_published" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_published');
                                                                              endif; ?> data-type="product">
                                             <?php echo esc_html__('Product Published', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_date" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_date');
                                                                        endif; ?> data-type="product">
                                             <?php echo esc_html__('Product Date', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_slug" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_slug');
                                                                        endif; ?> data-type="product">
                                             <?php echo esc_html__('Product Slug', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_image" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_image');
                                                                        endif; ?>>
                                             <?php echo esc_html__('Product Image', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_image_gallery" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_image_gallery');
                                                                                 endif; ?>>
                                             <?php echo esc_html__('Product Image Gallery', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_sku" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_sku');
                                                                        endif; ?>>
                                             <?php echo esc_html__('Product SKU', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_short_description" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_short_description');
                                                                                    endif; ?> data-type="product">
                                             <?php echo esc_html__('Product Short Description', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_virtual" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_virtual');
                                                                           endif; ?>>
                                             <?php echo esc_html__('Product Virtual', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_downloadable" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_downloadable');
                                                                                 endif; ?>>
                                             <?php echo esc_html__('Product Downloadable', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_stock" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_stock');
                                                                        endif; ?>>
                                             <?php echo esc_html__('Product Stock', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_stock_status" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_stock_status');
                                                                                 endif; ?>>
                                             <?php echo esc_html__('Product Stock Status', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_manage_stock" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_manage_stock');
                                                                                 endif; ?>>
                                             <?php echo esc_html__('Product Manage Stock', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_allow_backorders" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_allow_backorders');
                                                                                    endif; ?>>
                                             <?php echo esc_html__('Product Allow Backorders', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_low_stock_amount" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_low_stock_amount');
                                                                                    endif; ?>>
                                             <?php echo esc_html__('Product Low Stock Amount', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_sold_individually" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_sold_individually');
                                                                                    endif; ?>>
                                             <?php echo esc_html__('Product Sold Individually', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_tax_status" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_tax_status');
                                                                              endif; ?>>
                                             <?php echo esc_html__('Product Tax Status', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_tax_class" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_tax_class');
                                                                              endif; ?>>
                                             <?php echo esc_html__('Product Tax Class', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_sale_date_price_start" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_sale_date_price_start');
                                                                                          endif; ?>>
                                             <?php echo esc_html__('Sale date price start', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_sale_date_price_end" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_sale_date_price_end');
                                                                                       endif; ?>>
                                             <?php echo esc_html__('Sale date price end', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_weight" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_weight');
                                                                           endif; ?>>
                                             <?php echo esc_html__('Product Weight', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_length" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_length');
                                                                           endif; ?>>
                                             <?php echo esc_html__('Product Length', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_width" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_width');
                                                                        endif; ?>>
                                             <?php echo esc_html__('Product Width', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_height" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_height');
                                                                           endif; ?>>
                                             <?php echo esc_html__('Product Height', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_enable_reviews" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_enable_reviews');
                                                                                 endif; ?>>
                                             <?php echo esc_html__('Product Enable Reviews', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_purchase_note" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_purchase_note');
                                                                                 endif; ?>>
                                             <?php echo esc_html__('Product Purchase Note', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_sale_price" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_sale_price');
                                                                              endif; ?>>
                                             <?php echo esc_html__('Product Sale Price', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_regular_price" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_regular_price');
                                                                                 endif; ?>>
                                             <?php echo esc_html__('Product Regular Price', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_shipping_class" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_shipping_class');
                                                                                 endif; ?>>
                                             <?php echo esc_html__('Product Shipping Class', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_position" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_position');
                                                                           endif; ?>>
                                             <?php echo esc_html__('Product Position', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_upsell_ids" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_upsell_ids');
                                                                              endif; ?>>
                                             <?php echo esc_html__('Product Upsell Ids', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_crosssell_ids" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_crosssell_ids');
                                                                                 endif; ?>>
                                             <?php echo esc_html__('Product Crosssell Ids', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_barcode" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_barcode');
                                                                           endif; ?>>
                                             <?php echo esc_html__('Product Barcode', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_download_limit" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_download_limit');
                                                                                 endif; ?>>
                                             <?php echo esc_html__('Product Download Limit', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_download_expiry" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_download_expiry');
                                                                                    endif; ?>>
                                             <?php echo esc_html__('Product Download Expiry', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_download_file_name" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_download_file_name');
                                                                                       endif; ?>>
                                             <?php echo esc_html__('Product Download File Name', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_download_file_url" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_download_file_url');
                                                                                    endif; ?>>
                                             <?php echo esc_html__('Product Download File URL', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_wpcom_is_markdown" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'product_wpcom_is_markdown');
                                                                                    endif; ?>>
                                             <?php echo esc_html__('Product WPCOM is Markdown', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                          <option value="product_attribute" <?php selected($cipfa_column_name, "product_attribute"); ?>>
                                             <?php esc_html_e('Product Attribute', 'csv-importer-plus-for-acf'); ?>
                                          </option>
                                       </optgroup>
                                    <?php } ?>
                                 <?php endif; ?>

                                 <!-- Custom Taxonomies -->
                                 <?php if (!empty($cipfa_custom_taxonomies)) : ?>
                                    <optgroup label="Custom Taxonomies">
                                       <?php foreach ($cipfa_custom_taxonomies as $taxonomy) : ?>
                                          <option value="<?php echo esc_attr($taxonomy->name); ?>" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, esc_html($taxonomy->name));
                                                                                                   endif; ?>><?php echo esc_html($taxonomy->label); ?></option>
                                       <?php endforeach; ?>
                                    </optgroup>
                                 <?php endif; ?>

                                 <!--  Yoast SEO fields -->
                                 <?php if (defined('WPSEO_VERSION')) { ?>
                                    <optgroup label="Yoast SEO Fields">
                                       <option value="yoast_focus_Keyword" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'yoast_focus_Keyword');
                                                                           endif; ?>><?php echo esc_html__('Focus Keyword', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="yoast_seo_title" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'yoast_seo_title');
                                                                        endif; ?>><?php echo esc_html__('SEO Title', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="yoast_meta_description" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'yoast_meta_description');
                                                                              endif; ?>><?php echo esc_html__('Meta Description', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="yoast_cornerstone_content" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'yoast_cornerstone_content');
                                                                                 endif; ?>><?php echo esc_html__('Cornerstone Content', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="yoast_meta_robots_advanced" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'yoast_meta_robots_advanced');
                                                                                    endif; ?>><?php echo esc_html__('Meta Robots Advanced', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="yoast_show_content_in_search_results" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'yoast_show_content_in_search_results');
                                                                                             endif; ?>><?php echo esc_html__('Show Content In Search Results', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="yoast_search_engines_follow_links" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'yoast_search_engines_follow_links');
                                                                                          endif; ?>><?php echo esc_html__('Search Engines Follow Links', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="yoast_breadcrumb_title" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'yoast_breadcrumb_title');
                                                                              endif; ?>><?php echo esc_html__('Breadcrumb Title', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="yoast_canonical_url" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'yoast_canonical_url');
                                                                           endif; ?>><?php echo esc_html__('Canonical URL', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="yoast_schema_page_type" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'yoast_schema_page_type');
                                                                              endif; ?>><?php echo esc_html__('Schema Page Type', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="yoast_schema_article_type" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'yoast_schema_article_type');
                                                                                 endif; ?>><?php echo esc_html__('Schema Article  Type', 'csv-importer-plus-for-acf') ?></option>
                                    </optgroup>
                                 <?php } ?>

                                 <!--  Rank Math SEO fields -->
                                 <?php if (defined('RANK_MATH_VERSION')) { ?>
                                    <optgroup label="Rank Math Fields">
                                       <option value="rank_math_title" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_title');
                                                                        endif; ?>><?php echo esc_html__('Title', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_description" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_description');
                                                                              endif; ?>><?php echo esc_html__('Description', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_focus_keyword" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_focus_keyword');
                                                                                 endif; ?>><?php echo esc_html__('Focus keyword', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_robots" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_robots');
                                                                        endif; ?>><?php echo esc_html__('Robots', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_advanced_robots" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_advanced_robots');
                                                                                 endif; ?>><?php echo esc_html__('Advanced Robots', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_rich_snippet" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_rich_snippet');
                                                                              endif; ?>><?php echo esc_html__('Rich Snippet', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_schema_json" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_schema_json');
                                                                              endif; ?>><?php echo esc_html__('Schema Json', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_pillar_content" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_pillar_content');
                                                                                 endif; ?>><?php echo esc_html__('Pillar Content', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_canonical" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_canonical');
                                                                           endif; ?>><?php echo esc_html__('Canonical URL', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_primary_category_id" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_primary_category_id');
                                                                                       endif; ?>><?php echo esc_html__('Category ID', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_facebook_title" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_facebook_title');
                                                                                 endif; ?>><?php echo esc_html__('Facebook Title', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_facebook_description" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_facebook_description');
                                                                                       endif; ?>><?php echo esc_html__('Facebook Description', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_facebook_image" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_facebook_image');
                                                                                 endif; ?>><?php echo esc_html__('Facebook Image', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_twitter_title" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_twitter_title');
                                                                                 endif; ?>><?php echo esc_html__('Twitter Title', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_twitter_description" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_twitter_description');
                                                                                       endif; ?>><?php echo esc_html__('Twitter Description', 'csv-importer-plus-for-acf') ?></option>
                                       <option value="rank_math_twitter_image" <?php if (isset($cipfa_unique_column_names[$cipfa_column_name])) : selected($cipfa_column_name, 'rank_math_twitter_image');
                                                                                 endif; ?>><?php echo esc_html__('Twitter Image', 'csv-importer-plus-for-acf') ?></option>
                                    </optgroup>
                                 <?php } ?>
                              <?php endif; ?>

                              <?php // Check if ACF exists
                              if (class_exists('ACF')) {
                                 $cipfa_acf_pro_field_names = [];
                                 $cipfa_is_option_page = strpos($post_type, 'acf_option_') === 0;
                                 $cipfa_option_page_slug = $cipfa_is_option_page ? str_replace('acf_option_', '', $post_type) : '';
                              ?>
                                 <optgroup label="ACF Fields">
                                    <?php

                                    // Get all ACF field groups
                                    $cipfa_acf_field_groups = acf_get_field_groups();
                                    $cipfa_field_groups_for_post_type = array();

                                    // Filter field groups based on the selected post type
                                    foreach ($cipfa_acf_field_groups as $cipfa_group) {
                                       if (isset($cipfa_group['location'])) {
                                          foreach ($cipfa_group['location'] as $cipfa_locations) {
                                             foreach ($cipfa_locations as $cipfa_location) {
                                                if (
                                                   (!$cipfa_is_option_page &&
                                                      $cipfa_location['param'] == 'post_type' &&
                                                      $cipfa_location['operator'] == '==' &&
                                                      $cipfa_location['value'] == $post_type
                                                   )
                                                   ||
                                                   ($cipfa_is_option_page &&
                                                      $cipfa_location['param'] == 'options_page' &&
                                                      $cipfa_location['operator'] == '==' &&
                                                      $cipfa_location['value'] == $cipfa_option_page_slug
                                                   )
                                                   ||
                                                   ($post_type == 'page' && in_array($cipfa_location['param'], ['page_template', 'page_type', 'page_parent', 'page']))
                                                   ||
                                                   in_array($cipfa_location['param'], [
                                                      'post_template', 'post_status', 'post_format', 'post_category',
                                                      'post_taxonomy', 'post', 'current_user', 'current_user_role',
                                                      'user_form', 'user_role', 'taxonomy', 'comment', 'widget',
                                                      'nav_menu', 'nav_menu_item', 'block'
                                                   ])
                                                   ||
                                                   ($cipfa_location['param'] == 'attachment' && $post_type == 'attachment')
                                                ) {
                                                   $cipfa_field_groups_for_post_type[] = $cipfa_group;
                                                   break 2; // Stop if match found
                                                }
                                             }
                                          }
                                       }
                                    }

                                    if (!empty($cipfa_field_groups_for_post_type)) {
                                       foreach ($cipfa_field_groups_for_post_type as $cipfa_group) {
                                          $cipfa_fields = acf_get_fields($cipfa_group['key']);

                                          if ($cipfa_fields) {
                                             // Filter out all ACFE fields
                                             $cipfa_filtered_fields = array_filter($cipfa_fields, function ($f) {
                                                return strpos($f['type'], 'acfe_') !== 0;
                                             });

                                             // Map fields
                                             $cipfa_all_fields = CIPFA_PostProcessor::cipfa_mapping_acf_fields($cipfa_filtered_fields);
                                             // Display free fields
                                             foreach ($cipfa_all_fields['free'] as $cipfa_field) {
                                                echo '<option value="' . esc_attr($cipfa_field['key']) . '" data-type="acf" data-key-type="' . esc_attr($cipfa_field['type']) . '"'
                                                   . (isset($cipfa_unique_column_names[$cipfa_column_name]) ? selected($cipfa_column_name, $cipfa_field['name'], false) : '')
                                                   . '>'
                                                   . esc_html(ucwords($cipfa_field['label']))
                                                   . '</option>';
                                             }
                                             // Display Pro fields (disabled)
                                             foreach ($cipfa_all_fields['pro'] as $cipfa_field) {
                                                $cipfa_acf_pro_field_names[] = CIPFA\base\CIPFA_FileHandler::cipfa_clean_column_name($cipfa_field['name']);
                                                echo '<option value="' . esc_attr($cipfa_field['key']) . '" disabled style="color: #999;">'
                                                   . esc_html(ucwords($cipfa_field['label'])) . ' - Pro Access</option>';
                                             }
                                          } else {
                                             echo '<option disabled>No ACF fields found in group ' . esc_html($cipfa_group['title']) . '</option>';
                                          }
                                       }
                                    } else {
                                       echo '<option disabled>' . esc_html__('No ACF field groups found for this post type', 'csv-importer-plus-for-acf') . '</option>';
                                    }
                                    ?>
                                 </optgroup>
                              <?php } ?>
                           </select>

                           <?php
                           $cipfa_current_column_clean = CIPFA\base\CIPFA_FileHandler::cipfa_clean_column_name($cipfa_column_name);

                           if (!empty($cipfa_acf_pro_field_names) && in_array($cipfa_current_column_clean, $cipfa_acf_pro_field_names)) :
                           ?>
                              <div class="mt-2 text-xs absolute">
                                 <a href="https://csvimporterplusforacf.com/" target="_blank" class="text-indigo-600 hover:text-indigo-800 font-medium inline-flex items-center">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" style="margin-right: 4px;">
                                       <defs>
                                          <linearGradient id="cartGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                                             <stop offset="0%" stop-color="#2563EB" />
                                             <stop offset="100%" stop-color="#9333EA" />
                                          </linearGradient>
                                       </defs>
                                       <circle cx="9" cy="20" r="2" fill="#2563EB" />
                                       <circle cx="19" cy="20" r="2" fill="#2563EB" />
                                       <path d="M4 4H7L10 15H19L22 7H7" fill="url(#cartGradient)" />
                                       <path d="M7 7L4 4" stroke="#FFFFFF" stroke-width="1.5" fill="none" />
                                       <line x1="7" y1="11" x2="20" y2="11" stroke="#FFFFFF" stroke-width="1.5" />
                                    </svg>
                                    Upgrade to Pro to import this ACF/SCF field
                                 </a>
                              </div>
                           <?php endif; ?>
                        </td>
                        <td class="px-2 py-4 whitespace-nowrap">
                           <?php
                           CIPFA_BaseController::cipfa_safe_echo_tooltip(
                              CIPFA_BaseController::cipfa_tooltip(
                                 '',
                                 $cipfa_index
                              )
                           );
                           ?>
                        </td>
                     </tr>
                  <?php endforeach; ?>
               </tbody>
            </table>
         </div>
         <div class="flex justify-between mt-4">
            <a href="admin.php?page=csv_importer_plus_for_acf" title="<?php echo esc_attr__('Back', 'csv-importer-plus-for-acf'); ?>" class="font-medium justify-between py-2">
               <?php echo esc_html__('Back', 'csv-importer-plus-for-acf'); ?>
            </a>
            <button type="submit" class="import-button inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-gradient-to-br from-blue-600 to-purple-600 hover:bg-indigo-600 focus:outline-none focus:ring-2" name="import_data"><?php echo esc_html__('Import Data', 'csv-importer-plus-for-acf') ?></button>
         </div>
      </form>
   </div>
</div>