// Create an Options Page
add_action('admin_menu', 'acf_repeater_import_menu');
function acf_repeater_import_menu() {
    add_menu_page(
        'ACF Repeater Import',        // Page Title
        'ACF Import',                // Menu Title
        'manage_options',            // Capability
        'acf-repeater-import',       // Menu Slug
        'acf_repeater_import_page',  // Callback Function
        'dashicons-upload',          // Icon
        20                           // Position
    );
}
function acf_repeater_import_page() {
    ?>
    <div class="wrap">
        <h1>Import CSV into ACF Repeater Field</h1>
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="acf_csv_file" required>
            <input type="hidden" name="acf_import_nonce" value="<?php echo wp_create_nonce('acf_import'); ?>">
            <button type="submit" class="button button-primary">Import CSV</button>
        </form>
    </div>
    <?php
    // Check if form is submitted
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acf_import_nonce'])) {
        if (!wp_verify_nonce($_POST['acf_import_nonce'], 'acf_import')) {
            echo '<div class="notice notice-error"><p>Nonce verification failed!</p></div>';
            return;
        }
        // Check if file is uploaded
        if (!empty($_FILES['acf_csv_file']['tmp_name'])) {
            $file = $_FILES['acf_csv_file']['tmp_name'];
            // Call the import function
            acf_import_csv_to_repeater($file);
        } else {
            echo '<div class="notice notice-error"><p>Please upload a CSV file.</p></div>';
        }
    }
}



function acf_import_csv_to_repeater($file) {
    // The page ID where the ACF repeater field exists
    $page_id = 1004; // Replace with your page ID
    // The ACF field key for the repeater field
    $acf_field_key = 'exhibitor_list'; // Replace with your repeater field key
    // Read the CSV file
    $repeater_data = [];
    if (($handle = fopen($file, "r")) !== FALSE) {
        // Read the CSV header (optional)
        $header = fgetcsv($handle);
        // Loop through the CSV rows
        while (($row = fgetcsv($handle)) !== FALSE) {
            $repeater_data[] = [
                'column_one' => $row[0], // Replace with the key of your ACF subfield
                'column_two' => $row[1], // Replace with the key of your ACF subfield
				'column_three' => $row[2], // Replace with the key of your ACF subfield
                // Add more subfields as needed
            ];
        }
        fclose($handle);
    }
    // Update the ACF repeater field with the data
    if (!empty($repeater_data)) {
        update_field($acf_field_key, $repeater_data, $page_id);
        echo '<div class="notice notice-success"><p>Repeater field updated successfully!</p></div>';
    } else {
        echo '<div class="notice notice-error"><p>No data to import.</p></div>';
    }
}