<?php 
/**
 * v2.1.0
 * status: completed
 */
# ST_PROQYZ_IELTSLMS_EVALUATION_ADD_TO_CART



add_action('wp_ajax_ST_PROQYZ_IELTSLMS_EVALUATION_ADD_TO_CART', 'ST_PROQYZ_IELTSLMS_EVALUATION_ADD_TO_CART_callback');
function ST_PROQYZ_IELTSLMS_EVALUATION_ADD_TO_CART_callback(){
    if(
        isset($_POST['id']) && !empty($_POST['id']) && 
        isset($_POST['task']) && !empty($_POST['task']) &&
        isset($_POST['category']) && !empty($_POST['category'])
        
    ) {

        global $wpdb, $table_proqyz_v3_progress_submissions; // db tables progress submissions
        global $ST_OPTION_st_proqyz_IELTS_LMS_enable_evaluation, // root option for evaluation
        $ST_OPTION_st_proqyz_IELTS_LMS_enable_ai_evaluation; // root option for ai evaluation

        # writing evaluation (instructor)
        global $ST_OPTION_st_proqyz_IELTS_LMS_writing_task1_evaluation_enable, // writing task 1 evaluation enable - instructor
        $ST_OPTION_st_proqyz_IELTS_LMS_writing_task2_evaluation_enable, // writing task 2 evaluation enable - instructor
        $ST_OPTION_st_proqyz_IELTS_LMS_writing_task1and2_evaluation_enable, // writing task 1 and 2 evaluation enable - instructor
        $ST_OPTION_st_proqyz_IELTS_LMS_writing_task1_evaluation_plan_id, // writing task 1 evaluation plan id - instructor
        $ST_OPTION_st_proqyz_IELTS_LMS_writing_task2_evaluation_plan_id, // writing task 2 evaluation plan id - instructor
        $ST_OPTION_st_proqyz_IELTS_LMS_writing_task1and2_evaluation_plan_id; // writing task 1 and 2 evaluation plan id - instructor
        # writing evaluation (ai)
        global $ST_OPTION_st_proqyz_IELTS_LMS_ai_writing_task1_evaluation_enable, // writing task 1 evaluation enable - ai
        $ST_OPTION_st_proqyz_IELTS_LMS_ai_writing_task2_evaluation_enable, // writing task 2 evaluation enable - ai
        $ST_OPTION_st_proqyz_IELTS_LMS_ai_writing_task1and2_evaluation_enable, // writing task 1 and 2 evaluation enable - ai
        $ST_OPTION_st_proqyz_IELTS_LMS_ai_writing_task1_evaluation_plan_id, // writing task 1 evaluation plan id - ai
        $ST_OPTION_st_proqyz_IELTS_LMS_ai_writing_task2_evaluation_plan_id, // writing task 2 evaluation plan id - ai
        $ST_OPTION_st_proqyz_IELTS_LMS_ai_writing_task1and2_evaluation_plan_id; // writing task 1 and 2 evaluation plan id - ai

        # speaking evaluation (instructor)
        global $ST_OPTION_st_proqyz_IELTS_LMS_speaking_evaluation_enable, // speaking evaluation enable - instructor
        $ST_OPTION_st_proqyz_IELTS_LMS_speaking_evaluation_plan_id; // speaking evaluation plan id - instructor
        # speaking evaluation (ai)
        global $ST_OPTION_st_proqyz_IELTS_LMS_ai_speaking_evaluation_enable, // speaking evaluation enable - ai
        $ST_OPTION_st_proqyz_IELTS_LMS_ai_speaking_evaluation_plan_id; // speaking evaluation plan id - ai
        # cart keys
        global 
            $st_proqyz__evaluation_cart__writing_task_1,
			$st_proqyz__evaluation_cart__writing_task_2,
			$st_proqyz__evaluation_cart__writing_task_1_ai,
			$st_proqyz__evaluation_cart__writing_task_2_ai,
			$st_proqyz__evaluation_cart__speaking_tasks,
			$st_proqyz__evaluation_cart__speaking_tasks_ai;

        # checkout page
        global $ST_OPTION_checkout_page;

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

        $enable_evaluation = get_option($ST_OPTION_st_proqyz_IELTS_LMS_enable_evaluation,false);
        $enable_ai_evaluation = get_option($ST_OPTION_st_proqyz_IELTS_LMS_enable_ai_evaluation,false);
        $is_evaliation_enable = false;

        if( $enable_evaluation || $enable_ai_evaluation ) {
            $is_evaliation_enable = true;
        }


        if( !$is_evaliation_enable ){ 
            wp_send_json([
                "error" => (object) [
                    "message" => "Evaluation is disabled",
                    "ai" => $enable_ai_evaluation,
                    "evaluation" => $enable_evaluation
                ]
            ]);
        }

        $result_id      = $_POST['id'];
        $task           = $_POST['task']; // task-{writing-task-id}, speaking-tasks, spea
        
        $category       = $_POST['category'];
        $url            = $_POST['url']; 
        $enrolled_for   = [];


        if( $category == "writing" ) {

            if(isset($_POST['task_id']) && !empty($_POST['task_id'])){
                $task_id        = $_POST['task_id'];


                $task1_plan = 0;
                $task2_plan = 0;
                // $task1and2_plan = 0; - deprecated
                $product_id = null;
                $option_key = '';

                # check result 
                $category = "ielts-writing";
                $get_result = $wpdb->get_row("SELECT `user_id` FROM {$table_proqyz_v3_progress_submissions} WHERE `ID` = '$result_id' AND `quiz_category` = '$category' AND `status` = 1 LIMIT 1");
                if( !$get_result ) {
                    wp_send_json([
                        "error" => (object) [
                            "message" => "Looks like Result with given id dosn't exists anymore !"
                        ]
                    ]);
                }

                $student_id = $get_result->user_id;

                //$check_payment_for_tasks = get_user_meta($student_id,"st_proqyz__evaluation-".$result_id, true);
                $check_payment_for_tasks = st_proqyz_get_submission_evaluation_meta($result_id, "enrolled_for", $student_id, true);
                if( $check_payment_for_tasks ) {
                    $enrolled_for = (array) json_decode( $check_payment_for_tasks, true );
                }

                if(array_key_exists($task_id, $enrolled_for)) {
                    wp_send_json([
                        "error" => (object) [
                            "message" => "Looks like this task is already enrolled!"
                        ]
                    ]);
                }

                
                if( $task == "task-1") {
                    $option_key = $st_proqyz__evaluation_cart__writing_task_1;
                    $task1_enable = get_option($ST_OPTION_st_proqyz_IELTS_LMS_writing_task1_evaluation_enable,false);
                    if($task1_enable == 1 || $task1_enable === true || $task1_enable === '1' || $task1_enable === 'true' ){
                        # GET PRODUCT TASK 1
                        $WRITING_task_1_product_id = get_option($ST_OPTION_st_proqyz_IELTS_LMS_writing_task1_evaluation_plan_id,false);
                        if ( $WRITING_task_1_product_id ) {
                            $WRITING_task_1_product = wc_get_product( $WRITING_task_1_product_id );
                            if( $WRITING_task_1_product ){
                                if( $WRITING_task_1_product->get_price() > 0 ) {
                                    $task1_plan = 1;
                                }
                            }
                        } 

                        if( $task1_plan ) {
                            # $WRITING_task_1_product_id
                            # add to card logic
                            $product_id = $WRITING_task_1_product_id;

                        } else {
                            wp_send_json([
                                "error" => (object) [
                                    "message" => "Evaluation for TASK 1 is disabled or not properly configured"
                                ]
                            ]); 
                        }

                    } else {
                        wp_send_json([
                            "error" => (object) [
                                "message" => "Evaluation for TASK 1 is disabled"
                            ]
                        ]); 
                    }   

                } else if( $task == "task-2") {
                    $option_key = $st_proqyz__evaluation_cart__writing_task_2;
                    $task2_enable = get_option($ST_OPTION_st_proqyz_IELTS_LMS_writing_task2_evaluation_enable,false);
                    if($task2_enable == 1 || $task2_enable === true || $task2_enable === '1' || $task2_enable === 'true' ){
                        # GET PRODUCT TASK 1
                        $WRITING_task_2_product_id = get_option($ST_OPTION_st_proqyz_IELTS_LMS_writing_task2_evaluation_plan_id,false);
                        if ( $WRITING_task_2_product_id ) {
                            $WRITING_task_2_product = wc_get_product( $WRITING_task_2_product_id );
                            if( $WRITING_task_2_product ){
                                if( $WRITING_task_2_product->get_price() > 0 ) {
                                    $task2_plan = 1;
                                }
                            }
                        } 

                        if( $task2_plan ) {
                            # $WRITING_task_2_product_id
                            

                            # add to card logic
                            $product_id = $WRITING_task_2_product_id;

                        } else {
                            wp_send_json([
                                "error" => (object) [
                                    "message" => "Evaluation for TASK 2 is disabled or not properly configured"
                                ]
                            ]); 
                        }

                    } else {
                        wp_send_json([
                            "error" => (object) [
                                "message" => "Evaluation for TASK 2 is disabled"
                            ]
                        ]); 
                    } 

                } else if( $task == "task-1-and-2") {
                    wp_send_json([
                        "error" => (object) [
                            "message" => "Enrollment for TASK 1 + 2 is deprecated",
                            "ver" => '2.1.0.1'
                        ]
                    ]);
                        
                } else if( $task == "ai-task-1") {
                    $option_key = $st_proqyz__evaluation_cart__writing_task_1_ai;
                    $ai_task1_enable = get_option($ST_OPTION_st_proqyz_IELTS_LMS_ai_writing_task1_evaluation_enable,false);
                    if($ai_task1_enable == 1 || $ai_task1_enable === true || $ai_task1_enable === '1' || $ai_task1_enable === 'true' ){
                        # GET PRODUCT TASK 1
                        $ai_WRITING_task_1_product_id = get_option($ST_OPTION_st_proqyz_IELTS_LMS_ai_writing_task1_evaluation_plan_id,false);
                        if ( $ai_WRITING_task_1_product_id ) {
                            $ai_WRITING_task_1_product = wc_get_product( $ai_WRITING_task_1_product_id );
                            if( $ai_WRITING_task_1_product ){
                                if( $ai_WRITING_task_1_product->get_price() > 0 ) {
                                    $ai_task1_plan = 1;
                                }
                            }
                        } 

                        if( $ai_task1_plan ) {
                            # $WRITING_task_1_product_id
                            

                            # add to card logic
                            $product_id = $ai_WRITING_task_1_product_id;

                        } else {
                            wp_send_json([
                                "error" => (object) [
                                    "message" => "Evaluation for AI TASK 1 is disabled or not properly configured"
                                ]
                            ]); 
                        }

                    } else {
                        wp_send_json([
                            "error" => (object) [
                                "message" => "Evaluation for AI TASK 1 is disabled"
                            ]
                        ]); 
                    }   

                } else if( $task == "ai-task-2") {
                    $option_key = $st_proqyz__evaluation_cart__writing_task_2_ai;
                    $ai_task2_enable = get_option($ST_OPTION_st_proqyz_IELTS_LMS_ai_writing_task2_evaluation_enable,false);
                    if($ai_task2_enable == 1 || $ai_task2_enable === true || $ai_task2_enable === '1' || $ai_task2_enable === 'true' ){
                        # GET PRODUCT TASK 1
                        $ai_WRITING_task_2_product_id = get_option($ST_OPTION_st_proqyz_IELTS_LMS_ai_writing_task2_evaluation_plan_id,false);
                        if ( $ai_WRITING_task_2_product_id ) {
                            $ai_WRITING_task_2_product = wc_get_product( $ai_WRITING_task_2_product_id );
                            if( $ai_WRITING_task_2_product ){
                                if( $ai_WRITING_task_2_product->get_price() > 0 ) {
                                    $ai_task2_plan = 1;
                                }
                            }
                        } 

                        if( $ai_task2_plan ) {
                            # $WRITING_task_2_product_id
                            

                            # add to card logic
                            $product_id = $ai_WRITING_task_2_product_id;

                        } else {
                            wp_send_json([
                                "error" => (object) [
                                    "message" => "Evaluation for AI TASK 2 is disabled or not properly configured"
                                ]
                            ]); 
                        }

                    } else {
                        wp_send_json([
                            "error" => (object) [
                                "message" => "Evaluation for AI TASK 2 is disabled"
                            ]
                        ]); 
                    } 

                } else if( $task == "ai-task-1-and-2") {
                    wp_send_json([
                        "error" => (object) [
                            "message" => "Enrollment for AI TASK 1 + 2 is deprecated",
                            "ver" => '2.1.0.1'
                        ]
                    ]);
                        
                } else {
                    wp_send_json([
                        "error" => (object) [
                            "message" => "Unknown task"
                        ]
                    ]);
                }

                if( $product_id !== null ) {
                    // Check if wallet is enabled
                    $wallet_enabled = get_option('st_proqyz_wallet_enable', 0);
                    $product = wc_get_product( $product_id );
                    $product_price = $product ? floatval($product->get_price()) : 0;
                    $product_name = $product ? $product->get_name() : $category.' Evaluation';

                    //proceed with normal checkout
                    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);
                        update_user_meta($student_id,"_st-proqyz__evaluation-cart_details-$product_id",json_encode(array(
                            "product_id"    => $product_id,
                            "redirect_url"  => $url,
                            "result_id"     => $result_id,
                            "option_key"    => $option_key,
                            "task_id"       => $task_id                                  
                        )));
                    }

                    $checkout_page_option = get_option($ST_OPTION_checkout_page,'checkout');
                    $checkout_page = site_url()."/checkout";
                    

                    wp_send_json([
                        "success" => (object) [
                            "message"       => "Redirecting to checkout",
                            "has_redirect"  => true,
                            "redirect_url"  => $checkout_page,
                            "refferal"      => $url
                        ]
                    ]);
                    
                    
                
                } else {
                    wp_send_json([
                        "error" => (object) [
                            "message" => "Product not found"
                        ]
                    ]);
                }

            } else {
                wp_send_json([
                    "error" => (object) [
                        "message" => "Missing required fields"
                    ]
                ]);
            }

        } else if( $category == "speaking" ) {
            $speaking_tasks_plan    = false;
            $product_id             = null;
            $option_key             = '';

            # check result 
            $category = "ielts-speaking";
            $get_result = $wpdb->get_row("SELECT `user_id` FROM {$table_proqyz_v3_progress_submissions} WHERE `ID` = '$result_id' AND `quiz_category` = '$category' AND `status` = 1 LIMIT 1");
            if( !$get_result ) {
                wp_send_json([
                    "error" => (object) [
                        "message" => "Looks like Result with given id dosn't exists anymore !"
                    ]
                ]);
            }

            $student_id = $get_result->user_id;
            $check_payment_for_tasks = st_proqyz_get_submission_evaluation_meta($result_id, "enrolled_for", $student_id, true);
            if( $check_payment_for_tasks ) {
                $enrolled_for = (array) json_decode( $check_payment_for_tasks, true );
            }

            if( $task == "speaking-tasks") {
                $option_key = $st_proqyz__evaluation_cart__speaking_tasks;
                $speaking_tasks_enable = get_option($ST_OPTION_st_proqyz_IELTS_LMS_speaking_evaluation_enable,false);
                if($speaking_tasks_enable === true || $speaking_tasks_enable === 1 || $speaking_tasks_enable === '1' || $speaking_tasks_enable === 'true' ){
                    # GET PRODUCT TASK 1
                    $SPEAKING_TASKS_product_id = get_option($ST_OPTION_st_proqyz_IELTS_LMS_speaking_evaluation_plan_id,false);
                    if ( $SPEAKING_TASKS_product_id ) {
                        $SPEAKING_tasks_product = wc_get_product( $SPEAKING_TASKS_product_id );
                        if( $SPEAKING_tasks_product ){
                            if( $SPEAKING_tasks_product->get_price() > 0 ) {
                                if( array_key_exists('speaking-tasks', (array) $enrolled_for) ) {
                                    wp_send_json([
                                        "error" => (object) [
                                            "message" => "It looks like the Speaking evaluation is already enrolled."
                                        ]
                                    ]);
                                }
                                $product_id = $SPEAKING_TASKS_product_id;
                            }
                        }
                    }

                } else {
                    wp_send_json([
                        "error" => (object) [
                            "message" => "Enrollment for Speaking Tasks is disabled"
                        ]
                    ]); 
                } 
            } else if( $task == "speaking-ai" ) {
                $option_key = $st_proqyz__evaluation_cart__speaking_tasks_ai;
                $ai_speaking_enable = get_option($ST_OPTION_st_proqyz_IELTS_LMS_ai_speaking_evaluation_enable,false);
                if( $ai_speaking_enable === true || $ai_speaking_enable === 1 || $ai_speaking_enable === '1' || $ai_speaking_enable === 'true' ){
                    $AI_SPEAKING_product_id = get_option($ST_OPTION_st_proqyz_IELTS_LMS_ai_speaking_evaluation_plan_id,false);
                    if ( $AI_SPEAKING_product_id ) {
                        $AI_speaking_product = wc_get_product( $AI_SPEAKING_product_id );
                        if( $AI_speaking_product ){
                            if( $AI_speaking_product->get_price() > 0 ) {
                                if( array_key_exists('speaking-ai', (array) $enrolled_for) ) {
                                    wp_send_json([
                                        "error" => (object) [
                                            "message" => "It looks like the AI Speaking evaluation is already enrolled."
                                        ]
                                    ]);
                                }
                                $product_id = $AI_SPEAKING_product_id;
                            }
                        }
                    }

                    if( $product_id === null ) {
                        wp_send_json([
                            "error" => (object) [
                                "message" => "AI Speaking evaluation plan is disabled or not properly configured"
                            ]
                        ]);
                    }
                } else {
                    wp_send_json([
                        "error" => (object) [
                            "message" => "Enrollment for AI Speaking evaluation is disabled"
                        ]
                    ]);
                }

            } else {
                wp_send_json([
                    "error" => (object) [
                        "message" => "Unknown task"
                    ]
                ]);
            }


            # final checkout process
            if( $product_id !== null ) {
                // Check if wallet is enabled
                $wallet_enabled = get_option('st_proqyz_wallet_enable', 0);
                $product = wc_get_product( $product_id );
                $product_price = $product ? floatval($product->get_price()) : 0;

                $product_name = $product ? $product->get_name() : $category.' Evaluation';
                // If wallet is enabled and product has price, check wallet balance
                if( $wallet_enabled && $product_price > 0 && class_exists('ProQyz_Wallet') ) {
                    $wallet_balance = ProQyz_Wallet::get_balance($student_id);
                    $sufficient_balance = $wallet_balance >= $product_price;
                    
                    // Store cart details for wallet payment
                    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);
                        update_user_meta($student_id,"_st-proqyz__evaluation-cart_details-$product_id",json_encode(array(
                            "product_id"    => $product_id,
                            "redirect_url"  => $url,
                            "result_id"     => $result_id,
                            "option_key"    => $option_key                                  
                        )));
                    }
                    
                    // Return wallet info instead of redirecting
                    wp_send_json([
                        "success" => (object) [
                            "product_name"          => $product_name,
                            "wallet_enabled"        => true,
                            "wallet_balance"        => floatval($wallet_balance),
                            "product_price"         => $product_price,
                            "sufficient_balance"    => $sufficient_balance,
                            "message"               => $sufficient_balance ? "You can pay with wallet" : "Insufficient wallet balance",
                            "redirect_url"          => $sufficient_balance ? "" : site_url()."/checkout",
                            "has_redirect"          => !$sufficient_balance,
                            "refferal"              => $url
                        ]
                    ]);
                } else {
                    // Wallet disabled or free product - proceed with normal checkout
                    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);
                        update_user_meta($student_id,"_st-proqyz__evaluation-cart_details-$product_id",json_encode(array(
                            "product_id"    => $product_id,
                            "redirect_url"  => $url,
                            "result_id"     => $result_id,
                            "option_key"    => $option_key                                  
                        )));
                    }

                    $checkout_page_option = get_option($ST_OPTION_checkout_page,'checkout');
                    $checkout_page = site_url()."/checkout";
                    

                    wp_send_json([
                        "success" => (object) [
                            "message"       => "Redirecting to checkout",
                            "has_redirect"  => true,
                            "redirect_url"  => $checkout_page,
                            "refferal"      => $url
                        ]
                    ]);
                }
            
            } else {
                wp_send_json([
                    "error" => (object) [
                        "message" => "Product not found"
                    ]
                ]);
            }

        } else {
            wp_send_json([
                "error" => (object) [
                    "message" => "Unknown category"
                ]
            ]);
        }

    } else {
        wp_send_json([
            "error" => (object) [
                "message" => "Missing required fields"
            ]
        ]);
    }
}




