<?php
 
 /**
 * =============================================================================
 * @package         Blue Raven (Free Version)
 * @Plugin URI      https://enterrahost.com/plugins/blue-raven
 * 
 * @Author          EnterraHost
 * @Author URI      https://enterrahost.com
 * @License         GPL-2.0-or-later
 *  
 * @Copyright       (c) 2025 EnterraHost
 * @Contents        Save Variations
 * 
 * =============================================================================
 * 
 * || INDEX:
 * ||   - SAVE VARIATIONS
 * 
 * =============================================================================
 */

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

/*
============================================================
    SAVE VARIATIONS
============================================================
*/

function BlueRaven_saveVariations($content) {
    global $wpdb;
    parse_str($content, $product);
    $PID = $product['product-id'];

    ## ===========  Get existing variations CSV from database =========== ##
    
    $table_name = $wpdb->prefix . 'BlueRavenProducts';
    $existing_csv = $wpdb->get_var($wpdb->prepare("SELECT variations_CSV FROM $table_name WHERE ID = %d", $PID));
    $existing_variations = [];
    $headers = [];
    
    ## =========== Parse existing CSV if it exists  =========== ##
    
    if (!empty($existing_csv)) {
        $lines = explode("\n", trim($existing_csv));
        $headers = str_getcsv($lines[0]);
        for ($i = 1; $i < count($lines); $i++) {$row = str_getcsv($lines[$i]);$existing_variations[] = array_combine($headers, $row);}
    }
    
    ## =========== Prepare headers (same as your original code) =========== ##
    
    $headers = array(
        'ID', 'Type', 'SKU', 'GTIN, UPC, EAN, or ISBN', 'Name', 'Published', 'Is featured?',
        'Visibility in catalog', 'Short description', 'Description', 'Date sale price starts',
        'Date sale price ends', 'Tax status', 'Tax class', 'In stock?', 'Stock', 'Low stock amount',
        'Backorders allowed?', 'Sold individually?', 'Weight (kg)', 'Length (cm)', 'Width (cm)',
        'Height (cm)', 'Allow customer reviews?', 'Purchase note', 'Sale price', 'Regular price',
        'Categories', 'Tags', 'Shipping class', 'Images', 'Virtual','Download limit', 'Download expiry days',
        'Parent', 'Grouped products', 'Upsells', 'Cross-sells', 'External URL', 'Button text',
        'Position', 'Brands',
    );
    
    $veAttJson = isset($product["ve-att-json"]) ? $product['ve-att-json'] : '';

    ## =========== Decode the JSON (first replace &quot; with ") =========== ##
    
    $veAttJson = str_replace('&quot;', '"', $veAttJson);
    $attributes = json_decode($veAttJson, true);
    
    ## =========== Add attribute headers to CSV headers =========== ##
    
    if (!empty($attributes)) {
        foreach ($attributes as $index => $attributeGroup) {
            $attrNum = $index + 1;
            $attribute_headers[] = "Attribute {$attrNum} name";
            $attribute_headers[] = "Attribute {$attrNum} value(s)";
            $attribute_headers[] = "Attribute {$attrNum} visible";
            $attribute_headers[] = "Attribute {$attrNum} used_for_variations";
        }
    }

    BlueRaven_SendError("LOG", "blue-raven/templates/class-admin-my-products.php", "products ", json_encode($product));
          

    $downloads_headers = array();
    $i = 1;
    while (isset($product["ve-fileName{$i}"])) {

        BlueRaven_SendError("LOG", "blue-raven/templates/class-admin-my-products.php", "fileName", $product["ve-fileName2"]);
            
        $downloadsName = $product["ve-fileName{$i}"];
        if (!in_array($downloadsName, $downloads_headers)) {
            $downloads_headers[] = "Download {$i} ID";
            $downloads_headers[] = "Download {$i} name";
            $downloads_headers[] = "Download {$i} URL";
        }
        $i++;
    }

    BlueRaven_SendError("LOG", "blue-raven/templates/class-admin-my-products.php", "ve-product-stock-quantity", $product['ve-stock_status']);
          
    
    $csv_headers = array_merge($headers, $attribute_headers, $downloads_headers);
    
    $product_data = array(
        'ID' => isset($product['variable-product-id']) ? $product['variable-product-id'] : 0,
        'Type' => 'variation',
        'SKU' => isset($product['variable-product-sku']) ? $product['variable-product-sku'] : '',
        'GTIN, UPC, EAN, or ISBN' => isset($product['variable-product-other-barcode']) ? $product['variable-product-other-barcode'] : '',
        'Name' => stripslashes(isset($product['product-title']) ? $product['product-title'] : '') . " - " . ($product["variable-name"] ?? ''),
        'Published' => isset($product['enable-product']) ? 1 : 0,
        'Is featured?' => 0,
        'Visibility in catalog' => 'visible',
        'Short description' => '',
        'Description' => stripslashes(isset($product['ve-description-note']) ? $product['ve-description-note'] : ''),
        'Date sale price starts' => isset($product['ve-sales-from']) ? $product['ve-sales-from'] : '',
        'Date sale price ends' => isset($product['ve-sales-to']) ? $product['ve-sales-to'] : '',
        'Tax status' => 'taxable',
        'Tax class' => 'parent',
        'In stock?' => isset($product['ve-stock_status']) ? $product['ve-stock_status'] : '',
        'Stock' => isset($product['ve-product-stock-quantity']) ? $product['ve-product-stock-quantity'] : '',
        'Low stock amount' => isset($product['ve-low-stock-threshold']) ? $product['ve-low-stock-threshold'] : '',
        'Backorders allowed?' => isset($product['ve-allow-backorder']) ? $product['ve-allow-backorder'] : '',
        'Sold individually?' => 1,
        'Weight (kg)' => isset($product['ve-product-weight']) ? $product['ve-product-weight'] : '',
        'Length (cm)' => isset($product['ve-product-length']) ? $product['ve-product-length'] : '',
        'Width (cm)' => isset($product['ve-product-width']) ? $product['ve-product-width'] : '',
        'Height (cm)' => isset($product['ve-product-height']) ? $product['ve-product-height'] : '',
        'Allow customer reviews?' => 0,
        'Purchase note' => '',
        'Sale price' => isset($product['ve-sales-price']) ? $product['ve-sales-price'] : '',
        'Regular price' => isset($product['ve-product-price']) ? $product['ve-product-price'] : '',
        'Categories' => '',
        'Tags' => '',
        'Shipping class' => isset($product['ve-product-shipping-class']) ? $product['ve-product-shipping-class'] : '',
        'Images' => isset($product['ve-product-img']) ? $product['ve-product-img'] : '',
        'Virtual' => isset($product['virtual']) ? 1 : 0,
        'Download limit' => isset($product['ve-download-limit']) ? $product['ve-download-limit'] : '',
        'Download expiry days' => isset($product['ve-download-expiry']) ? $product['ve-download-expiry'] : '',
        'Parent' => isset($product['product-sku']) ? $product['product-sku'] : '',
        'Grouped products' => '',
        'Upsells' => '',
        'Cross-sells' => '',
        'External URL' => '',
        'Button text' => '',
        'Position' => isset($product['ve-menu-pos']) ? $product['ve-menu-pos'] : '',
        'Brands' => '',
    );
    
    ## =========== Add attributes to product data =========== ##
    
    if (!empty($attributes)) {
        foreach ($attributes as $index => $attributeGroup) {
            $attrNum = $index + 1;
            $product_data["Attribute {$attrNum} name"] = $attributeGroup[0]; 
            $product_data["Attribute {$attrNum} value(s)"] = $attributeGroup[1]; 
            $product_data["Attribute {$attrNum} visible"] = 1;
            $product_data["Attribute {$attrNum} used_for_variations"] = 1;
        }
    }
    
    ## =========== Add downloads =========== ##
    
    $downloads_index = 1;
    while (isset($product["ve-fileName{$downloads_index}"])) {
        $downloadsName = $product["ve-fileName{$downloads_index}"];
        if (!in_array($downloadsName, $downloads_headers)) {
            $product_data["Download {$downloads_index} ID"] = $downloads_index;
            $product_data["Download {$downloads_index} name"] = $product["ve-fileName$downloads_index"];
            $product_data["Download {$downloads_index} URL"] = $product["ve-fileURL$downloads_index"];
        }
        $downloads_index++;
    }
    
    ## =========== Check if variation exists by Name (changed from ID) =========== ##
    
    $variation_exists = false;
    foreach ($existing_variations as $index => $variation) {
        if (stripslashes($variation['Name']) == $product_data['Name'] || $variation['ID'] == $product_data['ID']) {
            $existing_variations[$index] = $product_data;
            $variation_exists = true;
            break;
        }
    }
    
    if (!$variation_exists) $existing_variations[] = $product_data;
    
    ## =========== Generate new CSV content =========== ##
    
    ob_start();
    $output = fopen('php://output', 'w');
    fputcsv($output, $csv_headers);

    ## =========== Write all variations =========== ##
    
    foreach ($existing_variations as $variation) {
        $row = [];
        foreach ($csv_headers as $header) { $row[] = $variation[$header] ?? ''; }
        fputcsv($output, $row);
    }
    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
	fclose($output); 
    
	// phpcs:ignore WordPress.PHP.DiscouragedFunctions.ob_get_clean_ob_get_clean
	$new_csv = ob_get_clean();
    
    ## =========== Update database with new CSV =========== ##
    
    $wpdb->update(
        $table_name,
        array('variations_csv' => $new_csv),
        array('ID' => $PID),
        array('%s'),
        array('%d')
    );

    return true;
}
