<?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        The Front end AJAX for the Product Table
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - WP AJAX BLUE RAVEN MY TABLE
 * || 
 * =============================================================================
 */

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

/*
============================================================
    WP AJAX BLUE RAVEN MY TABLE
============================================================
*/

add_action('wp_ajax_blue_raven_my_table', 'wp_ajax_blue_raven_my_products_table');

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

	if ( ! wp_verify_nonce( $nonce, 'blue_raven_my_table_nonce' ) ) {
		BlueRaven_SendError("ERROR", "blue-raven/includes/admin-products-table.php", "wp_ajax_blue_raven_my_products_table", "Invalid nonce");
		wp_send_json_error('Invalid nonce');
	}

    ## =========== Action =========== ##
        
   	$action = sanitize_text_field( wp_unslash( $_POST['subaction'] ?? '' ) );
    
    if ($action === 'reload') {
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Values are sanitized after unpacking
        $content = isset($_POST['content']) ? wp_unslash($_POST['content']) : [];

        $filter = isset($content[0]) ? sanitize_text_field($content[0]) : '';
        $search = isset($content[1]) ? sanitize_text_field($content[1]) : '';
        $page   = isset($content[2]) ? sanitize_text_field($content[2]) : '';
    
        if (!class_exists('Blue_Raven_Admin_My_Products')) require_once BLUERAVEN_PLUGIN_DIR . '/templates/class-admin-my-products.php';
        
        $instance = new Blue_Raven_Admin_My_Products();
        ob_start();
        $instance->innerTableRender($filter, $search, $page);
        $content = ob_get_clean();
        
		// Already Escaped
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped 
        echo $content;
        wp_die();
        
    ## =========== FAVORITES =========== ##        
        
    } else if ($action === 'favorite') {
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Array sanitized after unpacking
        $content = isset($_POST['content']) ? wp_unslash($_POST['content']) : [];

        // Individually sanitize values
        $product_id = isset($content[0]) ? intval($content[0]) : 0;
        $favorite_value = isset($content[1]) ? $content[1] : false;

        if ($product_id > 0) {
            $favorite_int = filter_var($favorite_value, FILTER_VALIDATE_BOOLEAN) ? 1 : 0;

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

            $updated = $wpdb->update(
                $table_name,
                ['favorite' => $favorite_int],
                ['id' => $product_id],
                ['%d'],
                ['%d']
            );

            if ($updated === false) {
                error_log("Update failed: " . $wpdb->last_error);
                BlueRaven_SendError("ERROR", "blue-raven/includes/admin-products-table.php", "Updating Favorite Product", "Failed to update table: $table_name : $favorite_int : $product_id");
                exit();
            } else {
                echo $favorite_int === 0 ? "Unfavorited this product" : "Marked this product as a favorite";
                exit();
            }
        } else {
            BlueRaven_SendError("ERROR", "blue-raven/includes/admin-products-table.php", "Updating Favorite Product", "Missing or invalid product ID. Values: " . json_encode($content));
            exit();
        }

        
    ## =========== DELETED =========== ##    
    
    } else if ($action === 'delete') {
        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Input sanitized per-item after unpacking
        $content = isset($_POST['content']) ? wp_unslash($_POST['content']) : [];

        if (!empty($content) && is_array($content)) {
            global $wpdb;
            $table_name = $wpdb->prefix . 'BlueRavenProducts'; 

            foreach ($content as $item) {
                $id = intval($item); // Cast individually
                if ($id > 0) {
                    $woo_product_id = $wpdb->get_var(
                        $wpdb->prepare("SELECT woo_product_id FROM $table_name WHERE id = %d", $id)
                    );
                    
                    if ($woo_product_id) {
                        wp_delete_post($woo_product_id, true);
                    }

                    $wpdb->delete($table_name, ['id' => $id], ['%d']);
                }
            }
        }

        wp_die();
        
    ## =========== IMPORT =========== ##    

    } else if($action == 'import') {
        require_once BLUERAVEN_PLUGIN_DIR . 'includes/third-party/class-blue-raven-woo-exporter.php';
        
        $args = array(
            'post_type'      => 'product',
            'posts_per_page' => -1, 
            'post_status'    => 'publish',
            'fields'         => 'ids', 
        );
        
        $product_ids = get_posts($args);
        foreach ($product_ids as $product_id) { exportWooProduct($product_id);}
        
        echo ('WooCommerce Products Have Been Imported');
        wp_die();
    } 
}