<?php 
/**
 * v2.1.0
 * status: completed
 * action: ilms-course-add-to-cart
 */

function proqyz_course_add_to_cart_callback() {
    if(1 == 1){
        $current_user_id = get_current_user_id();
        if( isset($_POST['id']) && !empty($_POST['id']) ) {
            $product_id = $_POST['id'];

            # Check if WooCommerce is active
            if (!class_exists('WooCommerce')) {
                return (object) [ "error" => (object) [
                    "message" => "Woocommerce is not active",
                    "status"  => 400,
                    "code"    => "ERR::plugin-not-active" 
                ]];
            }

            # get product by id
            $product = wc_get_product($product_id);
            if( $product ) {

                wc()->cart->empty_cart();
                $product_cart_id = WC()->cart->generate_cart_id( $product_id );
                if( ! WC()->cart->find_product_in_cart( $product_cart_id ) ){
                    WC()->cart->add_to_cart( $product_id, 1);
                }

                wp_send_json([
                    "success" => (object) [
                        "redirect" => "/cart"
                    ]
                ]);

            } else {
                wp_send_json([
                    "error" => (object) [
                        "message" => "Missing product by given id",
                        "status"  => 404,
                        "code"    => "ERR::missing-product"  
                    ]
                ]);
            }

        } else {
            wp_send_json([
                "error" => (object) [
                    "message" => "Missing product id",
                    "status"  => 400,
                    "code"    => "ERR::missing-product-id"  
                ]
            ]);
        }
    } else {
        wp_send_json([
            "error" => (object) [
                "message" => "User is not logged in",
                "status"  => 401,
                "code"    => "ERR::unauthorized"  
            ]
        ]);
    }
}

add_action('wp_ajax_proqyz-course-add-to-cart','proqyz_course_add_to_cart_callback');
add_action('wp_ajax_nopriv_proqyz-course-add-to-cart','proqyz_course_add_to_cart_callback');


