<?php 
# woocommerce hooks

add_action('woocommerce_payment_complete_order_status_completed', 'woocommerce_pre_payment_complete_function');
function woocommerce_pre_payment_complete_function($order_id){
    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;

    $order = new WC_Order( $order_id );
    $items = $order->get_items(); 
    $student_id = $order->get_user_id();
    $is_complete_hook = false;
    // wallet recharge - intergration -------------------
    $total_recharge_amount = 0;
    $processed_products = array();
    
    foreach ( $items as $item ) {
        $product_id = $item['product_id'];
        $quantity = $item->get_quantity();
        $cart_meta = get_user_meta($student_id, '_st-proqyz__evaluation-cart_details-'.$product_id, true);

        if( $cart_meta ) {
            $cart_json = json_decode($cart_meta);
            $result_id = $cart_json->result_id;
            $task_id   = isset($cart_json->task_id) ? $cart_json->task_id : null;
            // later add tasks id for both tasks

            // Retrieve existing enrolled tasks
            $enrolled_for = [];
            //$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);
            }

            // Handle different option keys
            if( $cart_json->option_key == $st_proqyz__evaluation_cart__writing_task_1 ){
                if( !empty($task_id) ){
                    $enrolled_for[$task_id] = [
                        "task_id"       => $task_id,
                        "task_key"      => $st_proqyz__evaluation_cart__writing_task_1,
                        "payment_for"   => 'instructor'
                    ];
                }
            } 
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__writing_task_2 ){
                if( !empty($task_id) ){
                    $enrolled_for[$task_id] = [
                        "task_id"       => $task_id,
                        "task_key"      => $st_proqyz__evaluation_cart__writing_task_2,
                        "payment_for"   => 'instructor'
                    ];
                }
            } 
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__writing_task_1_ai ){
                if( !empty($task_id) ){
                    $enrolled_for[$task_id] = [
                        "task_id"       => $task_id,
                        "task_key"      => $st_proqyz__evaluation_cart__writing_task_1_ai,
                        "payment_for"   => 'ai'
                    ];
                }
            } 
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__writing_task_2_ai ){
                if( !empty($task_id) ){
                    $enrolled_for[$task_id] = [
                        "task_id"       => $task_id,
                        "task_key"      => $st_proqyz__evaluation_cart__writing_task_2_ai,
                        "payment_for"   => 'ai'
                    ];
                }
            }  
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__speaking_tasks ) { 
                if(!isset($enrolled_for['speaking-tasks'])) {
                    $enrolled_for['speaking-tasks'] = [
                        "task_id"     => 'speaking-tasks',
                        "task_key"    => $st_proqyz__evaluation_cart__speaking_tasks,
                        "payment_for" => 'instructor'
                    ];
                }
                
            } 
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__speaking_tasks_ai ) {
                if(!isset($enrolled_for['speaking-ai'])) {
                    $enrolled_for['speaking-ai'] = [
                        "task_id"     => 'speaking-ai',
                        "task_key"    => $st_proqyz__evaluation_cart__speaking_tasks_ai,
                        "payment_for" => 'ai'
                    ];
                }
                
            } 

            // Update user meta with enrolled tasks
            //update_user_meta($student_id,"st_proqyz__evaluation-".$result_id,json_encode($enrolled_for));
            st_proqyz_update_submission_evaluation_meta($result_id, "enrolled_for", json_encode($enrolled_for), $student_id);

            // Remove cart details meta
            delete_user_meta($student_id, '_st-proqyz__evaluation-cart_details-'.$product_id);
            
            // Trigger completion hook if necessary
            if( $is_complete_hook ) {
                do_action( 'woocommerce_order_status_completed', $order_id );
            }
        }

        if(!class_exists('ProQyz_Wallet')) {
            add_user_meta($student_id, '_proqyz_wallet_recharge_notice', 'ProQyz Wallet plugin is not installed. Please install and activate it to enable wallet recharge functionality.');
            return;
        }

        if( class_exists('ProQyz_Wallet') ) {
            // wallet recharge - intergration -------------------
            // Get wallet recharge amount for this product
            $wallet_recharge_amount = get_post_meta($product_id, '_proqyz_wallet_recharge_amount', true);
            if ($wallet_recharge_amount && floatval($wallet_recharge_amount) > 0) {
                $recharge_amount = floatval($wallet_recharge_amount) * intval($quantity);
                $total_recharge_amount += $recharge_amount;
                
                $product = wc_get_product($product_id);
                $product_name = $product ? $product->get_name() : __('Product', 'proqyz');
                
                $processed_products[] = array(
                    'product_id' => $product_id,
                    'product_name' => $product_name,
                    'quantity' => $quantity,
                    'amount' => $recharge_amount
                );
            }

            if ($total_recharge_amount > 0) {
                $product_names = array();
                foreach ($processed_products as $prod) {
                    $product_names[] = $prod['product_name'] . ' (x' . $prod['quantity'] . ')';
                }
                
                $description = sprintf(
                    __('Wallet recharge from order #%d - %s', 'proqyz'),
                    $order_id,
                    implode(', ', $product_names)
                );
                
                // Add balance to wallet
                $transaction_id = ProQyz_Wallet::add_balance(
                    $student_id,
                    $total_recharge_amount,
                    $description,
                    $order_id,
                    'order',
                    null
                );
                
                if ($transaction_id) {
                    // Mark order as processed to prevent duplicate processing
                    $order->update_meta_data('_proqyz_wallet_recharge_processed', 'yes');
                    $order->update_meta_data('_proqyz_wallet_recharge_amount', $total_recharge_amount);
                    $order->save();
                    
                    // Add order note
                    $order->add_order_note(
                        sprintf(
                            __('Wallet recharged: %s added to customer wallet (Transaction ID: %d)', 'proqyz'),
                            wc_price($total_recharge_amount),
                            $transaction_id
                        )
                    );
                }
            }
        }
    }
}


add_action('woocommerce_order_status_completed','woocommerce_order_status_completed_function');
function woocommerce_order_status_completed_function($order_id){
    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;
    $order = new WC_Order( $order_id );
    $items = $order->get_items(); 
    $student_id = $order->get_user_id();
    $is_complete_hook = true;
    // wallet recharge - intergration -------------------
    $total_recharge_amount = 0;
    $processed_products = array();
    
    foreach ( $items as $item ) {
        $product_id = $item['product_id'];
        $quantity = $item->get_quantity();
        $cart_meta = get_user_meta($student_id, '_st-proqyz__evaluation-cart_details-'.$product_id, true);

        if( $cart_meta ) {
            $cart_json = json_decode($cart_meta);
            $result_id = $cart_json->result_id;
            $task_id   = isset($cart_json->task_id) ? $cart_json->task_id : null;

            // Retrieve existing enrolled tasks
            $enrolled_for = [];
            //$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);
            }

            // Handle different option keys
            if( $cart_json->option_key == $st_proqyz__evaluation_cart__writing_task_1 ){
                if( !empty($task_id) ){
                    $enrolled_for[$task_id] = [
                        "task_id"       => $task_id,
                        "task_key"      => $st_proqyz__evaluation_cart__writing_task_1,
                        "payment_for"   => 'instructor'
                    ];
                }
            } 
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__writing_task_2 ){
                if( !empty($task_id) ){
                    $enrolled_for[$task_id] = [
                        "task_id"       => $task_id,
                        "task_key"      => $st_proqyz__evaluation_cart__writing_task_2,
                        "payment_for"   => 'instructor'
                    ];
                }
            } 
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__writing_task_1_ai ){
                if( !empty($task_id) ){
                    $enrolled_for[$task_id] = [
                        "task_id"       => $task_id,
                        "task_key"      => $st_proqyz__evaluation_cart__writing_task_1_ai,
                        "payment_for"   => 'ai'
                    ];
                }
            } 
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__writing_task_2_ai ){
                if( !empty($task_id) ){
                    $enrolled_for[$task_id] = [
                        "task_id"       => $task_id,
                        "task_key"      => $st_proqyz__evaluation_cart__writing_task_2_ai,
                        "payment_for"   => 'ai'
                    ];
                }
            }  
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__speaking_tasks ) { 
                if(!isset($enrolled_for['speaking-tasks'])) {
                    $enrolled_for['speaking-tasks'] = [
                        "task_id"     => 'speaking-tasks',
                        "task_key"    => $st_proqyz__evaluation_cart__speaking_tasks,
                        "payment_for" => 'instructor'
                    ];
                }
                
            } 
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__speaking_tasks_ai ) {
                if(!isset($enrolled_for['speaking-ai'])) {
                    $enrolled_for['speaking-ai'] = [
                        "task_id"     => 'speaking-ai',
                        "task_key"    => $st_proqyz__evaluation_cart__speaking_tasks_ai,
                        "payment_for" => 'ai'
                    ];
                }
                
            }   

            // Update user meta with enrolled tasks
            //update_user_meta($student_id,"st_proqyz__evaluation-".$result_id,json_encode($enrolled_for));
            st_proqyz_update_submission_evaluation_meta($result_id, "enrolled_for", json_encode($enrolled_for), $student_id);

            // Remove cart details meta
            delete_user_meta($student_id, '_st-proqyz__evaluation-cart_details-'.$product_id);
            
            // Trigger completion hook if necessary
            if( $is_complete_hook ) {
                do_action( 'woocommerce_order_status_completed', $order_id );
            }
        }

        if(!class_exists('ProQyz_Wallet')) {
            add_user_meta($student_id, '_proqyz_wallet_recharge_notice', 'ProQyz Wallet plugin is not installed. Please install and activate it to enable wallet recharge functionality.');
            return;
        }

        if( class_exists('ProQyz_Wallet') ) {
            // wallet recharge - intergration -------------------
            // Get wallet recharge amount for this product
            $wallet_recharge_amount = get_post_meta($product_id, '_proqyz_wallet_recharge_amount', true);
            if ($wallet_recharge_amount && floatval($wallet_recharge_amount) > 0) {
                $recharge_amount = floatval($wallet_recharge_amount) * intval($quantity);
                $total_recharge_amount += $recharge_amount;
                
                $product = wc_get_product($product_id);
                $product_name = $product ? $product->get_name() : __('Product', 'proqyz');
                
                $processed_products[] = array(
                    'product_id' => $product_id,
                    'product_name' => $product_name,
                    'quantity' => $quantity,
                    'amount' => $recharge_amount
                );
            }

            add_user_meta($student_id, '_proqyz_wallet_recharge_notice--amount', $total_recharge_amount);
            add_user_meta($student_id, '_proqyz_wallet_recharge_notice--products', $processed_products);

            if ($total_recharge_amount > 0) {
                $product_names = array();
                foreach ($processed_products as $prod) {
                    $product_names[] = $prod['product_name'] . ' (x' . $prod['quantity'] . ')';
                }
                
                $description = sprintf(
                    __('Wallet recharge from order #%d - %s', 'proqyz'),
                    $order_id,
                    implode(', ', $product_names)
                );
                
                // Add balance to wallet
                $transaction_id = ProQyz_Wallet::add_balance(
                    $student_id,
                    $total_recharge_amount,
                    $description,
                    $order_id,
                    'order',
                    null
                );
                
                if ($transaction_id) {
                    // Mark order as processed to prevent duplicate processing
                    $order->update_meta_data('_proqyz_wallet_recharge_processed', 'yes');
                    $order->update_meta_data('_proqyz_wallet_recharge_amount', $total_recharge_amount);
                    $order->save();
                    
                    // Add order note
                    $order->add_order_note(
                        sprintf(
                            __('Wallet recharged: %s added to customer wallet (Transaction ID: %d)', 'proqyz'),
                            wc_price($total_recharge_amount),
                            $transaction_id
                        )
                    );
                }
            }
        }
    }
    
}

add_action('woocommerce_order_status_processing','woocommerce_pre_payment_processing_function');
function woocommerce_pre_payment_processing_function($order_id){

    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;
        
    $order = new WC_Order( $order_id );
    $items = $order->get_items(); 
    $student_id = $order->get_user_id();
    $is_complete_hook = false;
    // wallet recharge - intergration -------------------
    $total_recharge_amount = 0;
    $processed_products = array();

    
    foreach ( $items as $item ) {
        $product_id = $item['product_id'];
        $quantity = $item->get_quantity();
        $cart_meta = get_user_meta($student_id, '_st-proqyz__evaluation-cart_details-'.$product_id, true);

        if( $cart_meta ) {
            $cart_json = json_decode($cart_meta);
            $result_id = $cart_json->result_id;
            $task_id   = isset($cart_json->task_id) ? $cart_json->task_id : null;

            // Retrieve existing enrolled tasks
            $enrolled_for = [];
            //$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);
            }

            // Handle different option keys
            if( $cart_json->option_key == $st_proqyz__evaluation_cart__writing_task_1 ){
                if( !empty($task_id) ){
                    $enrolled_for[$task_id] = [
                        "task_id"       => $task_id,
                        "task_key"      => $st_proqyz__evaluation_cart__writing_task_1,
                        "payment_for"   => 'instructor'
                    ];
                }
            } 
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__writing_task_2 ){
                if( !empty($task_id) ){
                    $enrolled_for[$task_id] = [
                        "task_id"       => $task_id,
                        "task_key"      => $st_proqyz__evaluation_cart__writing_task_2,
                        "payment_for"   => 'instructor'
                    ];
                }
            } 
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__writing_task_1_ai ){
                if( !empty($task_id) ){
                    $enrolled_for[$task_id] = [
                        "task_id"       => $task_id,
                        "task_key"      => $st_proqyz__evaluation_cart__writing_task_1_ai,
                        "payment_for"   => 'ai'
                    ];
                }
            } 
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__writing_task_2_ai ){
                if( !empty($task_id) ){
                    $enrolled_for[$task_id] = [
                        "task_id"       => $task_id,
                        "task_key"      => $st_proqyz__evaluation_cart__writing_task_2_ai,
                        "payment_for"   => 'ai'
                    ];
                }
            }  
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__speaking_tasks ) { 
                if(!isset($enrolled_for['speaking-tasks'])) {
                    $enrolled_for['speaking-tasks'] = [
                        "task_id"     => 'speaking-tasks',
                        "task_key"    => $st_proqyz__evaluation_cart__speaking_tasks,
                        "payment_for" => 'instructor'
                    ];
                }
                
            } 
            // new - working
            else if( $cart_json->option_key == $st_proqyz__evaluation_cart__speaking_tasks_ai ) {
                if(!isset($enrolled_for['speaking-ai'])) {
                    $enrolled_for['speaking-ai'] = [
                        "task_id"     => 'speaking-ai',
                        "task_key"    => $st_proqyz__evaluation_cart__speaking_tasks_ai,
                        "payment_for" => 'ai'
                    ];
                }
                
            }   

            // Update user meta with enrolled tasks
            //update_user_meta($student_id,"st_proqyz__evaluation-".$result_id,json_encode($enrolled_for));
            st_proqyz_update_submission_evaluation_meta($result_id, "enrolled_for", json_encode($enrolled_for), $student_id);

            // Remove cart details meta
            delete_user_meta($student_id, '_st-proqyz__evaluation-cart_details-'.$product_id);
            
            // Trigger completion hook if necessary
            if( $is_complete_hook ) {
                do_action( 'woocommerce_order_status_completed', $order_id );
            }
        }

        if(!class_exists('ProQyz_Wallet')) {
            add_user_meta($student_id, '_proqyz_wallet_recharge_notice', 'ProQyz Wallet plugin is not installed. Please install and activate it to enable wallet recharge functionality.');
            return;
        }

        if( class_exists('ProQyz_Wallet') ) {
            // wallet recharge - intergration -------------------
            // Get wallet recharge amount for this product
            $wallet_recharge_amount = get_post_meta($product_id, '_proqyz_wallet_recharge_amount', true);
            if ($wallet_recharge_amount && floatval($wallet_recharge_amount) > 0) {
                $recharge_amount = floatval($wallet_recharge_amount) * intval($quantity);
                $total_recharge_amount += $recharge_amount;
                
                $product = wc_get_product($product_id);
                $product_name = $product ? $product->get_name() : __('Product', 'proqyz');
                
                $processed_products[] = array(
                    'product_id' => $product_id,
                    'product_name' => $product_name,
                    'quantity' => $quantity,
                    'amount' => $recharge_amount
                );
            }

            if ($total_recharge_amount > 0) {
                $product_names = array();
                foreach ($processed_products as $prod) {
                    $product_names[] = $prod['product_name'] . ' (x' . $prod['quantity'] . ')';
                }
                
                $description = sprintf(
                    __('Wallet recharge from order #%d - %s', 'proqyz'),
                    $order_id,
                    implode(', ', $product_names)
                );
                
                // Add balance to wallet
                $transaction_id = ProQyz_Wallet::add_balance(
                    $student_id,
                    $total_recharge_amount,
                    $description,
                    $order_id,
                    'order',
                    null
                );
                
                if ($transaction_id) {
                    // Mark order as processed to prevent duplicate processing
                    $order->update_meta_data('_proqyz_wallet_recharge_processed', 'yes');
                    $order->update_meta_data('_proqyz_wallet_recharge_amount', $total_recharge_amount);
                    $order->save();
                    
                    // Add order note
                    $order->add_order_note(
                        sprintf(
                            __('Wallet recharged: %s added to customer wallet (Transaction ID: %d)', 'proqyz'),
                            wc_price($total_recharge_amount),
                            $transaction_id
                        )
                    );
                }
            }
        }
    }
}



# hooks 
function proqyz_course_woocommerce_pre_payment_processing_callback( $order_id ){
    $order = new WC_Order( $order_id );
    $items = $order->get_items(); 
    $current_user_id = $order->get_user_id();
    $is_paid    = 0;
    $is_onhold  = 0;
    foreach ( $items as $item ) {
        $product_id = $item->get_product_id();
        # check if this course belongs to a ilms-course
        $get_product_type = get_post_meta($product_id, 'product_type', true);
        if( $get_product_type ){
            if( $get_product_type === "proqyz-course" ) {
                # product SKU
                $product = wc_get_product($product_id);
                if( $product ){
                    # sku
                    $product_sku = $product->get_sku();
                    # perform the enroll logic
                    $get_payment_meta = get_post_meta($product_id, 'course-meta_payment', true);
                    if( $get_payment_meta ) {
                        $course_payment_settings    = (object) $get_payment_meta;
                        $course_access              = isset($course_payment_settings->access)? $course_payment_settings->access : 'open';
                                
                        if( $course_access == "enroll" ) {
                            $course_price           = isset($course_payment_settings->price)? $course_payment_settings->price : 0;
                            $course_sale_price      = isset($course_payment_settings->sale)? $course_payment_settings->sale : 0;
                            $course_expire_obj      = isset($course_payment_settings->expire)? (object) $course_payment_settings->expire : null;
                            $course_expire_status   = isset($course_expire_obj->status)? (string) $course_expire_obj->status : 'never';
                            $course_expire_days     = isset($course_expire_obj->dd)? (int) $course_expire_obj->dd : 0;


                            if( $course_expire_status == "never" ) {
                                # no need to calculate payment anymore
                                $order_confirmation     = (object) [
                                    "expire"        => "never",
                                    "enroll"        => true,
                                    "access"        => "enroll",
                                    "created_at"    => date("U"),
                                    "expires_in"    => 0,    
                                    "expires_on"    => 0,
                                    "status"        => "active"
                                ];
                            } else if( $course_expire_status == "time" ) {
                                # payment - expire - days
                                if($course_expire_days > 0){
                                    $mili_time  = ((int) $course_expire_days * 86400);
                                    $expires_on = date("U") + $mili_time;

                                    $order_confirmation     = (object) [
                                        "expire"        => "expire",
                                        "enroll"        => true,
                                        "access"        => "enroll",
                                        "created_at"    => date("U"),
                                        "expires_in"    => $course_expire_days,    
                                        "expires_on"    => $expires_on,
                                        "status"        => "active"
                                    ];
                                } else {
                                    $order_confirmation     = (object) [
                                        "expire"        => "never",
                                        "enroll"        => true,
                                        "access"        => "enroll",
                                        "created_at"    => date("U"),
                                        "expires_in"    => 0,    
                                        "expires_on"    => 0,
                                        "status"        => "active"
                                    ];
                                }
                            }

                            $enroll_meta = update_user_meta( $current_user_id, 'enroll-'.$product_sku, $order_confirmation);
                        
                        } else if( $course_access == "open" ) {
                            // no need to do anything
                        }
                    }

                    
                }
            }
        }
        
    }
    
}



add_action('woocommerce_payment_complete_order_status_completed', 'proqyz_course_woocommerce_pre_payment_processing_callback');
add_action('woocommerce_order_status_completed','proqyz_course_woocommerce_pre_payment_processing_callback');
add_action('woocommerce_order_status_processing','proqyz_course_woocommerce_pre_payment_processing_callback');
add_action('woocommerce_cod_process_payment', 'proqyz_course_woocommerce_pre_payment_processing_callback');
