HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: /var/www/html/shootinschool/wp-content/plugins/shootin-school-plugin/woocommerce_hooks.php
<?php
require __DIR__ . '/vendor/autoload.php';

use Twilio\Rest\Client;
// https://github.com/woocommerce/woocommerce/wiki/Payment-Token-API
// add_action( 'init', 'testing' );
// function testing() {
//     $token = new WC_Payment_Token_CC();
//     $token->set_token( '000000g0000' );
//     $token->set_last4( '4124' );
//     $token->set_expiry_year( '2017' );
//     $token->set_expiry_month( '1' ); // incorrect length
//     $token->set_card_type( 'visa' );
//     $token->set_gateway_id( 'yith-stripe' );
//     $token->set_user_id( get_current_user_id() );
//     $token->set_default( true );
//     $token->set_expiry_month( '01' );
//     $token->create(); // save to database


//     // $token = new WC_Payment_Token_eCheck();
//     // $token->set_token( 'token here' );
//     // $token->set_last4( '4123' );

//     // $token = WC_Payment_Tokens::get( 42 ); // Token 42 is a default token for user 3
//     // $token = WC_Payment_Tokens::get( 43 ); // Token 43 is user 3's token, but not default

//     // $token = new WC_Payment_Token_CC();
//     // // set last4, expiry year, month, and card type
//     // $token->create(); // save to database

//      wp_die();

//      // _billing_first_name : Customer
//      // _billing_email : customer_demo@gmail.com
//      // _billing_address_index : Customer Demo  Test address  Florida FL 82003 US
//      // _stripe_customer_id : cus_GifpDopNKUeZ4J
// }


/**
 * Edit my account menu order
 */
// add_filter ( 'woocommerce_account_menu_items', 'my_account_menu_order' );
// function my_account_menu_order() {
//     $menuOrder = array(
//         // 'dashboard'          => __( 'My Dashboard', 'woocommerce' ),
//         'my-home'          => __( 'My Home', 'woocommerce' ),
//         'orders'             => __( 'My Orders', 'woocommerce' ),
//         'make-appointment'   => __( 'Make New Appointment', 'woocommerce' ),
//         // 'downloads'          => __( 'Download', 'woocommerce' ),
//         'edit-address'       => __( 'Addresses', 'woocommerce' ),
//         'edit-account'      => __( 'Account Details', 'woocommerce' ),
//         'customer-logout'    => __( 'Logout', 'woocommerce' ),
//     );
//     return $menuOrder;
//  }

/**
 * Register new endpoints to use inside My Account page. N.B: Update permalinks after change
 */
// add_action( 'init', 'my_account_new_endpoints' );
// function my_account_new_endpoints() {
//     add_rewrite_endpoint( 'my-home', EP_PAGES );
//     add_rewrite_endpoint( 'make-appointment', EP_PAGES );
// }

/**
 * Get new endpoint content
 */
// add_action( 'woocommerce_account_my-home_endpoint', 'my_home_endpoint_content' );
// function my_home_endpoint_content() {

//     include_once TRAINING_INSTRUCTOR_APPOINTMENT_PLUGIN_DIR . "/customers/dashboard.php";

// }

/**
 * Get new endpoint content
 */
// add_action( 'woocommerce_account_make-appointment_endpoint', 'make_appointment_endpoint_content' );
// function make_appointment_endpoint_content() {
//     echo "Content Comes Here Also";
// }

/**
 * Process Form Submission and credit management
 */
add_action('woocommerce_payment_complete', 'purchase_complete_handle');
function purchase_complete_handle($order_id)
{

    error_log("*********** woocommerce_payment_complete *************");


    if (!$order_id)
        return;

    global $wpdb;
    $the_order = wc_get_order($order_id);


    $customer_id = $the_order->get_customer_id();
    // $customer_id = $the_order->get_user_id();
    error_log("customer_id: " . $customer_id);
    $onecheck = 0;
    $order_items = $the_order->get_items();
    error_log("**** order_items : ");
    error_log(print_r($order_items, TRUE));
    foreach ($order_items as $order_item) {
        $gravity_forms_history = null;
        $entry_id = false;

        $meta_data = $order_item->get_meta_data();
        error_log("**** meta_data : ");
        error_log(print_r($meta_data, TRUE));
        if (WC_GFPA_Compatibility::is_wc_version_gte_3_2()) {
            foreach ($meta_data as $meta_data_item) {
                $d = $meta_data_item->get_data();
                if ($d['key'] == '_gravity_forms_history') {
                    $gravity_forms_history = array($meta_data_item);
                    break;
                }
            }
        } else {
            $gravity_forms_history = wp_list_filter($meta_data, array('key' => '_gravity_forms_history'));
        }

        error_log("**** gravity_forms_history : ");
        error_log(print_r($gravity_forms_history, TRUE));

        if ($gravity_forms_history) {
            $gravity_forms_history_value = array_pop($gravity_forms_history);
            $entry_id = isset($gravity_forms_history_value->value['_gravity_form_linked_entry_id']) && !empty($gravity_forms_history_value->value['_gravity_form_linked_entry_id']) ?
                $gravity_forms_history_value->value['_gravity_form_linked_entry_id'] : false;

            $entry = GFAPI::get_entry($entry_id);

            if ($entry_id && !is_wp_error($entry_id)) {

                $form_id = $entry['form_id'];
                error_log("form_id: " . $form_id);
                // Restrict only 3 gravity forms
                if (in_array($form_id, [GF_GROUP_FORM_ID, GF_INDIVIDUAL_FORM_ID, GF_UNLIMITED_FORM_ID])) {

                    // error_log("**** entry_id : " . $entry_id);
                    // error_log("**** form_id : " . $form_id);

                    // $form = GFFormsModel::get_form_meta( $form_id );
                    $planHiddenName = rgar($entry, '9');
                    $planData = rgar($entry, '1');
                    $sanitizedPlanData = explode(chr(1), str_replace(array(' ', '|'), chr(1), $planData));

                    $credits = NULL;
                    $expiry = NULL;
                    $billable = 0;
                    $unlimited_type = NULL;
                    $today = date("Y-m-d");

                    if ($planHiddenName == 'unlimited') {
                        // $billable = 0;
                        $expiry = date("Y-m-d", strtotime($today . " +1 month"));
                        $unlimited_type = strtolower($sanitizedPlanData[0]);
                    } else if (in_array($planHiddenName, ['group', 'individual'])) {
                        $credits = (int)$sanitizedPlanData[0] * $order_item->get_quantity();
                        global $woocommerce;
                        $items = $woocommerce->cart->get_cart();
                        error_log("*********** count_of_items *************" . count($items));
                        // foreach($items as $item) {
                        // error_log("*********** _gravity_form_lead *************".$item['_gravity_form_lead'][9]);
                        // if( in_array('_gravity_form_lead', $item) ){
                        // $pieces = explode(" ", $item['_gravity_form_lead'][1]);
                        // error_log("*********** count_of_pieces *************".$pieces[0]);
                        $queryCheck = "SELECT id,start_credits FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id AND order_id != $order_id  GROUP BY order_id  ORDER BY id DESC";
                        $dataCheck = $wpdb->get_results($queryCheck, ARRAY_A);
                        if ($onecheck == 0) {
                            if (count($dataCheck) == 1) {
                                $queryData = "SELECT id,start_credits,order_id,package_hidden_name FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id ORDER BY id DESC";
                                $dataList = $wpdb->get_results($queryData, ARRAY_A);
                                $check = 0;
                                $checkValue = 0;
                                foreach ($dataList as $listData) {
                                    if ($order_id != $listData['order_id']) {
                                        error_log("*********** reached here21 *************" . $credits);
                                        if (($listData['start_credits'] == 1) && (int)$credits != 1) {
                                            error_log("*********** reached here28 *************" . $credits);

                                            $check = 1;
                                            $checkValue = (int)$checkValue + 1;
                                            $onecheck = 1;
                                        } else {
                                            $check = 0;
                                            $checkValue = 0;
                                        }
                                        if ($listData['start_credits'] > 1) {
                                            $check = 0;
                                            $checkValue = 0;
                                            break;
                                        }
                                    }
                                }
                                if ($check == 1) {
                                    error_log("*********** reached here13 *************" . $listData['package_hidden_name']);
                                    error_log("*********** reached here20 *************" . $credits);
                                    if (($credits  == 5) || ($credits  == 10)) {
                                        error_log("*********** reached here14 *************" . $credits);
                                        $credits = (int)$credits - (int)$checkValue;
                                    }
                                }
                            }
                        }
                        // }
                        error_log("*********** reached here3 *************" . $check);
                        error_log("*********** reached here10 *************" . $listData['package_hidden_name']);


                        // }
                    }
                    $customer_purchase_amt = $the_order->get_total();
                    error_log("*********** reached here2 *************");
                    $args = array(
                        "customer_id" => $customer_id,
                        "order_id" => (int)$order_id,
                        "gf_form_id" => (int)$form_id,
                        "gform_entry_id" => (int)$entry_id,
                        "package_hidden_name" => $planHiddenName,
                        "credits" => $credits,
                        "start_credits" => $credits,
                        "is_unlimited_type" => $unlimited_type,
                        "expiry" => $expiry
                    );

                    $query = "SELECT COUNT(customer_id) FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id";
                    $data = $wpdb->get_row($query, ARRAY_A);
                    if ($credits == 1 && $data['COUNT(customer_id)'] == 0) {
                        $args["customer_purchase_amt"] = $customer_purchase_amt;
                    }
                    $sqlInsert = $wpdb->insert(DB_WC_GF_CUSTOMER_PURCHASES, $args);
                    $purchase_id = $wpdb->insert_id;
                    //---------------------mail--------------------------
                    $current_user_id = $customer_id;
                    $query = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $current_user_id  ORDER BY id ASC";
                    $purchases = $wpdb->get_results($query, ARRAY_A);
                    //  if (count($purchases) == 1) {
                    //      $email_user = $wpdb->get_row("SELECT * FROM ".DB_EMAILS." WHERE id = 52", ARRAY_A);
                    //              $user = $wpdb->get_row("SELECT * FROM ".DB_USERS." WHERE ID = $current_user_id", ARRAY_A);
                    //              $cust_email = $user['user_email'];
                    //              $cust_msg = $email_user['body'];
                    //              $cust_subject = $email_user['subject'];
                    //              /* Customer */
                    //              preg_match_all('/{(.*?)}/', $cust_msg, $matches);
                    //              if(in_array("customer_name", $matches[1])){
                    //                  $cust_msg = str_replace('{customer_name}',$user['display_name'],$cust_msg);
                    //              }

                    //              $headers[] = 'Content-Type: text/html; charset=UTF-8';
                    //              $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
                    //              $headers[] = 'Cc: shootinschool@gmail.com';
                    //              if($email_user['notify_via_email']==1){
                    //                  try {
                    //                      //code...
                    //                      wp_mail($cust_email, $cust_subject, $cust_msg, $headers);

                    //                  } catch (Exception $th) {
                    //                      //throw $th;
                    //                  }
                    //              }

                    //  }
                    //---------------------mail--------------------------
                    // Manage Recurring Subscription for Unlimited Packages

                    if(rgar( $entry, '9' ) == "unlimited"){
                        $recurring_amt = rgar( $entry, '2' );
                       }
                        if($planHiddenName == 'unlimited'){
                            $args = array(
                                "customer_purchase_id" => $wpdb->insert_id,
                                "next_payment_charging_amount" => (int)$recurring_amt
                            );
                    // if ($planHiddenName == 'unlimited') {
                    //     $args = array(
                    //         "customer_purchase_id" => $wpdb->insert_id,
                    //         "next_payment_charging_amount" => (int)$customer_purchase_amt
                    //     );
                        $sqlInsert = $wpdb->insert(DB_WC_GF_CUSTOMER_PURCHASES_RECURRING, $args);
                        // $first_name = rgar($entry, '8.3');
                        // $last_name = rgar($entry, '8.6');

                        $child_option = rgar($entry, '15');
                        if($child_option=='Create a Child')
                        {
                            $first_name = rgar($entry, '8.3');
                            $last_name = rgar($entry, '8.6');
                            $args = array(
                                "user_id" => $customer_id,
                                "first_name" => $first_name,
                                "last_name" => $last_name,
                                "grade" => rgar($entry, '5'),
                                "jersey_size" => rgar($entry, '7'),
                                "child_type" => $planHiddenName,
                                "purchase_id" => $purchase_id,
                                "school_name" => rgar($entry, '12'),
                                "child_dob" => rgar($entry, '16'),
                                "profile_image" => rgar($entry, '13')
                            );
                            $sqlInsert = $wpdb->insert(DB_CHILD_DETAILS, $args);
                        }
                        else
                        {
                            $childid = rgar($entry, '14');
                            $query = $wpdb->prepare(
                                "SELECT * FROM " . DB_CHILD_DETAILS . " WHERE id = %d",
                                $childid
                            );
                            $data = $wpdb->get_row($query);
                            if (is_null($data)) {
                                $first_name = rgar($entry, '8.3');
                                $last_name = rgar($entry, '8.6');
                                $args = array(
                                    "user_id" => $customer_id,
                                    "first_name" => $first_name,
                                    "last_name" => $last_name,
                                    "grade" => rgar($entry, '5'),
                                    "jersey_size" => rgar($entry, '7'),
                                    "child_type" => $planHiddenName,
                                    "purchase_id" => $purchase_id,
                                    "school_name" => rgar($entry, '12'),
                                    "child_dob" => rgar($entry, '16'),
                                    "profile_image" => rgar($entry, '13')
                                );
                                $sqlInsert = $wpdb->insert(DB_CHILD_DETAILS, $args);
                            }
                            else
                            {
                            $args = array(
                                "user_id" => $customer_id,
                                "grade" => rgar($entry, '5'),
                                "jersey_size" => rgar($entry, '7'),
                                "child_type" => $planHiddenName,
                                "purchase_id" => $purchase_id,
                                "school_name" => rgar($entry, '12'),
                                "child_dob" => rgar($entry, '16'),
                                "profile_image" => rgar($entry, '13')
                            );
                            $a = $wpdb->update(DB_CHILD_DETAILS, $args, array('id' => $childid));
                        }
                            // $name_parts = explode(' ', $full_name);
                            // $first_name = isset($name_parts[0]) ? $name_parts[0] : '';
                            // $last_name = isset($name_parts[1]) ? implode(' ', array_slice($name_parts, 1)) : '';
                        }

                        $query = "SELECT id FROM " . DB_CHILD_DETAILS . " WHERE user_id = '$customer_id' AND LOWER(first_name) = LOWER('$first_name') AND LOWER(last_name) = LOWER('$last_name')";
                        $data = $wpdb->get_row($query);
                        $query2 = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE order_id=" . (int)$order_id;


                        $myCredit = $wpdb->get_row($query2);



                        //if($wpdb->num_rows == 0){
                        // $args = array(
                        //     "user_id" => $customer_id,
                        //     "first_name" => $first_name,
                        //     "last_name" => $last_name,
                        //     "grade" => rgar($entry, '5'),
                        //     "jersey_size" => rgar($entry, '7'),
                        //     "child_type" => $planHiddenName,
                        //     "purchase_id" => $purchase_id,
                        //     "school_name" => rgar($entry, '12'),
                        //     "child_dob" => rgar($entry, '16'),
                        //     "profile_image" => rgar($entry, '13')

                        // );
                        // $sqlInsert = $wpdb->insert(DB_CHILD_DETAILS, $args);
                        //}
                    } else {
                        // Add Child Details
                        $child_option = rgar($entry, '15');
                        if($child_option=='Create a Child')
                        {
                            $first_name = rgar($entry, '8.3');
                            $last_name = rgar($entry, '8.6');
                            $args = array(
                                "user_id" => $customer_id,
                                "first_name" => $first_name,
                                "last_name" => $last_name,
                                "grade" => rgar($entry, '5'),
                                "jersey_size" => rgar($entry, '7'),
                                "child_type" => $planHiddenName,
                                "purchase_id" => $purchase_id,
                                "school_name" => rgar($entry, '12'),
                                "child_dob" => rgar($entry, '16'),
                                "profile_image" => rgar($entry, '13')
                            );
                            $sqlInsert = $wpdb->insert(DB_CHILD_DETAILS, $args);
                        }
                        else
                        {
                            $childid = rgar($entry, '14');
                            $query = $wpdb->prepare(
                                "SELECT * FROM " . DB_CHILD_DETAILS . " WHERE id = %d",
                                $childid
                            );
                            $data = $wpdb->get_row($query);
                            if (is_null($data)) {
                                $first_name = rgar($entry, '8.3');
                                $last_name = rgar($entry, '8.6');
                                $args = array(
                                    "user_id" => $customer_id,
                                    "first_name" => $first_name,
                                    "last_name" => $last_name,
                                    "grade" => rgar($entry, '5'),
                                    "jersey_size" => rgar($entry, '7'),
                                    "child_type" => $planHiddenName,
                                    "purchase_id" => $purchase_id,
                                    "school_name" => rgar($entry, '12'),
                                    "child_dob" => rgar($entry, '16'),
                                    "profile_image" => rgar($entry, '13')
                                );
                                $sqlInsert = $wpdb->insert(DB_CHILD_DETAILS, $args);
                            }
                            else
                            {
                            $args = array(
                                "user_id" => $customer_id,
                                "grade" => rgar($entry, '5'),
                                "jersey_size" => rgar($entry, '7'),
                                "child_type" => $planHiddenName,
                                "purchase_id" => $purchase_id,
                                "school_name" => rgar($entry, '12'),
                                "child_dob" => rgar($entry, '16'),
                                "profile_image" => rgar($entry, '13')
                            );
                            $a = $wpdb->update(DB_CHILD_DETAILS, $args, array('id' => $childid));
                        }
                            // $name_parts = explode(' ', $full_name);
                            // $first_name = isset($name_parts[0]) ? $name_parts[0] : '';
                            // $last_name = isset($name_parts[1]) ? implode(' ', array_slice($name_parts, 1)) : '';
                        }
                        $query = "SELECT id FROM " . DB_CHILD_DETAILS . " WHERE user_id = '$customer_id' AND LOWER(first_name) = LOWER('$first_name') AND LOWER(last_name) = LOWER('$last_name')";
                        $data = $wpdb->get_row($query);

                        $query2 = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE order_id=" . (int)$order_id;

                        error_log("*********** reached here11 *************" . $listData['package_hidden_name']);
                        $myCredit = $wpdb->get_row($query2);

                        //if($wpdb->num_rows == 0){
                        
                        //}
                    }
                } else if ($form_id == GF_TEAM_FORM_ID) { // Team Instruction

                    // error_log("************** GF_TEAM_FORM_ID : Team Instruction **************");

                    // Handle Dynamic Package Assigning
                    $planHiddenName = rgar($entry, '9');
                    $credits = $order_item->get_quantity();
                    $unlimited_type = NULL;
                    $expiry = NULL;

                    $query2 = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE order_id=" . (int)$order_id;


                    $myCredit = $wpdb->get_row($query2);

                    // $queryCheck = "SELECT id,credits FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id GROUP BY order_id  ORDER BY id DESC";
                    // $dataCheck = $wpdb->get_results($queryCheck, ARRAY_A);
                    // $query = "SELECT id,credits FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id GROUP BY order_id ORDER BY id DESC LIMIT 1";
                    // $data2 = $wpdb->get_row($query, ARRAY_A);
                    // if(count($dataCheck) == 1){
                    //     $queryData = "SELECT id,credits FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id ORDER BY id DESC";
                    //     $dataList = $wpdb->get_results($queryData, ARRAY_A);
                    //     foreach($dataList as $listData){
                    //         if($credits  != 1){

                    //             $credits = (int)$credits-1;
                    //         }
                    //     }

                    // }
                    // error_log("*********** reached here1 *************");
                    error_log("*********** reached here12 *************" . $listData['package_hidden_name']);
                    $args = array(
                        "customer_id1" => $customer_id,
                        "order_id" => (int)$order_id,
                        "gf_form_id" => (int)$form_id,
                        "gform_entry_id" => (int)$entry_id,
                        "package_hidden_name" => $planHiddenName,
                        "credits" => $credits,
                        "start_credits" => $credits,
                        "is_unlimited_type" => $unlimited_type,
                        "expiry" => $expiry
                    );
                    $sqlInsert = $wpdb->insert(DB_WC_GF_CUSTOMER_PURCHASES, $args);
                    //---------------------mail--------------------------
                    $current_user_id = $customer_id;
                    $query = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $current_user_id  ORDER BY id ASC";
                    $purchases = $wpdb->get_results($query, ARRAY_A);
                    //  if (count($purchases) == 1) {
                    //      $email_user = $wpdb->get_row("SELECT * FROM ".DB_EMAILS." WHERE id = 52", ARRAY_A);
                    //              $user = $wpdb->get_row("SELECT * FROM ".DB_USERS." WHERE ID = $current_user_id", ARRAY_A);
                    //              $cust_email = $user['user_email'];
                    //              $cust_msg = $email_user['body'];
                    //              $cust_subject = $email_user['subject'];
                    //              /* Customer */
                    //              preg_match_all('/{(.*?)}/', $cust_msg, $matches);
                    //              if(in_array("customer_name", $matches[1])){
                    //                  $cust_msg = str_replace('{customer_name}',$user['display_name'],$cust_msg);
                    //              }

                    //              $headers[] = 'Content-Type: text/html; charset=UTF-8';
                    //              $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
                    //              $headers[] = 'Cc: shootinschool@gmail.com';
                    //              if($email_user['notify_via_email']==1){
                    //                  try {
                    //                      //code...
                    //                      wp_mail($cust_email, $cust_subject, $cust_msg, $headers);

                    //                  } catch (Exception $th) {
                    //                      //throw $th;
                    //                  }
                    //              }

                    //  }
                    //---------------------mail--------------------------
                }

                $order = new WC_Order($order_id);

                if (!empty($order)) {
                    $order->update_status('completed');
                }
            }
        }
    }
}
// add_action( 'woocommerce_new_order', 'bwc_new_order' );
// function bwc_new_order($order_id) {
//     $order = new WC_Order($order_id);

//     if (!empty($order)) {
//         $order->update_status( 'completed' );
//     }
// }
// function after_order_placed( $order ) {


//     error_log("**** order_items3 : ");
//     error_log(print_r($order->get_items(), TRUE));
   

// }
// add_action( 'woocommerce_checkout_order_created', 'after_order_placed' );


// add_action('woocommerce_new_order', 'bwc_new_order_complete');
// function bwc_new_order_complete($order_id)
// {
    // sleep(30);
    // global $wpdb;
    // error_log("*********** woocommerce_payment_complete *************");
    // $table_name = "wp_4s71kwx95x_ferdaratedData";

    // // $data = array(
    // //     'bwcpid' => 1,
    // //     'shootpid' => 2,
    // //     'bwcgfid' => 3,
    // //     'shootgfid' => $order_id,
    // //     'test' => 'value5'
    // // );

    // // $wpdb->insert($table_name, $data);
    // if (!$order_id)
    //     return;

    // // global $wpdb;
    // // $the_order = wc_get_order($order_id);
    // $the_order = new WC_Order($order_id);

    // $customer_id = $the_order->get_customer_id();
    // // $customer_id = $the_order->get_user_id();
    // // $data = array(
    // //     'bwcpid' => 1,
    // //     'shootpid' => 2,
    // //     'bwcgfid' => 3,
    // //     'shootgfid' => $customer_id,
    // //     'test' => 'value5'
    // // );

    // // $wpdb->insert($table_name, $data);
    // error_log("customer_id: " . $customer_id);
    // $onecheck = 0;
    // // $order_items = $the_order->get_items();
    // $order_items = array_map(function ($order_items) {
    //     return $order_items->get_data();
    // }, $the_order->get_items());
    // error_log("**** order_items2 : ");
    // error_log(print_r($order_items, TRUE));
    // foreach ($order_items as $order_item) {
    //     $gravity_forms_history = null;
    //     $entry_id = false;

    //     $meta_data = $order_item->get_meta_data();
    //     error_log("**** meta_data : ");
    //     error_log(print_r($meta_data, TRUE));
    //     if (WC_GFPA_Compatibility::is_wc_version_gte_3_2()) {
    //         foreach ($meta_data as $meta_data_item) {
    //             $d = $meta_data_item->get_data();
    //             if ($d['key'] == '_gravity_forms_history') {
    //                 $gravity_forms_history = array($meta_data_item);
    //                 break;
    //             }
    //         }
    //     } else {
    //         $gravity_forms_history = wp_list_filter($meta_data, array('key' => '_gravity_forms_history'));
    //     }

    //     // error_log("**** gravity_forms_history : ");
    //     // error_log( print_r($gravity_forms_history, TRUE) );

    //     if ($gravity_forms_history) {
    //         $gravity_forms_history_value = array_pop($gravity_forms_history);
    //         $entry_id = isset($gravity_forms_history_value->value['_gravity_form_linked_entry_id']) && !empty($gravity_forms_history_value->value['_gravity_form_linked_entry_id']) ?
    //             $gravity_forms_history_value->value['_gravity_form_linked_entry_id'] : false;

    //         $entry = GFAPI::get_entry($entry_id);

    //         if ($entry_id && !is_wp_error($entry_id)) {

    //             $form_id = $entry['form_id'];
    //             $table_name = "wp_4s71kwx95x_ferdaratedData";
    //             $data = array(
    //                 'bwcpid' => 1,
    //                 'shootpid' => 2,
    //                 'bwcgfid' => 3,
    //                 'shootgfid' => $form_id,
    //                 'test' => 'formid'
    //             );

    //             $wpdb->insert($table_name, $data);
    //             // Restrict only 3 gravity forms
    //             if (in_array($form_id, [GF_GROUP_FORM_ID, GF_INDIVIDUAL_FORM_ID, GF_UNLIMITED_FORM_ID])) {

    //                 // error_log("**** entry_id : " . $entry_id);
    //                 // error_log("**** form_id : " . $form_id);

    //                 // $form = GFFormsModel::get_form_meta( $form_id );
    //                 $planHiddenName = rgar($entry, '9');
    //                 $planData = rgar($entry, '1');
    //                 $sanitizedPlanData = explode(chr(1), str_replace(array(' ', '|'), chr(1), $planData));

    //                 $credits = NULL;
    //                 $expiry = NULL;
    //                 $billable = 0;
    //                 $unlimited_type = NULL;
    //                 $today = date("Y-m-d");

    //                 if ($planHiddenName == 'unlimited') {
    //                     // $billable = 0;
    //                     $expiry = date("Y-m-d", strtotime($today . " +1 month"));
    //                     $unlimited_type = strtolower($sanitizedPlanData[0]);
    //                 } else if (in_array($planHiddenName, ['group', 'individual'])) {
    //                     $credits = (int)$sanitizedPlanData[0] * $order_item->get_quantity();
    //                     global $woocommerce;
    //                     $items = $woocommerce->cart->get_cart();
    //                     error_log("*********** count_of_items *************" . count($items));
    //                     // foreach($items as $item) {
    //                     // error_log("*********** _gravity_form_lead *************".$item['_gravity_form_lead'][9]);
    //                     // if( in_array('_gravity_form_lead', $item) ){
    //                     // $pieces = explode(" ", $item['_gravity_form_lead'][1]);
    //                     // error_log("*********** count_of_pieces *************".$pieces[0]);
    //                     $queryCheck = "SELECT id,start_credits FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id AND order_id != $order_id  GROUP BY order_id  ORDER BY id DESC";
    //                     $dataCheck = $wpdb->get_results($queryCheck, ARRAY_A);
    //                     if ($onecheck == 0) {
    //                         if (count($dataCheck) == 1) {
    //                             $queryData = "SELECT id,start_credits,order_id,package_hidden_name FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id ORDER BY id DESC";
    //                             $dataList = $wpdb->get_results($queryData, ARRAY_A);
    //                             $check = 0;
    //                             $checkValue = 0;
    //                             foreach ($dataList as $listData) {
    //                                 if ($order_id != $listData['order_id']) {
    //                                     error_log("*********** reached here21 *************" . $credits);
    //                                     if (($listData['start_credits'] == 1) && (int)$credits != 1) {
    //                                         error_log("*********** reached here28 *************" . $credits);

    //                                         $check = 1;
    //                                         $checkValue = (int)$checkValue + 1;
    //                                         $onecheck = 1;
    //                                     } else {
    //                                         $check = 0;
    //                                         $checkValue = 0;
    //                                     }
    //                                     if ($listData['start_credits'] > 1) {
    //                                         $check = 0;
    //                                         $checkValue = 0;
    //                                         break;
    //                                     }
    //                                 }
    //                             }
    //                             if ($check == 1) {
    //                                 error_log("*********** reached here13 *************" . $listData['package_hidden_name']);
    //                                 error_log("*********** reached here20 *************" . $credits);
    //                                 if (($credits  == 5) || ($credits  == 10)) {
    //                                     error_log("*********** reached here14 *************" . $credits);
    //                                     $credits = (int)$credits - (int)$checkValue;
    //                                 }
    //                             }
    //                         }
    //                     }
    //                     // }
    //                     error_log("*********** reached here3 *************" . $check);
    //                     error_log("*********** reached here10 *************" . $listData['package_hidden_name']);


    //                     // }
    //                 }
    //                 $customer_purchase_amt = $the_order->get_total();
    //                 error_log("*********** reached here2 *************");
    //                 $args = array(
    //                     "customer_id" => $customer_id,
    //                     "order_id" => (int)$order_id,
    //                     "gf_form_id" => (int)$form_id,
    //                     "gform_entry_id" => (int)$entry_id,
    //                     "package_hidden_name" => $planHiddenName,
    //                     "credits" => $credits,
    //                     "start_credits" => $credits,
    //                     "is_unlimited_type" => $unlimited_type,
    //                     "expiry" => $expiry
    //                 );

    //                 $query = "SELECT COUNT(customer_id) FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id";
    //                 $data = $wpdb->get_row($query, ARRAY_A);
    //                 if ($credits == 1 && $data['COUNT(customer_id)'] == 0) {
    //                     $args["customer_purchase_amt"] = $customer_purchase_amt;
    //                 }
    //                 $sqlInsert = $wpdb->insert(DB_WC_GF_CUSTOMER_PURCHASES, $args);
    //                 $purchase_id = $wpdb->insert_id;
    //                 //---------------------mail--------------------------
    //                 $current_user_id = $customer_id;
    //                 $query = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $current_user_id  ORDER BY id ASC";
    //                 $purchases = $wpdb->get_results($query, ARRAY_A);
    //                 //  if (count($purchases) == 1) {
    //                 //      $email_user = $wpdb->get_row("SELECT * FROM ".DB_EMAILS." WHERE id = 52", ARRAY_A);
    //                 //              $user = $wpdb->get_row("SELECT * FROM ".DB_USERS." WHERE ID = $current_user_id", ARRAY_A);
    //                 //              $cust_email = $user['user_email'];
    //                 //              $cust_msg = $email_user['body'];
    //                 //              $cust_subject = $email_user['subject'];
    //                 //              /* Customer */
    //                 //              preg_match_all('/{(.*?)}/', $cust_msg, $matches);
    //                 //              if(in_array("customer_name", $matches[1])){
    //                 //                  $cust_msg = str_replace('{customer_name}',$user['display_name'],$cust_msg);
    //                 //              }

    //                 //              $headers[] = 'Content-Type: text/html; charset=UTF-8';
    //                 //              $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
    //                 //              $headers[] = 'Cc: shootinschool@gmail.com';
    //                 //              if($email_user['notify_via_email']==1){
    //                 //                  try {
    //                 //                      //code...
    //                 //                      wp_mail($cust_email, $cust_subject, $cust_msg, $headers);

    //                 //                  } catch (Exception $th) {
    //                 //                      //throw $th;
    //                 //                  }
    //                 //              }

    //                 //  }
    //                 //---------------------mail--------------------------
    //                 // Manage Recurring Subscription for Unlimited Packages

    //                 if ($planHiddenName == 'unlimited') {
    //                     $args = array(
    //                         "customer_purchase_id" => $wpdb->insert_id,
    //                         "next_payment_charging_amount" => (int)$customer_purchase_amt
    //                     );
    //                     $sqlInsert = $wpdb->insert(DB_WC_GF_CUSTOMER_PURCHASES_RECURRING, $args);
    //                     $first_name = rgar($entry, '8.3');
    //                     $last_name = rgar($entry, '8.6');
    //                     $query = "SELECT id FROM " . DB_CHILD_DETAILS . " WHERE user_id = '$customer_id' AND LOWER(first_name) = LOWER('$first_name') AND LOWER(last_name) = LOWER('$last_name')";
    //                     $data = $wpdb->get_row($query);
    //                     $query2 = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE order_id=" . (int)$order_id;


    //                     $myCredit = $wpdb->get_row($query2);



    //                     //if($wpdb->num_rows == 0){
    //                     $args = array(
    //                         "user_id" => $customer_id,
    //                         "first_name" => $first_name,
    //                         "last_name" => $last_name,
    //                         "grade" => rgar($entry, '5'),
    //                         "jersey_size" => rgar($entry, '7'),
    //                         "child_type" => $planHiddenName,
    //                         "purchase_id" => $purchase_id,
    //                         "school_name" => rgar($entry, '12'),
    //                         "child_dob" => rgar($entry, '14'),
    //                         "profile_image" => rgar($entry, '13')

    //                     );
    //                     $sqlInsert = $wpdb->insert(DB_CHILD_DETAILS, $args);
    //                     //}
    //                 } else {
    //                     // Add Child Details
    //                     $first_name = rgar($entry, '8.3');
    //                     $last_name = rgar($entry, '8.6');
    //                     $query = "SELECT id FROM " . DB_CHILD_DETAILS . " WHERE user_id = '$customer_id' AND LOWER(first_name) = LOWER('$first_name') AND LOWER(last_name) = LOWER('$last_name')";
    //                     $data = $wpdb->get_row($query);

    //                     $query2 = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE order_id=" . (int)$order_id;

    //                     error_log("*********** reached here11 *************" . $listData['package_hidden_name']);
    //                     $myCredit = $wpdb->get_row($query2);

    //                     //if($wpdb->num_rows == 0){
    //                     $args = array(
    //                         "user_id" => $customer_id,
    //                         "first_name" => $first_name,
    //                         "last_name" => $last_name,
    //                         "grade" => rgar($entry, '5'),
    //                         "jersey_size" => rgar($entry, '7'),
    //                         "child_type" => $planHiddenName,
    //                         "purchase_id" => $purchase_id,
    //                         "school_name" => rgar($entry, '12'),
    //                         "child_dob" => rgar($entry, '14'),
    //                         "profile_image" => rgar($entry, '13')
    //                     );
    //                     $sqlInsert = $wpdb->insert(DB_CHILD_DETAILS, $args);
    //                     //}
    //                 }
    //             } else if ($form_id == GF_TEAM_FORM_ID) { // Team Instruction

    //                 // error_log("************** GF_TEAM_FORM_ID : Team Instruction **************");

    //                 // Handle Dynamic Package Assigning
    //                 $planHiddenName = rgar($entry, '9');
    //                 $credits = $order_item->get_quantity();
    //                 $unlimited_type = NULL;
    //                 $expiry = NULL;

    //                 $query2 = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE order_id=" . (int)$order_id;


    //                 $myCredit = $wpdb->get_row($query2);

    //                 // $queryCheck = "SELECT id,credits FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id GROUP BY order_id  ORDER BY id DESC";
    //                 // $dataCheck = $wpdb->get_results($queryCheck, ARRAY_A);
    //                 // $query = "SELECT id,credits FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id GROUP BY order_id ORDER BY id DESC LIMIT 1";
    //                 // $data2 = $wpdb->get_row($query, ARRAY_A);
    //                 // if(count($dataCheck) == 1){
    //                 //     $queryData = "SELECT id,credits FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id ORDER BY id DESC";
    //                 //     $dataList = $wpdb->get_results($queryData, ARRAY_A);
    //                 //     foreach($dataList as $listData){
    //                 //         if($credits  != 1){

    //                 //             $credits = (int)$credits-1;
    //                 //         }
    //                 //     }

    //                 // }
    //                 // error_log("*********** reached here1 *************");
    //                 // error_log("*********** reached here12 *************".$listData['package_hidden_name']);
    //                 $args = array(
    //                     "customer_id1" => $customer_id,
    //                     "order_id" => (int)$order_id,
    //                     "gf_form_id" => (int)$form_id,
    //                     "gform_entry_id" => (int)$entry_id,
    //                     "package_hidden_name" => $planHiddenName,
    //                     "credits" => $credits,
    //                     "start_credits" => $credits,
    //                     "is_unlimited_type" => $unlimited_type,
    //                     "expiry" => $expiry
    //                 );
    //                 $sqlInsert = $wpdb->insert(DB_WC_GF_CUSTOMER_PURCHASES, $args);
    //                 //---------------------mail--------------------------
    //                 $current_user_id = $customer_id;
    //                 $query = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $current_user_id  ORDER BY id ASC";
    //                 $purchases = $wpdb->get_results($query, ARRAY_A);
    //                 //  if (count($purchases) == 1) {
    //                 //      $email_user = $wpdb->get_row("SELECT * FROM ".DB_EMAILS." WHERE id = 52", ARRAY_A);
    //                 //              $user = $wpdb->get_row("SELECT * FROM ".DB_USERS." WHERE ID = $current_user_id", ARRAY_A);
    //                 //              $cust_email = $user['user_email'];
    //                 //              $cust_msg = $email_user['body'];
    //                 //              $cust_subject = $email_user['subject'];
    //                 //              /* Customer */
    //                 //              preg_match_all('/{(.*?)}/', $cust_msg, $matches);
    //                 //              if(in_array("customer_name", $matches[1])){
    //                 //                  $cust_msg = str_replace('{customer_name}',$user['display_name'],$cust_msg);
    //                 //              }

    //                 //              $headers[] = 'Content-Type: text/html; charset=UTF-8';
    //                 //              $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
    //                 //              $headers[] = 'Cc: shootinschool@gmail.com';
    //                 //              if($email_user['notify_via_email']==1){
    //                 //                  try {
    //                 //                      //code...
    //                 //                      wp_mail($cust_email, $cust_subject, $cust_msg, $headers);

    //                 //                  } catch (Exception $th) {
    //                 //                      //throw $th;
    //                 //                  }
    //                 //              }

    //                 //  }
    //                 //---------------------mail--------------------------
    //             }

    //             $order = new WC_Order($order_id);

    //             if (!empty($order)) {
    //                 $order->update_status('completed');
    //             }
    //         }
    //     }
    // }
// }

add_filter('default_checkout_billing_country', 'change_default_checkout_country');
function change_default_checkout_country()
{
    return 'US'; // country code for United States
}

// function getWC_order_details($order_id) {
// }
// add_action('woocommerce_after_register_post_type', 'getWC_order_details');


// new customer buys 1 session apply the cost of that 1 session towards their next purchase.
function woo_add_cart_fee()
{

    if (is_user_logged_in()) {
        global $wpdb;
        global $woocommerce;
        $customer_id = get_current_user_id();
        $query = "SELECT COUNT('customer_purchase_amt') as customer_purchase_count,customer_purchase_amt,package_hidden_name FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id GROUP BY order_id ";
        $data = $wpdb->get_row($query, ARRAY_A);
        $items = $woocommerce->cart->get_cart();
        error_log("*********** count_of_items *************" . count($items));
        foreach ($items as $item) {
            error_log("*********** _gravity_form_lead *************" . $item['_gravity_form_lead'][9]);
            if (in_array('_gravity_form_lead', $item)) {
                $pieces = explode(" ", $item['_gravity_form_lead'][1]);
                // if($data['package_hidden_name'] == $item['_gravity_form_lead'][9] && $pieces[0]!= 1 && $data['customer_purchase_count']<= 2){
                if (($data['package_hidden_name'] == 'individual' ||  $data['package_hidden_name'] == 'group') && ($pieces[0] != 1) && ($data['customer_purchase_count'] <= 10) && ($item['_gravity_form_lead'][9] == 'individual' ||  $item['_gravity_form_lead'][9] == 'group')) {



                    $queryCheck = "SELECT id,start_credits FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id GROUP BY order_id  ORDER BY id DESC";
                    $dataCheck = $wpdb->get_results($queryCheck, ARRAY_A);
                    $query = "SELECT id,start_credits FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id GROUP BY order_id ORDER BY id DESC LIMIT 1";
                    $data2 = $wpdb->get_row($query, ARRAY_A);
                    if (count($dataCheck) == 1) {
                        $queryData = "SELECT id,start_credits,order_id FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id ORDER BY id DESC";
                        $dataList = $wpdb->get_results($queryData, ARRAY_A);
                        $check = 0;
                        $checkValue = 0;
                        foreach ($dataList as $listData) {

                            if (($listData['start_credits'] == 1) && $pieces[0] != 1) {
                                $check = 1;
                                $checkValue = (int)$checkValue + 1;
                            } else {
                                $check = 0;
                                $checkValue = 0;
                            }
                            if ($listData['start_credits'] > 1) {
                                $check = 0;
                                break;
                            }
                        }
                        if ($check == 1) {
                            $woocommerce->cart->add_fee(__('Second Purchase Discount', 'woocommerce'), -$data['customer_purchase_amt']);
                        }
                        error_log("*********** reached here3 *************" . $check);
                    }
                }
            }
        }
    }
}
add_action('woocommerce_before_calculate_totals', 'woo_add_cart_fee');

// ************************ ADMIN MANUAL ORDER SECTION **************************************
add_filter('gform_submit_button', 'add_onclick', 10, 2);
function add_onclick($button, $form)
{

    $dom = new DOMDocument();
    $dom->loadHTML('<?xml encoding="utf-8" ?>' . $button);
    $input = $dom->getElementsByTagName('input')->item(0);
    $onclick = $input->getAttribute('onclick');

    $onclick .= " assignHiddenValue();";

    $input->setAttribute('onclick', $onclick);
    return $dom->saveHtml($input);
}

// Customize Gravity Form
// add_action( 'gform_pre_submission', 'pre_submission_handler' );
// function pre_submission_handler( $form ) {
//     // $_POST['input_14'] = rgpost( 'input_5' );
//     $_POST['input_10'] = '5|235';
// }

// function gf_make_submit_input_into_a_button_element($button_input, $form) {
//   //save attribute string to $button_match[1]
//   preg_match("/<input([^\/>]*)(\s\/)*>/", $button_input, $button_match);

//   //remove value attribute
//   $button_atts = str_replace("value='".$form['button']['text']."' ", "", $button_match[1]);

//   return '<button style="display:none;" '.$button_atts.'>'.$form['button']['text'].'<i class="fa fa-refresh"></i></button><button>Hoi</button>';
// }
// add_filter('gform_submit_button', 'gf_make_submit_input_into_a_button_element', 10, 2);

// // filter the Gravity Forms button type
// add_filter( 'gform_submit_button', 'form_submit_button', 10, 2 );
// function form_submit_button( $button, $form ) {
//     return "<button class='button' id='gform_submit_button_{$form['id']}'><span>Submit</span></button>";
// }

// Customize Gravity Form submission for admin assigned orders
add_action('gform_after_submission', 'gf_manual_assign_package', 10, 2);
function gf_manual_assign_package($entry, $form)
{

    if (!is_admin()) return; // Will work only from Admin Backed.

    global $wpdb;
    global $woocommerce;

    // error_log( print_r($entry, TRUE) );
    // error_log("*******");
    // error_log( print_r($form, TRUE) );

    $form_id = rgar($entry, 'form_id');

    // Check if Admin Manual Order submission OR Default Woocommerce submission
    if (in_array($form_id, [GF_GROUP_FORM_ID, GF_INDIVIDUAL_FORM_ID, GF_UNLIMITED_FORM_ID])) {

        $hidden_check = rgar($entry, '10');
        if ($hidden_check != 'woo_gf_sub') { // Default Woocommerce submission

            $arr = explode("|", $hidden_check);
            $product_id = $arr[0];
            $customer_id = $arr[1];
            $the_user = get_user_by('id', $customer_id);

            $address = array(
                'first_name' => get_user_meta($customer_id, 'shipping_first_name', true),
                'last_name'  => get_user_meta($customer_id, 'shipping_last_name', true),
                'company'    => get_user_meta($customer_id, 'shipping_company', true),
                'email'      => $the_user->user_email,
                'phone'      => get_user_meta($customer_id, 'billing_billing_phone', true),
                'address_1'  => get_user_meta($customer_id, 'shipping_address_1', true),
                'address_2'  => get_user_meta($customer_id, 'shipping_address_2', true),
                'city'       => get_user_meta($customer_id, 'shipping_city', true),
                'state'      => get_user_meta($customer_id, 'shipping_state', true),
                'postcode'   => get_user_meta($customer_id, 'shipping_postcode', true),
                'country'    => get_user_meta($customer_id, 'shipping_country', true),
            );

            $prices = array('totals' => array(
                'subtotal' => rgar($entry, '2'),
                'total' => rgar($entry, '2'),
            ));

            $order_data = array(
                'customer_id' => $customer_id

            );

            $the_order = wc_create_order($order_data);

            $the_order->add_product(wc_get_product($product_id), 1, $prices);
            $the_order->set_address($address, 'billing');
            $the_order->calculate_totals();
            $the_order->update_status("processing", 'Admin Manual Order', TRUE);

            $order_id = $the_order->get_id();

            $order_items = $the_order->get_items();
            $order_type = $the_order->get_type();
            $entry_id = $entry['id'];
            $childrens = '';
            foreach ($order_items as $order_item) {
                if ($entry_id && !is_wp_error($entry_id)) {

                    $entry = GFAPI::get_entry($entry_id);
                    if ($entry) {

                        do_action('gform_entry_created', $entry, $form);

                        $entry = gf_apply_filters(array('gform_entry_post_save', $form_id), $entry, $form);

                        GFAPI::update_entry($entry);

                        $user_id = $the_order->get_user_id() ? $the_order->get_user_id() : false;
                        if ($user_id) {
                            GFAPI::update_entry_property($entry_id, 'created_by', $user_id);
                        }

                        gform_update_meta($entry_id, 'woocommerce_order_number', $order_item->get_order_id(), $form_id);
                        gform_update_meta($entry_id, 'woocommerce_order_item_number', $order_item->get_id(), $form_id);

                        do_action('woocommerce_gravityforms_entry_created', $entry_id, $order_id, $order_item, $form, $entry);

                        // Update `woocommerce_order_itemmeta`
                        $fullName = rgar($entry, '8.3') . ' ' . rgar($entry, '8.6');
                        $formatted_total = '$' . number_format(rgar($entry, '2'), 2);
                        $metaArr = array(
                            ['Name', $fullName],
                            [GFFormsModel::get_field($form, 1)->label, rgar($entry, '1')],
                            [GFFormsModel::get_field($form, 5)->label, rgar($entry, '5')],
                            [GFFormsModel::get_field($form, 7)->label, rgar($entry, '7')],
                            [GFFormsModel::get_field($form, 2)->label, $formatted_total],
                        );

                        foreach ($metaArr as $single) {
                            $args = array(
                                "order_item_id" => $order_item->get_id(),
                                "meta_key" => $single[0],
                                "meta_value" => $single[1]
                            );

                            $wpdb->insert($wpdb->prefix . "woocommerce_order_itemmeta", $args);
                        }

                        // Handle Dynamic Package Assigning
                        $planData = rgar($entry, '1');
                        $sanitizedPlanData = explode(chr(1), str_replace(array(' ', '|'), chr(1), $planData));
                        $planHiddenName = rgar($entry, '9');

                        $credits = NULL;
                        $expiry = NULL;
                        $unlimited_type = NULL;
                        $today = date("Y-m-d");

                        if ($planHiddenName == 'unlimited') {
                            $expiry = date("Y-m-d", strtotime($today . " +1 month"));
                            $unlimited_type = strtolower($sanitizedPlanData[0]);
                        } else if (in_array($planHiddenName, ['group', 'individual'])) {
                            $credits = (int)$sanitizedPlanData[0];
                        }
                        $customer_purchase_amt = $the_order->get_total();

                        $args = array(
                            "customer_id" => $customer_id,
                            "order_id" => (int)$order_id,
                            "gf_form_id" => (int)$form_id,
                            "gform_entry_id" => (int)$entry_id,
                            "package_hidden_name" => $planHiddenName,
                            "credits" => $credits,
                            "start_credits" => $credits,
                            "is_unlimited_type" => $unlimited_type,
                            "expiry" => $expiry
                        );

                        $query = "SELECT COUNT(customer_id) FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id";
                        $data = $wpdb->get_row($query, ARRAY_A);
                        if ($credits == 1 && $data['COUNT(customer_id)'] == 0) {
                            $args["customer_purchase_amt"] = $customer_purchase_amt;
                        }
                        $sqlInsert = $wpdb->insert(DB_WC_GF_CUSTOMER_PURCHASES, $args);
                        //---------------------mail--------------------------
                        $current_user_id = $customer_id;
                        $query = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $current_user_id  ORDER BY id ASC";
                        $purchases = $wpdb->get_results($query, ARRAY_A);
                        // if (count($purchases) == 1) {
                        //     $email_user = $wpdb->get_row("SELECT * FROM ".DB_EMAILS." WHERE id = 52", ARRAY_A);
                        //             $user = $wpdb->get_row("SELECT * FROM ".DB_USERS." WHERE ID = $current_user_id", ARRAY_A);
                        //             $cust_email = $user['user_email'];
                        //             $cust_msg = $email_user['body'];
                        //             $cust_subject = $email_user['subject'];
                        //             /* Customer */
                        //             preg_match_all('/{(.*?)}/', $cust_msg, $matches);
                        //             if(in_array("customer_name", $matches[1])){
                        //                 $cust_msg = str_replace('{customer_name}',$user['display_name'],$cust_msg);
                        //             }

                        //             $headers[] = 'Content-Type: text/html; charset=UTF-8';
                        //             $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
                        //             $headers[] = 'Cc: shootinschool@gmail.com';
                        //             if($email_user['notify_via_email']==1){
                        //                 try {
                        //                     //code...
                        //                     wp_mail($cust_email, $cust_subject, $cust_msg, $headers);

                        //                 } catch (Exception $th) {
                        //                     //throw $th;
                        //                 }
                        //             }

                        // }
                        //---------------------mail--------------------------


                        $query2 = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE order_id=" . (int)$order_id;


                        $myCredit = $wpdb->get_row($query2);


                        // Manage Recurring Subscription for Unlimited Packages
                        if ($planHiddenName == 'unlimited') {
                            $args = array(
                                "user_id" => $customer_id,
                                "first_name" => rgar($entry, '8.3'),
                                "last_name" => rgar($entry, '8.6'),
                                "grade" => rgar($entry, '5'),
                                "jersey_size" => rgar($entry, '7'),
                                "child_type" => $planHiddenName,
                                'purchase_id' => $myCredit->id,
                                "school_name" => rgar($entry, '12'),
                                "child_dob" => rgar($entry, '14'),
                                "profile_image" => rgar($entry, '13')
                            );
                            $childrens .= $args['first_name'] . " " . $args['last_name'] . ",";
                            $sqlInsert = $wpdb->insert(DB_CHILD_DETAILS, $args);
                            // $args = array(
                            //     "customer_purchase_id" => $wpdb->insert_id,
                            //     "next_payment_charging_amount" => (int)$customer_purchase_amt
                            // );
                            // $sqlInsert = $wpdb->insert(DB_WC_GF_CUSTOMER_PURCHASES_RECURRING, $args);

                        } else {
                            // Add Child Details
                            $args = array(
                                "user_id" => $customer_id,
                                "first_name" => rgar($entry, '8.3'),
                                "last_name" => rgar($entry, '8.6'),
                                "grade" => rgar($entry, '5'),
                                "jersey_size" => rgar($entry, '7'),
                                "child_type" => $planHiddenName,
                                'purchase_id' => $myCredit->id,
                                "school_name" => rgar($entry, '12'),
                                "child_dob" => rgar($entry, '14'),
                                "profile_image" => rgar($entry, '13')
                            );
                            $childrens .= $args['first_name'] . " " . $args['last_name'] . ",";
                            $sqlInsert = $wpdb->insert(DB_CHILD_DETAILS, $args);
                        }
                    }
                }
            }

            // Payment Check
            $sel_payment = rgar($entry, '11');
            if ($sel_payment == "yes") {
                // already paid

            } else {
                // intimate check payment via email
                $email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 22", ARRAY_A);
                $user = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = $customer_id", ARRAY_A);
                $cust_email = $user['user_email'];
                $cust_msg = $email_user['body'];
                $cust_subject = $email_user['subject'];
                /* Customer */
                preg_match_all('/{(.*?)}/', $cust_msg, $matches);
                if (in_array("customer_name", $matches[1])) {
                    $cust_msg = str_replace('{customer_name}', $user['display_name'], $cust_msg);
                }
                if (in_array("order_id", $matches[1])) {
                    $cust_msg = str_replace('{order_id}', $order_id, $cust_msg);
                }
                if (in_array("charge", $matches[1])) {
                    $cust_msg = str_replace('{charge}', rgar($entry, '2'), $cust_msg);
                }
                if (in_array("children", $matches[1])) {
                    $cust_msg = str_replace('{children}', $childrens, $cust_msg);
                }
                if (in_array("credits", $matches[1])) {
                    if (isset($data['credits'])) {
                        $cust_msg = str_replace('{credits}', $data['credits'], $cust_msg);
                    } else {
                        $cust_msg = str_replace('{credits}', "NA", $cust_msg);
                    }
                }
                if (in_array("package_type", $matches[1])) {
                    if ($data['is_unlimited'] == 1) {
                        $package = "Unlimited Instruction";
                        if ($data['package_hidden_name'] == 'group') {
                            $package .= "(Group)";
                        } else if ($data['package_hidden_name'] == 'individual') {
                            $package .= "(Individual)";
                        }
                    } else {
                        if ($data['package_hidden_name'] == 'group') {
                            $package = "Group Instruction";
                        } else if ($data['package_hidden_name'] == 'individual') {
                            $package = "Individual Instruction";
                        }
                    }
                    $cust_msg = str_replace('{package_type}', $package, $cust_msg);
                }


                $headers[] = 'Content-Type: text/html; charset=UTF-8';
                $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
                $headers[] = 'Cc: shootinschool@gmail.com';
                if ($email_user['notify_via_email'] == 1) {
                    try {
                        //code...
                        wp_mail($cust_email, $cust_subject, $cust_msg, $headers);
                    } catch (Exception $th) {
                        //throw $th;
                    }
                }

                if ($email_user['notify_via_sms'] == 1) {
                    $cust_msg_sms = $cust_msg;
                    $cust_msg_sms = str_replace('<br>', "\n", $cust_msg_sms);
                    $cust_msg_sms = str_replace('&nbsp', " ", $cust_msg_sms);
                    preg_match_all('/<(.*?)>/', $cust_msg_sms, $sms_matches);
                    $phone = get_user_meta($customer_id, $key = 'billing_billing_phone');
                    if (count($phone) > 0) {
                        foreach ($sms_matches[0] as $match) {

                            if ($match == "</p>") {
                                $cust_msg_sms = str_replace($match, "\n", $cust_msg_sms);
                            } else {
                                $cust_msg_sms = str_replace($match, '', $cust_msg_sms);
                            }
                        }
                        // $args = array(
                        //     'number_to'=> fetchCountryMobileCode($customer_id) . $phone[0],
                        //     'message' => $cust_msg_sms
                        // );
                        // twl_send_sms( $args );
                        $phones = [];
                        if (!in_array($phone[0], $phones)) {

                            try {
                                $number = fetchCountryMobileCode($customer_id) . $phone[0];
                                // twl_send_sms($args);
                                $sid = TWILIO_ID;
                                $token = TWILIO_AUTH_TOKEN;
                                // In production, these should be environment variables. E.g.:
                                // $auth_token = $_ENV["TWILIO_AUTH_TOKEN"]

                                // A Twilio number you own with SMS capabilities
                                $twilio_number = TWILIO_NUMBER;
                                $twilio = new Client($sid, $token);

                                $message = $twilio->messages->create(
                                    $number,
                                    ["body" => $cust_msg_sms, "from" => $twilio_number]
                                );
                                array_push($phones, $phone[0]);
                            } catch (Exception $e) {
                                // die( $e->getCode() . ' : ' . $e->getMessage() );

                            }
                        }
                    }
                }
            }
            $order = new WC_Order($order_id);

            if (!empty($order)) {
                $order->update_status('completed');
            }
        }
    }
}