<?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        Post Product to WOO and or DB
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - SAVE PRODUCT
 * || 
 * =============================================================================
 */
 
if ( ! defined( 'ABSPATH' ) ) exit; 

/*
============================================================
    SAVE PRODUCT
============================================================
*/

function BlueRaven_saveProductBR($content){ 
   
    parse_str($content, $content);
    
    if($content != []){
        
        global $wpdb;
        $table_name = $wpdb->prefix . 'BlueRavenProducts';
        
        require_once BLUERAVEN_PLUGIN_DIR . 'includes/third-party/class-blue-raven-product-exporter.php';
        require_once BLUERAVEN_PLUGIN_DIR . 'includes/third-party/class-blue-raven-woo-updater.php';
  
        $id = isset($content['product-id']) && is_scalar($content['product-id']) ? absint(sanitize_text_field((string)$content['product-id'])) : 0;
        
        $title = isset($content['product-title']) ? sanitize_text_field(wp_unslash($content['product-title'])) : '';
        $slug = isset($content['product-slug']) ? sanitize_title(wp_unslash($content['product-slug'])) : '';
        $description = isset($content['long-description']) ? wp_kses_post(wp_unslash($content['long-description'])) : '';
        $shortDescription = isset($content['short-description']) ? sanitize_textarea_field(wp_unslash($content['short-description'])) : '';

        $sku = isset($content['product-sku']) ? sanitize_text_field(wp_unslash($content['product-sku'])) : '';
        $category = isset($content['product-categories']) ? sanitize_text_field(wp_unslash($content['product-categories'])) : '';
        $thumbnail = isset($content['product-image-list']) ? $content['product-image-list'] : '';
        $thumbnail_array = !empty($thumbnail) ? array_map('esc_url_raw', explode(',', $thumbnail)) : array();
        $first_thumbnail = !empty($thumbnail_array) ? esc_url_raw(trim($thumbnail_array[0])) : '';

        $meta_title = isset($content['meta-title']) ? sanitize_text_field($content['meta-title']) : '';
        $meta_description = isset($content['meta-description']) ? sanitize_textarea_field($content['meta-description']) : '';
        $meta_keys = isset($content['meta-keys']) ? sanitize_text_field($content['meta-keys']) : '';
        $meta_keys_array = !empty($meta_keys) ? array_map('sanitize_text_field', explode(',', $meta_keys)) : array();
        $meta_keys_json = !empty($meta_keys_array) ? wp_json_encode($meta_keys_array) : '';
                
        $price = isset($content['product-price']) ? floatval($content['product-price']) : 0;
        $sale = isset($content['sales-price']) ? floatval($content['sales-price']) : 0;
        $sale_start = isset($content['sales-from']) ? sanitize_text_field($content['sales-from']) : '';
        $sale_end = isset($content['sales-to']) ? sanitize_text_field($content['sales-to']) : '';
        $cost = 0;
        
        $csv = wp_unslash(exportBRProduct($content,$id));
        $db_product_id = $wpdb->get_var($wpdb->prepare("SELECT id FROM $table_name WHERE id = %d",$id));
        
        if (!$db_product_id) {
            $result = $wpdb->insert(
                $table_name,
                array(
                    'id'                => $id,
                    'woo_product_id'    => null,
                    'title'             => $title,
                    'slug'              => $slug,
                    'description'       => $description,
                    'short_description' => $shortDescription,
                    'sku'               => $sku,
                    'category'          => $category,
                    'status'            => 'draft',
                    'thumbnail'         => $first_thumbnail,
                    'price'             => floatval($price),
                    'cost'              => floatval($cost),
                    'meta_title'        => $meta_title,
                    'meta_description'  => $meta_description,
                    'meta_keywords'     => $meta_keys_json,
                    'product_CSV'       => $csv
                ),
                array(
                    '%d',               // id
                    '%s',               // woo_product_id (null)
                    '%s',               // title
                    '%s',               // slug
                    '%s',               // description
                    '%s',               // short_description
                    '%s',               // sku
                    '%s',               // category
                    '%s',               // status
                    '%s',               // thumbnail
                    '%f',               // price
                    '%f',               // cost
                    '%s',               // meta_title
                    '%s',               // meta_description
                    '%s',               // meta_keywords
                    '%s'                // product_CSV
                )
            );
        }
        
        $row = $wpdb->get_row($wpdb->prepare("SELECT woo_product_id, variations_CSV, attributes_json FROM $table_name WHERE id = %d",$id),ARRAY_A);
        
        $productID = $row['woo_product_id'] ?? null;
        $variations_CSV = $row['variations_CSV'] ?? null;
        $attibuteJSON = $row['attributes_json'] ?? null;
        $status;

        if ($content['product-save-type'] == 'save-woo-draft' ||  $content['product-save-type'] == 'save-woo-product'){
            $results = process_csv_file($csv, $variations_CSV, $attibuteJSON, $productID, $id, $content['product-save-type'] == 'save-woo-draft' ? false : true, $slug);
            $status = ($content['product-save-type'] == 'save-woo-product') ? 'published' : 'draft';
        
            if(empty($results['successful'])) {
                wp_send_json_error(array('message' => "errors : " . json_encode($results)));
                exit();
            }else{
                $productID = $results['successful'][0]['product_id'];
            }
        }else{
            $status = 'draft';
        }
        
        $result = $wpdb->update(
            $table_name,
            array(
                'woo_product_id' => $productID,                                 // %d (integer)
                'title' => $title,                                              // %s (string)
                'slug' => $slug,                                                // %s
                'description' => $description,                                  // %s
                'short_description' => $shortDescription,                       // %s
                'sku' => $sku,                                                  // %s
                'category' => $category,                                        // %s
                'status' => $status,                                            // %s
                'thumbnail' => $first_thumbnail,                                // %s
                'price' => floatval($price),
                'cost' => floatval($cost),
                'meta_title' => $meta_title,                                    // %s
                'meta_description' => $meta_description,                        // %s
                'meta_keywords' => $meta_keys_json,                             // %s (JSON is stored as string)
                'product_CSV' => $csv                                           // %s
            ),
            array('id' => $id),                                                 // WHERE clause (id = %d)
            array(                                                              // Format for values:
                '%d',                                                           // woo_product_id
                '%s',                                                           // title
                '%s',                                                           // slug
                '%s',                                                           // description
                '%s',                                                           // short_description
                '%s',                                                           // sku
                '%s',                                                           // category
                '%s',                                                           // status
                '%s',                                                           // thumbnail
                '%f',                                                           // price
                '%f',                                                           // cost
                '%s',                                                           // meta_title
                '%s',                                                           // meta_description
                '%s',                                                           // meta_keywords
                '%s'                                                            // product_CSV
            ),
            array('%d')                                                         // Format for WHERE (id)
        );
    
        if ($result === false) {
            
            $error = $wpdb->last_error;
            $q = $wpdb->last_query;
        
            BlueRaven_SendError("ERROR", "my-product-save-draft.php", "Update failed", "$id Error: {$error} | Query: {$q}");
            wp_send_json_error(['message' => "Failed to update this product."]);
    
        } else {
            if ($content['product-save-type'] == 'save-woo-draft'){
                wp_send_json_success(['status' => "Product saved as Draft."]);
            }else if( $content['product-save-type'] == 'save-woo-product'){
                wp_send_json_success(['status' => "Product has been Published."]);
            }else{
                wp_send_json_success(['status' => "Product saved an Blue Raven Draft."]);
            }
        }
    }
}