<?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        Create the CSV for saving a BR Product
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - HEADERS
 * ||   - PRODUCT DATA
 * ||   - ATTRIBUTES
 * ||   - DOWNLOADS
 * ||   - CREATE
 * ||   
 * =============================================================================
 */

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

function exportBRProduct($product, $publish = 0) {
    
/*  
============================================================
    HEADERS
============================================================
*/

    ## =========== Prepare CSV headers =========== ##
    
    $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', 'Meta: blue_raven_meta_title', 'Meta: blue_raven_meta_description',
        'Meta: blue_raven_meta_keywords',
    );
    
    ## =========== Add dynamic attribute headers =========== ##
    
    $attribute_headers = array();
    
    $i = 1;
    while (isset($product["attribute_name_{$i}"])) {
        $attributeName = $product["attribute_name_{$i}"];
        if (!in_array($attributeName, $attribute_headers)) {
            $attribute_headers[] = "Attribute {$i} Name";
            $attribute_headers[] = "Attribute {$i} value(s)";
            $attribute_headers[] = "Attribute {$i} visible";
            $attribute_headers[] = "Attribute {$i} used_for_variations";
        }
        $i++;
    }

    $downloads_headers = array();
    
    $i = 1;
    while (isset($product["fileName{$i}"])) {
        $downloadsName = $product["fileName{$i}"];
        if (!in_array($downloadsName, $downloads_headers)) {
            $downloads_headers[] = "Download {$i} ID";
            $downloads_headers[] = "Download {$i} name";
            $downloads_headers[] = "Download {$i} URL";
        }
        $i++;
    }
    
    ## =========== Merge all headers =========== ##
    
    $csv_headers = array_merge($headers, $attribute_headers, $downloads_headers);
    
/*
============================================================
    PRODUCT DATA
============================================================
*/    

    ## =========== Prepare product data =========== ## 
    
    $product_data = array(
        'ID' => isset($product['product-id']) ? $product['product-id'] : 0,  
        'Type' => isset($product['product-type']) ? $product['product-type'] : 'simple',  
        'SKU' => isset($product['product-sku']) ? $product['product-sku'] : '',  
        'GTIN, UPC, EAN, or ISBN' => isset($product['product-barcode']) ? $product['product-barcode'] : '',  
        
        'Name' => isset($product['product-title']) ? $product['product-title'] : '',
        'Published' => isset($publish) ? $publish : 0,
        'Is featured?' => 0, 
        'Visibility in catalog' => 'visible',  
        
        'Short description' => isset($product['short-description']) ? $product['short-description'] : '',
        'Description' => isset($product['long-description']) ? $product['long-description'] : '', 
        
        'Date sale price starts' => isset($product['sales-from']) ? $product['sales-from'] : '',  
        'Date sale price ends' => isset($product['sales-to']) ? $product['sales-to'] : '',  
        
        'Tax status' => 'taxable',  
        'Tax class' => '', 
        
        'In stock?' => '',
        'Stock' => '',
        'Low stock amount' => '',
        'Backorders allowed?' => isset($product['allow-backorder']) ? $product['allow-backorder'] : '',  
        'Sold individually?' => isset($product['product-stock-sold-individually-check']) ? $product['product-stock-sold-individually-check'] : '', 
        
        'Weight (kg)' => isset($product['product-weight']) ? $product['product-weight'] : '',
        'Length (cm)' => isset($product['product-length']) ? $product['product-length'] : '',
        'Width (cm)' => isset($product['product-width']) ? $product['product-width'] : '',
        'Height (cm)' => isset($product['product-height']) ? $product['product-height'] : '',
        
        'Allow customer reviews?' => !empty($product['enable-reviews']) ? 1 : 0,
        'Purchase note' => isset($product['purchase-note']) ? $product['purchase-note'] : '',  
        'Sale price' => isset($product['sales-price']) ? $product['sales-price'] : '',  
        'Regular price' => isset($product['product-price']) ? $product['product-price'] : '', 
        'Categories' => isset($product['product-categories']) ? $product['product-categories'] : '', 
        'Tags' => isset($product['product-tags']) ? $product['product-tags'] : '', 
        'Shipping class' => isset($product['product-shipping-class']) ? $product['product-shipping-class'] : '', 
        'Images' => isset($product['product-image-list']) ? $product['product-image-list'] : '', 
        'Virtual' => isset($product['mark-as-virtual']) ? $product['mark-as-virtual'] : false,
        'Download limit' => isset($product['download-limit']) ? $product['download-limit'] : '', 
        'Download expiry days' => isset($product['download-expiry']) ? $product['download-expiry'] : '', 
        'Parent' => isset($product['parent']) ? $product['parent'] : '',
        'Grouped products' => isset($product['product-grouped-list']) ? $product['product-grouped-list'] : '',
        'Upsells' => isset($product['product-upsells-list']) ? $product['product-upsells-list'] : '',
        'Cross-sells' => isset($product['product-cross-list']) ? $product['product-cross-list'] : '',
        'External URL' => isset($product['product-ex-url']) ? $product['product-ex-url'] : '',
        'Button text' => isset($product['product-ex-text']) ? $product['product-ex-text'] : '',
        'Position' => isset($product['menu-order']) ? $product['menu-order'] : '',  
        'Brands' => isset($product['product-brands']) ? $product['product-brands'] : '', 
        'Meta: blue_raven_meta_title' => isset($product['meta-title']) ? $product['meta-title'] : '', 
        'Meta: blue_raven_meta_description' => isset($product['meta-description']) ? $product['meta-description'] : '',
        'Meta: blue_raven_meta_keywords' =>  isset($product['meta-keys']) ? preg_replace('/\s*,\s*/', ', ', trim(preg_replace('/\s+/', ' ', $product['meta-keys'] ?? ''))) : '',
    );
    
    if (isset($product['track-stock-check']) && $product['track-stock-check'] === '1') {
        $product_data['Stock'] = isset($product['product-stock-quantity']) ? $product['product-stock-quantity'] : '';
        $product_data['Low stock amount'] = isset($product['low-stock-threshold']) ? $product['low-stock-threshold'] : '';
    } else {
        $product_data['In stock?'] = isset($product['stock_status']) ? $product['stock_status'] : 'outofstock';
    }   
    
/*
============================================================
    ATTRIBUTES
============================================================
*/    
    
    $attribute_data = array();
        
    $attribute_index = 1;
    while (isset($product["attribute_name_$attribute_index"])) {
        $attributeName = $product["attribute_name_$attribute_index"];
        if (!in_array($attributeName, $attribute_headers)) {
            $product_data["Attribute {$attribute_index} name"] = $product["attribute_name_$attribute_index"];
            $product_data["Attribute {$attribute_index} value(s)"] = str_replace('|', ',', $product["attribute_value_$attribute_index"]);
            $product_data["Attribute {$attribute_index} visible"] = $product["attribute_check_$attribute_index"] ? 1 : 0;
            $product_data["Attribute {$attribute_index} used_for_variations"] = $product["attribute_variations_$attribute_index"] ? 1 : 0;
        }
        $attribute_index++;
    }

/*
============================================================
    DOWNLOADS
============================================================
*/ 
    
    $downloads_data = array();
    
    $downloads_index = 1;
    while (isset($product["fileName{$downloads_index}"])) {
        $downloadsName = $product["fileName{$downloads_index}"];
        if (!in_array($downloadsName, $downloads_headers)) {
            $product_data["Download {$downloads_index} ID"] = $downloads_index;
            $product_data["Download {$downloads_index} name"] = $product["fileName$downloads_index"];
            $product_data["Download {$downloads_index} URL"] = $product["fileURL$downloads_index"];
        }
        $downloads_index++;
    }
    
/*
============================================================
    CREATE
============================================================
*/ 

    ## =========== Create CSV file =========== ## 

    $file_name = 'myproduct_BR.csv';
	
	// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Using fopen for local CSV export only
    $file_handle = fopen($file_name, 'w');
    
    fputcsv($file_handle, $csv_headers);
    fputcsv($file_handle, $product_data);
    
	// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Safe for memory stream
    fclose($file_handle);
    
    ## =========== return =========== ## 
    
    ob_start(); 
	
	// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Safe for memory stream
    $file_handle = fopen('php://output', 'w');
    
    fputcsv($file_handle, $csv_headers);
    fputcsv($file_handle, $product_data);
    
	// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Safe for memory stream
    fclose($file_handle);
    
    $csv_text = ob_get_clean(); 
    
    return $csv_text;
}
?>