<?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        New product, Brandability and more
 * 
 * =============================================================================
 * 
 * || INDEX:
 * ||   - WP AJAX BLUE RAVEN PRODUCTS
 * ||   - BRANDING
 * ||   - NEW PRODUCT
 * ||   - SAVE TO TABLE
 * ||   - PRODUCT CREATE
 * ||
 * =============================================================================
 */

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

/*
============================================================ 
    WP AJAX BLUE RAVEN PRODUCTS
============================================================
*/

add_action('wp_ajax_blue_raven_products', 'wp_ajax_blue_raven_products');

function wp_ajax_blue_raven_products() {
    
	$nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';

	if (!wp_verify_nonce($nonce, 'blue_raven_products_nonce')) {
		BlueRaven_SendError("ERROR", "blue-raven/includes/admin-products.php", "wp_ajax_blue_raven_products", "Invalid nonce");
		wp_send_json_error('Invalid nonce');
	}
    
    ## =========== Action =========== ##
        
	$action = sanitize_text_field(wp_unslash($_POST['subaction'] ?? ''));
    
/*
============================================================
    BRANDING
============================================================
*/

    if ($action === 'brand-options-page') {

        if (!class_exists('Blue_Raven_Admin_Brandability')) { require_once BLUERAVEN_PLUGIN_DIR . '/templates/class-admin-brand.php'; }
        
        $pageView = new Blue_Raven_Admin_Brandability();
        ob_start();
        $pageView->render();
        $content = ob_get_clean();
        
		// Content already escaped
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo $content;
        
    ## =========== save brandability =========== ##
        
    }else if ($action === 'save brandability' && (isset($_POST['content']))){
        
		$content_raw = filter_input(INPUT_POST, 'content', FILTER_UNSAFE_RAW); 
        $content = wp_strip_all_tags($content_raw); 

		if ($content === null) {
			$content = '';
		}

		$content = wp_unslash($content);

		// Validate content before parsing
		if (preg_match('/^[a-zA-Z0-9=&%_\-\.\+]*$/', $content)) {
			parse_str($content, $data);
		} else {
			$data = [];
		}

		// Recursively sanitize parsed data
		function BlueRaven_sanitize_recursive($input) {
			if (is_array($input)) {
				return array_map('BlueRaven_sanitize_recursive', $input);
			}
			return htmlspecialchars($input, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
		}

		$sanitizedData = BlueRaven_sanitize_recursive($data);
        
        ///-- Convert to JSON
        
        $jsonContent = json_encode($sanitizedData);
        if ($jsonContent === false) {
			wp_die(
				esc_html__('Failed to encode JSON: ', 'blue-raven') . esc_html(json_last_error_msg()),
				esc_html__('Error', 'blue-raven'),
				['response' => 500]
			);
		}
        
        $saved = saveToTableBlueRavenValues('brandability', $jsonContent);
        if ($saved) {
            echo('Successfully updated your brand settings.');
        } else {
            echo('Failed to update your brand settings. Please try again or contact support.');
        }
        
        exit();
             
/*
============================================================
    NEW PRODUCT
============================================================
*/  
        
    }else if ($action === 'new product' && (isset($_POST['content']))){   
            
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized after parsing
        $content = wp_unslash($_POST['content'] ?? '');
        
    ## =========== Sanitize content =========== ##
    
        parse_str($content, $parsed);
        $clean = [];
        foreach ($parsed as $key => $value) {
            $clean[$key] = sanitize_text_field($value); 
        }
        
    ## =========== Get title =========== ##
        
        $json = json_encode($clean);
        
        $description = $clean['description'];
        $cut = substr($description, 0, 125);
        if (strlen($description) > 125) { $cut .= '...'; }

    ## =========== Add new product =========== ##
    
        global $wpdb;
        $table_name = $wpdb->prefix . 'BlueRavenProducts';
        
        $data = array('title' => $cut ?? 'New Product','status' => 'pending','pending' => true,'create_json' => $json,'created_at' => current_time('mysql'));
        $format = array('%s', '%s', '%d', '%s', '%s'  );     
        $success = $wpdb->insert($table_name, $data, $format);
        
        if ($success) {
            BlueRaven_createNewProduct($wpdb->insert_id);
            wp_send_json_success([ 'product_id' => $wpdb->insert_id]);
            
        } else {
            BlueRaven_SendError("ERROR", "blue-raven/includes/admin-products.php", "new product", "Failed to insert new product: " .  $wpdb->last_error);
            wp_send_json_error(['message' => 'Database error: ' . $wpdb->last_error ]);

        }
        
    } else if (isset($action) && $action === 'check_product_status') {

        global $wpdb;

        $product_id = isset($_POST['product_id']) ? intval(wp_unslash($_POST['product_id'])) : 0;

        if (!$product_id) {
            wp_send_json_error(['message' => 'Missing or invalid product ID']);
        }

        $table_name = $wpdb->prefix . 'BlueRavenProducts';

        $product = $wpdb->get_row(
            $wpdb->prepare("SELECT pending FROM {$table_name} WHERE id = %d", $product_id),
            ARRAY_A
        );

        if ($product) {
            $is_pending = (bool) $product['pending'];
            wp_send_json_success(['status' => $is_pending]);
        } else {
            wp_send_json_error(['message' => 'Product not found']);
        }
    }
}

/*
============================================================
    SAVE TO TABLE
============================================================
*/  

    ## =========== save to :: BlueRavenValues =========== ##
    
function saveToTableBlueRavenValues($setting_key, $value){
    
    ## =========== get Data =========== ##
    
    global $wpdb;
    
    try {
        $table = $wpdb->prefix . 'BlueRavenValues';
        $data = ['value' => $value,'enabled' => 1,'updated_at' => current_time('mysql', 1)];
        $exists = $wpdb->get_var($wpdb->prepare("SELECT id FROM $table WHERE setting = %s", $setting_key));

    ## =========== Update / Insert Update =========== ##
    
        if ($exists) {
            return $wpdb->update(
                $table,
                $data,
                ['setting' => $setting_key]
            ) !== false;
        } else {
            $data['setting'] = $setting_key;
            $data['created_at'] = current_time('mysql', 1);
            
            return $wpdb->insert($table, $data) !== false;
        }
    } catch (Exception $e) {
        BlueRaven_SendError("ERROR", "blue-raven/includes/admin-products.php", "SAVE TO TABLE ERROR", $e->getMessage());
        error_log('saving update to table failed: ' . $e->getMessage());
        return false;
    }
}

/*
============================================================
    PRODUCT CREATE
============================================================
*/  

function BlueRaven_createNewProduct($productID){
    
    global $wpdb;
    
    try {
        
    ## =========== Get Product Information =========== ##
    
       $product = $wpdb->get_row($wpdb->prepare("SELECT create_json FROM {$wpdb->prefix}BlueRavenProducts AS p WHERE p.id = %d", $productID), ARRAY_A);
        
    ## =========== Get Brand Information =========== ##
    
        $brand = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}BlueRavenValues AS v WHERE v.setting = %s", 'brandability'), ARRAY_A);
    
    ## =========== Get Lisence Key =========== ##
    
        $key = $wpdb->get_var($wpdb->prepare("SELECT value FROM {$wpdb->prefix}BlueRavenConfig AS v WHERE v.setting = %s", 'licenseKey'));
        $token = $wpdb->get_var($wpdb->prepare("SELECT value FROM {$wpdb->prefix}BlueRavenConfig AS v WHERE v.setting = %s", 'licensepass'));

    ## =========== Ping Server =========== ##    

        $url2 = 'https://portal.enterrahost.com/functions/blue-raven/blue-raven-functions.php';
        $args2 = ['body'=> ['p' => 'ping'],'timeout'=> 5,'headers'=> ['Content-Type' => 'application/x-www-form-urlencoded',],'data_format' => 'body',];
        $response2 = wp_remote_post($url2, $args2);

        if (is_wp_error($response2)) {
            $wpdb->update($table_name,['pending'=> true,'notification' => 'Failed to send request to server','request_json' => $payload],['id' => $pid],['%d', '%s', '%s'], ['%d']);
            return;
        }

        ## =========== Post Request Server =========== ##   
    
        $url = 'https://portal.enterrahost.com/functions/blue-raven/blue-raven-functions.php';
        $currency = get_woocommerce_currency();
        $callback_path = site_url('/wp-json/blue-raven/v1/callback'); 
        $rqid = wp_generate_uuid4();
        $pid = $productID;
        
        $data_to_sign = $rqid . $pid . 'create product';
        $signature = hash_hmac('sha256', $data_to_sign, $key);
        $url_parts = wp_parse_url(site_url());
		
        $data = [
            'product'           => $product['create_json'],
            'brand'             => $brand['value'],
            'currency'          => $currency,
            'action'            => 'create product',
            'callback_url'      => $callback_path,
            'request_id'        => $rqid,
            'product_id'        => $pid,
            'auth_signature'    => $signature,
            'token'             => $token,
            'domain'            => $url_parts
        ];    
        
        $payload = json_encode($data);
        
        global $wpdb;
        $table_name = $wpdb->prefix . 'BlueRavenProducts';

    ## =========== Mark as pending and log request =========== ##
        
        $wpdb->update($table_name,['pending'=> true,'notification' => '','request_json' => $payload],['id' => $pid],['%d', '%s', '%s'], ['%d']);
    
    ## ===========  Send request =========== ##
        
        $args = ['body'=> $payload,'timeout'=> 5, 'blocking'=> true,'headers'=> ['Content-Type' => 'application/json'],'data_format' => 'body',];
        $response = wp_remote_post($url, $args);
       
    } catch (Exception $e) {
        BlueRaven_SendError("ERROR", "blue-raven/includes/admin-products.php", "Create Product ERROR", $e->getMessage());
        error_log('saving update to table failed: ' . $e->getMessage());
        return false;
    }  
}
