<?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        Handle response for product creation 
 * 
 * =============================================================================
 * 
 * || INDEX:
 * ||   -  HANDLE RESPONSE
 * ||   -  ERROR
 * ||   -  PAUSED
 * || 
 * =============================================================================
 */

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

/*
============================================================
    HANDLE RESPONSE
============================================================
*/ 

function handleResponse($params){
    
    $action = $params['action'] ?? 'Failed';
    $status = $params['status'] ?? '';
    $productID = $params['product_id'] ?? '';
    $result = $params['result'] ?? '';
    
    global $wpdb;
    $table_name = $wpdb->prefix . 'BlueRavenProducts';
    $current_status = $wpdb->get_var($wpdb->prepare("SELECT status FROM {$table_name} WHERE id = %d",$productID));
    
    if($params['status'] == 'completed' && $action != 'Failed'){
        switch ($action) {
            case 'create product':
                $content = json_decode($result, true);
                $content = $content['choices'][0]['message']['content'] ?? null;
                preg_match('/```json\s*(.*?)\s*```/s', $content, $matches);
                $innerJson = $matches[1] ?? null;

                if ($innerJson) {
                    $productData = json_decode($innerJson, true);

                    $title = ($productData['title'] ?? '404');
                    $shortDescription = ($productData['short_description'] ?? '404');
                    $longDescription = ($productData['long_description'] ?? '404');
                    $tags = json_encode($productData['tags'] ?? '404');
                    $metaTitle = ($productData['meta_title'] ?? '404');
                    $metaDescription = ($productData['meta_description'] ?? '404');
                    $metaTags = json_encode($productData['meta_tags'] ?? '404');
                    $price = ($productData['price'] ?? '404');
                    $notification = ($productData['notification'] ?? '');
                    
    ## =========== Fetch Create JSON =========== ##
                    
                    $create_json = $wpdb->get_var($wpdb->prepare("SELECT create_json FROM $table_name WHERE ID = %d",$productID));
                    $create_json = json_decode($create_json, true);
                    
    ## =========== Get Category and Check Title =========== ##
                    
                    $category = !empty($create_json['productCategory']) ? $create_json['productCategory'] : 'uncategorized';
                    $keepTitle = $create_json['keep-title'] ?? 'false';
                    $title = (trim($keepTitle) === 'on') ? trim($create_json['product-title']) : $title;

    ## =========== Save to table =========== ##
    
                    $invalid_statuses = ['pending', 'Failed', 'Service Halt'];
                    $status = in_array($current_status, $invalid_statuses, true) ? 'draft' : $current_status;
     
                    $data = array(
                        'title'                 => $title,
                        'status'                => $status,
                        'pending'               => false,
                        'description'           => $longDescription,
                        'short_description'     => $shortDescription,
                        'category'              => $category,
                        'price'                 => $price,
                        'meta_title'            => $metaTitle,
                        'meta_description'      => $metaDescription,
                        'meta_keywords'         => $metaTags,
                        'notification'          => $notification,
                        'updated_at'            => current_time('mysql'), 
                    );
                    
                    $format = array(
                        '%s', // title
                        '%s', // status
                        '%d', // pending
                        '%s', // description
                        '%s', // short_description
                        '%s', // category
                        '%d', // price (assuming this is a decimal/number)
                        '%s', // meta_title
                        '%s', // meta_description
                        '%s', // meta_keywords
                        '%s', // notification
                        '%s', // updated_at
                    );
                    
                    $where = array( 'id' => $productID );
                    $where_format = array( '%d' );
                    $success = $wpdb->update($table_name, $data, $where, $format, $where_format);
                    
                } else { BlueRaven_SendError("Error", "blue-raven/includes/third-party/admin-blue-raven-catch-handler.php", "No JSON found :: ", "content: " . $content); }
                         
                break;
            default:
                break;
        }
        
/*
============================================================
    ERROR
============================================================
*/         
        
    }else if($params['status'] == 'error'){
        
    ## =========== Save to table =========== ##

        $data = array('status' => 'Failed' ,'pending' => false,'notification' => $result,'updated_at' => current_time('mysql'), );
        $format = array('%s', '%d', '%s', '%s', );
        $where = array( 'id' => $productID );
        $where_format = array( '%d' );
        
        $success = $wpdb->update($table_name, $data, $where, $format, $where_format);
                    
        if ($success === false) BlueRaven_SendError("Error", "blue-raven/includes/third-party/admin-blue-raven-catch-handler.php", "BLUE RAVEN SERVER ERROR", 'DB update failed: ' . $wpdb->last_error);
        
/*
============================================================
    PAUSED
============================================================
*/          
        
    }else if($params['status'] == 'paused'){
         
    ## =========== Save to table =========== ##
    
        $data = array('status'=> 'Service Halt','pending'=> false,'notification'=> $result,'updated_at'=> current_time('mysql'), );
        $format = array('%s','%d','%s','%s',);
        $where = array( 'id' => $productID );
        $where_format = array( '%d' ); 

        $success = $wpdb->update($table_name, $data, $where, $format, $where_format);

        if ($success === false) BlueRaven_SendError("Error", "blue-raven/includes/third-party/admin-blue-raven-catch-handler.php", "BLUE RAVEN SERVER ERROR", 'DB update failed: ' . $wpdb->last_error);
    }
}




    