<?php
if (!defined('ABSPATH')) {
    exit;
}

// Ensure WooCommerce is active
if (!class_exists('WooCommerce')) {
    echo '<div class="error"><p>WooCommerce is required but not active. You need it to use this. Go to Plugins -> Add New Plugin and search for WooCommerce.</p></div>';
    return;
}

// make sure user can do this
if (!current_user_can('publish_posts')) {
            wp_die('Unauthorized');
        }

// Include the products array file
require_once (plugin_dir_path(__FILE__) . 'incs/products-pub.php');

//Initialize array variable
$babcategory = '';


// Check if the form has been submitted (nonce is present).
if (isset($_GET['babcategory_nonce'])) {
    // Verify the nonce
    if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['babcategory_nonce'])), 'babcategory_action')) {
        wp_die('Security check failed.');
    }

    // nonce passed so populate form fields
    if(isset($_GET['babcategory'])){
        $babcategory = sanitize_text_field(wp_unslash($_GET['babcategory']));
    $all_babproducts = [
    'all_babproducts_10' => $all_babproducts_10,
    'all_babproducts_12' => $all_babproducts_12,
    'all_babproducts_16' => $all_babproducts_16,
    'all_babproducts_32' => $all_babproducts_32,
    'all_babproducts_80' => $all_babproducts_80,
];

        $babproducts = $all_babproducts[$babcategory] ?? $babcategory;
    }
}

// Directory where the original images are located
$copy_dir = plugin_dir_path(__FILE__) . 'img/';

// Ensure category exists
$category_name = 'Fresh Coffee';
$category = get_term_by('name', $category_name, 'product_cat');

if (!$category) {
    $category_insert = wp_insert_term($category_name, 'product_cat');
    if (is_wp_error($category_insert)) {
        echo '<div class="error"><p>Category creation failed: ' . esc_attr($category_insert->get_error_message()) . '</p></div>';
        return;
    }
    $category_id = $category_insert['term_id'];
} else {
    $category_id = $category->term_id;
}

// Function to copy and set product image
function brandabean_set_product_image($product_id, $image_filename, $copy_dir) {
    $upload_dir = wp_upload_dir();
    $source_file = $copy_dir . $image_filename;
    $imagerandom = wp_rand(1000, 5000);
    $modimage_filename = $imagerandom . '-' . $image_filename;
    $destination_file = $upload_dir['path'] . '/' . $modimage_filename;
    
    if (!file_exists($source_file)) {
        wp_die('Source image not found: ' . esc_html($source_file));
        return false;
    }

        // copy
        if (!copy($source_file, $destination_file)) {
            wp_die(esc_html('New image copy failed: ' . $source_file . ' to ' . $destination_file));
            return false;
    }
    
    $wp_filetype = wp_check_filetype($image_filename, null);
    if (!$wp_filetype['type']) {
        wp_delete_file($destination_file); // Remove the copied file if no type is found
        wp_die('No valid file type: ' . esc_html($image_filename));
        return false;
    }

    $attachment = [
        'post_mime_type' => $wp_filetype['type'],
        'post_title'     => sanitize_file_name($image_filename),
        'post_content'   => '',
        'post_status'    => 'inherit',
    ];

    $attach_id = wp_insert_attachment($attachment, $destination_file, $product_id);
    if (is_wp_error($attach_id)) {
        wp_delete_file($destination_file); // Remove the copied file if attachment failed.
        wp_die('Attachment failed: ' . esc_html($attach_id->get_error_message()));
        return false;
    }

    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata($attach_id, $destination_file);
    wp_update_attachment_metadata($attach_id, $attach_data);
    set_post_thumbnail($product_id, $attach_id);
    return true;
}

// for products
$batch_size = 16;

// for loading
$chunk_size = 64;

    //initialize arrays
    $product_arrays = [
        'all_babproducts_10' => $all_babproducts_10,
        'all_babproducts_12' => $all_babproducts_12,
        'all_babproducts_16' => $all_babproducts_16,
        'all_babproducts_32' => $all_babproducts_32,
        'all_babproducts_80' => $all_babproducts_80,
    ];

function brandabean_get_product_chunk($array_name, $offset, $chunk_size, $product_arrays) {

    if (!is_array($product_arrays) || !is_string($array_name) || !isset($product_arrays[$array_name])) {
        return []; // Return empty array if the key is not populated
        }

    return array_slice($product_arrays[$array_name], $offset, $chunk_size);
}

    // Flag to track batch completion
    $processing_complete = false;
    
    if (isset($_POST['brandabean_update_products'])) {
    if (!isset($_POST['brandabean_update_products_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['brandabean_update_products_nonce'])), 'brandabean_update_products_action')) {
        wp_die('Security check failed.');
    }
    
    if (isset($_POST['product_prefix'])) {
    $prefix = trim(sanitize_text_field(wp_unslash($_POST['product_prefix'])));
    // Allow spaces, alphanumeric, -, _, and & in the prefix in case brand name uses these
    $prefix = preg_replace("/[^a-zA-Z0-9\s\-\_\&]/", "", $prefix);
    update_option('brandabean_product_prefix', $prefix);
    } else {
    $prefix = get_option('brandabean_product_prefix', '');
    }
    
    $start_index = isset($_POST['start_index']) ? intval($_POST['start_index']) : 0;
    $offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0;
    $total_products = isset($_POST['total_products']) ? intval($_POST['total_products']) : 0;
    $selected_array_name = isset($_POST['product_array_select']) ? sanitize_text_field(wp_unslash($_POST['product_array_select'])) : $babcategory;
    
    $hardcoded_products = brandabean_get_product_chunk($selected_array_name, $offset, $chunk_size, $product_arrays);

    if (empty($hardcoded_products) && $total_products > 0) {
        echo '<div class="updated"><p>Products updated successfully! You can find these products in your <b>Products</b> and in a category called <b>Fresh Coffee</b></p></div>';
        return;
    }
    
    $total_products = $total_products === 0 ? count(brandabean_get_product_chunk($selected_array_name, 0, PHP_INT_MAX, $product_arrays)) : $total_products;
    
    // Processing batch of products
for ($i = $start_index; $i < min($start_index + $batch_size, count($hardcoded_products)); $i++) {

    $product_data = $hardcoded_products[$i];
    $sku = isset($product_data['sku']) ? sanitize_text_field($product_data['sku']) : '';
    if (empty($sku)) {
        continue;
    }

    // Use POST values if available, otherwise defaults
    $name = isset($_POST['product_name'][$i]) ? sanitize_text_field(wp_unslash($_POST['product_name'][$i])) : (isset($product_data['name']) ? sanitize_text_field($product_data['name']) : '');
    $price = isset($_POST['product_price'][$i]) ? floatval(wp_unslash($_POST['product_price'][$i])) : (isset($product_data['price']) ? floatval($product_data['price']) : 0);
    $weight = isset($_POST['product_weight'][$i]) ? floatval(wp_unslash($_POST['product_weight'][$i])) : (isset($product_data['weight']) ? floatval($product_data['weight']) : 0);
    $description = isset($_POST['product_description'][$i]) ? sanitize_textarea_field(wp_unslash($_POST['product_description'][$i])) : (isset($product_data['description']) ? sanitize_textarea_field($product_data['description']) : '');
    $image = isset($_POST['product_image'][$i]) ? sanitize_text_field(wp_unslash($_POST['product_image'][$i])) : (isset($product_data['image']) ? sanitize_text_field($product_data['image']) : '');

    $existing_product_id = wc_get_product_id_by_sku($sku);
    $product = $existing_product_id ? wc_get_product($existing_product_id) : new WC_Product_Simple();

    if (!$product) {
        continue;
    }

    $final_name = $prefix ? $prefix . ' ' . $name : $name;

    $product->set_name($final_name);
    $product->set_sku($sku);
    $product->set_price($price);
    $product->set_regular_price($price);
    $product->set_weight($weight);
    $product->set_description($description);
    $product->set_category_ids([$category_id]);

    $product_id = $product->save();

    if (is_wp_error($product_id)) {
        wp_die('Product creation error: ' . esc_html($product_id->get_error_message()));
    }

    if (!empty($image)) {
        if (!brandabean_set_product_image($product_id, $image, $copy_dir)) {
            echo '<div class="error"><p>Image upload failed for product: ' . esc_html($name) . ' (SKU: ' . esc_html($sku) . ')</p></div>';
        }
    }
}

// Calculate progress info for JS
$next_index = $start_index + $batch_size;
$total_products = $total_products === 0 ? count($product_arrays[$selected_array_name]) : $total_products;
$processing_complete = ($next_index >= count($product_arrays[$selected_array_name]) && $offset + $chunk_size >= $total_products);

// Output progress bar and form once per batch (outside loop)
echo '<h3>Processing Selected Product Set...</h3>';
echo '<div id="progress_bar_container" style="width: 300px; border: 1px solid #ccc; margin: 10px 0;">';
echo '<div id="progress_bar" style="width: 0%; height: 20px; background-color: #4CAF50;"></div>';
echo '</div>';
echo '<div id="progress_text"><p>Processed ' . esc_html(min($next_index, $total_products)) . ' of ' . esc_html($total_products) . ' products...</p></div>';
echo '<div id="progress_data" data-next="' . esc_attr($next_index) . '" data-total="' . esc_attr($total_products) . '"></div>';

// Hidden form for resubmission
echo '<form id="resubmit_form" method="post" style="display:none;">';
wp_nonce_field('brandabean_update_products_action', 'brandabean_update_products_nonce');
echo '<input type="hidden" name="brandabean_update_products" value="1">';
echo '<input type="hidden" name="start_index" value="' . esc_attr($next_index) . '">';
echo '<input type="hidden" name="offset" value="' . esc_attr($offset) . '">';
echo '<input type="hidden" name="total_products" value="' . esc_attr($total_products) . '">';
echo '<input type="hidden" name="product_array_select" value="' . esc_attr($selected_array_name) . '">';

// Output sanitized product fields as hidden inputs
foreach (['product_name', 'product_sku', 'product_price', 'product_weight', 'product_description', 'product_image'] as $field) {
    if (isset($_POST[$field]) && is_array($_POST[$field])) {
        foreach (sanitize_text_field(wp_unslash($_POST[$field])) as $k => $v) {
            if ($field === 'product_price' || $field === 'product_weight') {
                $val = floatval(wp_unslash($v));
                echo '<input type="hidden" name="' . esc_attr($field) . '[' . esc_attr($k) . ']" value="' . esc_attr($val) . '">';
            } elseif ($field === 'product_description') {
                echo '<input type="hidden" name="' . esc_attr($field) . '[' . esc_attr($k) . ']" value="' . esc_textarea(wp_unslash($v)) . '">';
            } else {
                echo '<input type="hidden" name="' . esc_attr($field) . '[' . esc_attr($k) . ']" value="' . esc_attr(sanitize_text_field(wp_unslash($v))) . '">';
            }
        }
    }
}

echo '</form>';

// Display success message once processing completes
if ($processing_complete) {
    echo '<div class="updated"><p>Success! You can find these products in your main menu <b>Products</b> and in a category called <b>Fresh Coffee</b>.</p></div>';
    }
}
        // top menu links:
        $adm_url = admin_url( 'admin.php?page=' );
        $plu_url = plugin_dir_url(__FILE__);
        
        // Load html and the initial chunk of products for the form 
        ?>
    <div class="wrap">
            <img src="<?php echo esc_url($plu_url) . 'static-images/dlogowide.png'; ?>" alt="Logo" style="max-width:100%; height:auto;"><br>
            <a href="<?php echo esc_url($adm_url) . 'coffee-dropship-trademarks'; ?>">
            <img src="<?php echo esc_url($plu_url) . 'static-images/button1.png'; ?>" alt="Read Me" style="max-width:100%; height:auto;"></a>
		    <a href="<?php echo esc_url($adm_url) . 'coffee-dropship-how-this-works'; ?>">
            <img src="<?php echo esc_url($plu_url) . 'static-images/button4.png'; ?>" alt="How This Works" style="max-width:100%; height:auto;"></a>
	        <a href="<?php echo esc_url($adm_url) . 'brandabean-coffee-dropship_menu'; ?>">
            <img src="<?php echo esc_url($plu_url) . 'static-images/button2.png'; ?>" alt="Logo Upload" style="max-width:100%; height:auto;"></a>
            <a href="<?php echo esc_url($adm_url) . 'coffee-dropship-send-logo'; ?>">
            <img src="<?php echo esc_url($plu_url) . 'static-images/button3.png'; ?>" alt="Logo Send" style="max-width:100%; height:auto;"></a>
            <img src="<?php echo esc_url($plu_url) . 'static-images/button5a.png'; ?>" alt="Manage Products" style="max-width:100%; height:auto;">
            </div>
    <div class="wrap">
        <h1>Manage Products</h1>
            <label>
            <input type="checkbox" id="brandabeanimageCheckbox"> <b> Your Cost:</b> Show My Pricing (dropship pricing) by checking the box.
            </label>
            <br><img id="brandabeanpricing" src="<?php echo esc_url($plu_url) . 'static-images/babcosts.png'; ?>" alt="Pricing" style="display: none;">

    <?php $random = wp_rand(100, 500); // Append a random number to bypass cache on preview image, at or around line 337 ?>
    <h2>Scroll Down To Publish Products. Default retail price is set at 30% above "Your Cost". Leave as is or edit.  Never edit the SKU field in your products.</h2>
    <h2>BEFORE SUBMITTING PRODUCTS: Make sure you uploaded your logo and it appears on the bags (visit the ADD YOUR LOGO TO PRODUCTS button above).</h2>
    <h2><br>+ View the displayed bag image, you should see your logo image on this bag if already uploaded. <img align="left" src="<?php echo esc_url($plu_url) . 'img/best-coffee-brand-image9.jpg?v=' . esc_attr($random); ?>" alt="Your Coffee Product" style="max-width:10%; height:auto;"></h2>
    <h3>+ If you already have live products and want to change a price or edit other fields you should do that in &quot;Products&quot; (main menu, not this plugin).</h3>
    <h3>+ You can change prices now or leave as is.  They can always be edited later in your normal Products menu.</h3>
    <h3>+ It is recommended the database be backed up each time you plan to insert new products.</h3>
    </div>
    
    <div><h2>Inserting Products Instructions:</h2><ol>
    <li>Each time you visit this page, the default 10oz Coffee Products are selected below. There are 5 Product Sets. Each set has about 64 products.</li>
    <li>You can select a product set and click the Load Product Set button to change bag sizes. This way, you can publish sizes you want, or do each one.</li>
    <li>After selecting a product set (or using the default set) you can modify pricing, titles, etc. and publish, or leave as is. They can be edited later too.</li>
    <li>&quot;Product Sets&quot; include: 10 Oz Bags (plus single serve cups) | 12 Oz Bags | 1 LB Bags | 2 LB Bags | 5 LB Bags.</li>
    <li>Each product set has the same coffee bags, in different sizes as listed above.  Every set includes Ground Coffee, Whole Bean, Coarse Grind, Espresso, French Press and Fine Grind.</li>
    <li>To publish all products do each set, one at a time.  It can take 1 to 3 minutes per product set, please be patient.</li>
    <li>The &quot;Load Product Set&quot; button does not publish products, only loads them on this page.  Scroll to the very bottom to Publish to your store.</li>
    </ol></div>
    
    <div>
    <form method="get" action="<?php echo esc_url(admin_url('admin.php')); ?>">
    <?php wp_nonce_field('babcategory_action', 'babcategory_nonce'); ?>
    <label for="babcategory">Select A Product Set To Load Below: </label>
    <select name="babcategory">
        <option value="all_babproducts_10" <?php selected($babcategory . 'all_babproducts_10'); ?>>10 Oz Bags + Single Serve Cups</option>
         <option value="all_babproducts_12" <?php selected($babcategory . 'all_babproducts_12'); ?>>12 Oz Bags</option>
        <option value="all_babproducts_16" <?php selected($babcategory . 'all_babproducts_16'); ?>>1 Lb Bags</option>
        <option value="all_babproducts_32" <?php selected($babcategory . 'all_babproducts_32'); ?>>2 Lb Bags</option>
        <option value="all_babproducts_80" <?php selected($babcategory . 'all_babproducts_80'); ?>>5 Lb Bags</option>
    </select>
    <input type="hidden" name="page" value="coffee-dropship-products">
    <input type="submit" value="Load Product Set">
    </form>
    
    <hr><hr>
    <div class="wrap">
    <?php
    if (!empty($babproducts)) : 
    ?>
    
    <h2>Current Loaded Product Set: <font color="#ff0000">
        <?php // show the user which products are loaded in the form if changed by the user
            if (isset($babcategory)) {
                echo ($babcategory === 'all_babproducts_10' ? '10 Oz Coffee Bags plus Single Serve Cups' : '') .
                    ($babcategory === 'all_babproducts_12' ? '12 Oz Coffee Bags' : '') .
                    ($babcategory === 'all_babproducts_16' ? '1 Lb Coffee Bags' : '') .
                    ($babcategory === 'all_babproducts_32' ? '2 Lb Coffee Bags' : '') .
                    ($babcategory === 'all_babproducts_80' ? '5 Lb Coffee Bags' : ''); } ?> </font></h2>
                    
    <form method="post">
    <?php wp_nonce_field('brandabean_update_products_action', 'brandabean_update_products_nonce');
    
    $saved_prefix = esc_attr(get_option('brandabean_product_prefix', '')); ?>

    <h3>
    <label for="product_prefix">Your Brand Name (Prefix for Product Title):</label>
    <input type="text" id="product_prefix" name="product_prefix" value="<?php echo esc_attr($saved_prefix); ?>" maxlength="20">
    <span id="char_count">20 characters remaining</span>

    <br><font color="#ff0000">(optionally add your brand name to each product title here BEFORE adding products) see example below.</font>
    </h3> Example:  <b>Your Brand Name:</b> Premium Roasters<br><b>Default Product Title:</b> Coffee House Blend Whole Bean Coffee<br><b>New Product Title:</b> &quot;Premium Roasters Coffee House Blend Whole Bean Coffee&quot;
    <table class="wp-list-table widefat fixed striped">
        <thead>
            <tr>
                <th>Product Name</th>
                <th>Price</th>
                <th>Description</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($babproducts as $index => $product) : ?>
                <tr>
                    <td>
                        <input type="text" name="product_name[]" value="<?php echo esc_attr($product['name']); ?>">
                        <input type="hidden" name="product_sku[]" value="<?php echo esc_attr($product['sku']); ?>">
                    </td>
                    <td>
                        <input type="number" step="0.01" name="product_price[]" value="<?php echo esc_attr($product['price']); ?>">
                        <input type="hidden" name="product_weight[]" value="<?php echo esc_attr($product['weight']); ?>">
                    </td>
                    <td>
                        <textarea name="product_description[]"><?php echo esc_textarea($product['description']); ?></textarea>
                        <input type="hidden" name="product_image[]" value="<?php echo esc_attr($product['image']); ?>">
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    <input type="hidden" name="brandabean_update_products" value="1">
    <div><br>Please wait for the green progress bar to complete after submitting this form.<br><strong>It may take 20 to 60 seconds</strong> for this page to display the green progress bar as products load.<br><br></div>
    <input type="submit" name="brandabean_update_products" class="button-primary" value="Publish These Products">
    </form>
    <?php else : ?>
    <p>No coffee product set has been selected yet.  Make a selection in the menu above and scroll down to the bottom once loaded.</p>
<?php endif; ?>
</div>
</div>