<?php 
require_once 'woo-hooks.php';
/**
 * Set product image from a URL.
 */
function set_product_image_from_url($product_id, $image_url) {
    if (!$product_id || !$image_url) {
        return false;
    }

    // Check if the product already has a featured image set
    $current_thumbnail_id = get_post_thumbnail_id($product_id);
    if ($current_thumbnail_id) {
        // Remove the existing featured image
        wp_delete_attachment($current_thumbnail_id, true);
    }

    // Get the file type
    $filetype = wp_check_filetype(basename($image_url), null);
    if (!$filetype['type']) {
        return false;
    }

    // Prepare upload directory
    $upload_dir = wp_upload_dir();

    // Generate sanitized filename
    $filename = sanitize_file_name(basename($image_url)); // Original filename
    $filename = str_replace(' ', '-', $filename); // Replace spaces with hyphens
    $filename = strtolower($filename); // Convert to lowercase
    $filename = 'small-' . $filename; // Prefix with 'small-'

    // Ensure filename is unique in the upload directory
    $filename = wp_unique_filename($upload_dir['path'], $filename);

    // Set the full path to the file
    $file_path = $upload_dir['path'] . '/' . $filename;

    // Download the file
    $image_data = file_get_contents($image_url);
    if ($image_data === false) {
        return false;
    }

    // Save the file to the uploads directory
    file_put_contents($file_path, $image_data);

    // Prepare an array of post data for the attachment
    $attachment = array(
        'guid'           => $upload_dir['url'] . '/' . basename($file_path),
        'post_mime_type' => $filetype['type'],
        'post_title'     => pathinfo($filename, PATHINFO_FILENAME),
        'post_content'   => '',
        'post_status'    => 'inherit'
    );

    // Insert the attachment into the media library
    $attach_id = wp_insert_attachment($attachment, $file_path, $product_id);

    // Generate the metadata for the attachment and update the database record
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata($attach_id, $file_path);
    wp_update_attachment_metadata($attach_id, $attach_data);

    // Set the image as the product's featured image
    set_post_thumbnail($product_id, $attach_id);

    return true;
}

// Define the custom filter function
function proqyz_course_get_woo_product_callback($content, $params = []) {
    // Your custom filtering logic here
    $params = (object) $params;
    $product_meta_unique_key = $params->_id;
    $product_name = $params->title;
    $product_description = $params->description;
    $product_price = $params->price;
    $product_sale_price = $params->sale;
    $product_payment = (object) $params->_payment;
    $product_thumbnail = isset($params->thumbnail) ? $params->thumbnail : null;

    // Check if WooCommerce is active
    if (!class_exists('WooCommerce')) {
        return (object)["error" => (object)[
            "message" => "Woocommerce is not active"
        ]];
    }

    // Check if product with unique key exists
    $existing_product_id = wc_get_product_id_by_sku($product_meta_unique_key);
    if ($existing_product_id) {

        // Update existing product
        $product = wc_get_product($existing_product_id);
        // Update product data
        $product->set_name($product_name);
        $product->set_description($product_description);
        // Set other product data as needed
        if ($product_sale_price > 0) {
            $product->set_sale_price($product_sale_price);
            $product->set_regular_price($product_price);
        } else {
            $product->set_regular_price($product_price);
            $product->set_sale_price('');
        }
        $product->update_meta_data("course-meta_payment", $product_payment);
        $product->update_meta_data("product_type", "proqyz-course");
        // Save product
        $product->save();

        $u_product = wc_get_product($existing_product_id);
        // Get the regular price and sale price
        $product_price = $u_product->get_regular_price();
        $product_sale_price = $u_product->get_sale_price();

        return (object)["success" => (object)[
            "original_amount" => $product_price,
            "sale_amount" => $product_sale_price,
            "currency_symbol" => get_woocommerce_currency_symbol(),
            "product_id" => $existing_product_id
        ]];
    } else {

        // Create new product
        $product = new WC_Product_Simple();
        $product->set_name($product_name);
        $product->set_description($product_description);
        // Set other product data as needed
        if ($product_sale_price > 0) {
            $product->set_sale_price($product_sale_price);
            $product->set_regular_price($product_price);
        } else {
            $product->set_regular_price($product_price);
            $product->set_sale_price('');
        }
        // Set unique key as SKU
        $product->set_sku($product_meta_unique_key);
        // Save product
        $product->update_meta_data("course-meta_payment", $product_payment);
        $product->update_meta_data("product_type", "proqyz-course");

        $product_id = $product->save();

        $u_product = wc_get_product($product_id);
        // Get the regular price and sale price
        $product_price = $u_product->get_regular_price();
        $product_sale_price = $u_product->get_sale_price();

        if ($product_thumbnail) {
            set_product_image_from_url($product_id, $product_thumbnail);
        }

        return (object)["success" => (object)[
            "original_amount" => $product_price,
            "sale_amount" => $product_sale_price,
            "currency_symbol" => get_woocommerce_currency_symbol(),
            "product_id" => $product_id
        ]];
    }

    return (object)["error" => (object)[
        "message" => "Empty response"
    ]];
}

// Hook the custom filter function to a filter hook
add_filter('proqyz-course-get-woo-product', 'proqyz_course_get_woo_product_callback', 10, 3);
