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/customers/add_appointment.php
<?php

require __DIR__ . '../../vendor/autoload.php';

use Twilio\Rest\Client;

add_action('wp_ajax_nopriv_get_locations_based_on_day', 'get_locations_based_on_day');
add_action('wp_ajax_get_locations_based_on_day', 'get_locations_based_on_day');
function get_locations_based_on_day()
{

    global $wpdb;
    if (date('w') == 0 || date('w') == 6) {
        if (get_option('scheduled_date') == date('Y-m-d')) {
        } else {
            echo json_encode(array("status" => FALSE, "message" => "No Location available on selected date", "message2" => 'Schedule for the week is not completed, please check after some time.'));
            die();
        }
    }
    if($_POST['customerID'] != 0){
        $isBwc = get_user_meta($_POST['customerID'], 'isBwc', true);
        
    }
    $date = date("Y-m-d", strtotime($_POST['date']));

    $package = explode("|", $_POST['package']);
    $package_id = $package[0];
    $myCredits = $wpdb->get_results("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE  id='$package_id'  and is_cancelled=0", ARRAY_A);
    foreach ($myCredits as $key => $myCredit) {

        if ($myCredit['is_unlimited_type']) {
            // if( strtotime($myCredit['expiry']) <= $current_date) continue;
            $session_name = $myCredit['is_unlimited_type'];
        } else {
            if ($myCredit['credits'] <= 0) continue;
            $session_name = $myCredit['package_hidden_name'];
        }
    }
    //$session_name = $myCredits['package_hidden_name'];
    $unixTimestamp = strtotime($date);

    //Get the day of the week using PHP's date function.
    $dayOfWeek = date("l", $unixTimestamp);
    $weekday = strtolower($dayOfWeek);
    $current_user = wp_get_current_user();

    if (user_can($current_user, 'administrator') ||  user_can($current_user, 'siab_sub_admin')) {
        //$locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS." WHERE  is_deleted = 0", ARRAY_A);
        //$locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS." WHERE  JSON_EXTRACT(`working_hours`, '$.tuesday.package') = 'both' AND is_deleted = 0", ARRAY_A);
        if ($isBwc == 1) {
            $locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE (JSON_EXTRACT(`working_hours`, '$." . $weekday . ".package')  = '" . $session_name . "' or JSON_EXTRACT(`working_hours`, '$." . $weekday . ".package')  = 'both') AND is_deleted = 0 AND (platform = 2 OR platform = 3)", ARRAY_A);
        }else{
            $locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE (JSON_EXTRACT(`working_hours`, '$." . $weekday . ".package')  = '" . $session_name . "' or JSON_EXTRACT(`working_hours`, '$." . $weekday . ".package')  = 'both') AND is_deleted = 0 AND (platform = 1 OR platform = 3)", ARRAY_A);
        }
     
    } else {
        //$locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS." WHERE status = 0 AND is_deleted = 0", ARRAY_A);
        $locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE (JSON_EXTRACT(`working_hours`, '$." . $weekday . ".package')  = '" . $session_name . "' or JSON_EXTRACT(`working_hours`, '$." . $weekday . ".package')  = 'both') AND is_deleted = 0 and status = 0 AND (platform = 1 OR platform = 3)", ARRAY_A);
    }

    $permittedLocs = array();
    foreach ($locations as $loc) {
        $working_hours = json_decode($loc['working_hours'], TRUE);
        if ($working_hours[$weekday]['open'] && $working_hours[$weekday]['close']) {
            $permittedLocs[] = array('id' => $loc['id'], "name" => $loc['name']);
        }
    }

    if (count($permittedLocs) > 0) {
        echo json_encode(['status' => TRUE, 'name' => $package, 'locations' => $permittedLocs]);
        die();
    } else {
        echo json_encode(['status' => FALSE, 'name' => $package, "message2" => '', 'message' => 'No Location available on selected date']);
        die();
    }
}


add_action('wp_ajax_nopriv_get_time_slots', 'get_time_slots');
add_action('wp_ajax_get_time_slots', 'get_time_slots');
// Get location, date and session type, and check for off days in all instructors, max capacity, and finally get list of all availabilities of instructors matching the criteria
function get_time_slots()
{

    global $wpdb;

    parse_str($_POST['form_data'], $form_data); //This will convert the string to array

    $location_id = $_POST['location_id'];
    $session_sel = explode('|', $_POST['session_sel']);
    $idsession_sel = $session_sel[0];
    $date = date("Y-m-d", strtotime($_POST['date']));

    $myCredits = $wpdb->get_row("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE id = '$idsession_sel'", ARRAY_A);
    $package = $myCredits['package_hidden_name'];

    //=============================================================================
    $currentDate = new DateTime('now', new DateTimeZone(DEFAULT_TIMEZONE)); // Get the current date
    $startOfWeek = (clone $currentDate)->modify('this week monday'); // Monday of this week
    $endOfWeek = (clone $startOfWeek)->modify('+6 days'); // Sunday of this week

    $selectedDate = new DateTime($date, new DateTimeZone(DEFAULT_TIMEZONE));

    // Check if the selected date falls within the current week (Monday to Sunday)
    if ($selectedDate < $startOfWeek || $selectedDate > $endOfWeek) {
        echo json_encode(['status' => FALSE, 'message' => 'Please select a date from the current week (Monday to Sunday).','validation'=>0]);
        wp_die(); // Stop further execution if validation fails
    }
    //=============================================================================

    $myCredits = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE id = '$idsession_sel'";
    $package_query = $wpdb->get_row($myCredits);
    $package = $package_query->package_hidden_name;
    $is_unlimited_type = $package_query->is_unlimited_type;

    // Convert the date string into a unix timestamp.
    $unixTimestamp = strtotime($date);

    //Get the day of the week using PHP's date function.
    $dayOfWeek = date("l", $unixTimestamp);
    $weekday = strtolower($dayOfWeek);

    // 1) Get timings of all coaching location on selected date and location
    $query = "SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id = '$location_id'";
    $location = $wpdb->get_row($query);
    //------------------------------------------------------------------------------------------------------------------
    $query = "SELECT * FROM " . DB_GRADE_LOCATIONS . " WHERE location_id = '$location_id' and day = '$dayOfWeek'";
    $grade_location = $wpdb->get_row($query);
    // $count = count($grade_location);
    // $gradehrsArr = json_decode($grade_location->grade_hours, TRUE);
    if ($grade_location) {
        // If there is a result
        $count = 1;
        $gradehrsArr = json_decode($grade_location->grade_hours, TRUE);
    } else {
        // If there is no result
        $count = 0;
        $gradehrsArr = [];  // Ensure $gradehrsArr is an empty array if no $grade_location
    }
    // echo $wpdb->last_query;
    //$gopen = $gradehrsArr[$weekday]['open'];
    //$gclose = $gradehrsArr[$weekday]['close'];

    $open_timing = array();
    $close_timing = array();

    $gopen_timing = array();
    $gclose_timing = array();
    $ggrade = array();

    $finalEndTimeArr = '-- Choose --';
    $finalStartTimeArr = '-- Choose --';
    $finalStartTimeArr = [];
    $finalEndTimeArr = [];
    $open_timing = []; // Initialize the open timing array
    $close_timing = []; // Initialize the close timing array
    $gopen_timing = [];
    $gclose_timing = [];
    $ggrade = [];

    $finalStartTimeArr = [];  // Initialize as an empty array
    $finalEndTimeArr = [];    // Initialize as an empty array
    if ($location) {
        $hrsArr = json_decode($location->working_hours, TRUE);
        if ($hrsArr) {
            $open = $hrsArr[$weekday]['open'];
            $close = $hrsArr[$weekday]['close'];
            $mainlabel =  $hrsArr[$weekday]['label'];
            $AddMins = 60 * 60;
        
            if ($open != "" && $close != "") {
                $openTime = strtotime($open);
                $closeTime = strtotime($close);
        
                while ($openTime <= $closeTime - $AddMins) {
                    array_push($open_timing, $openTime);
                    array_push($close_timing, ($openTime + $AddMins));
                    $openTime += $AddMins;
                }
        
                // Sort the open_timing and close_timing arrays
                // usort($open_timing, 'sortByTime');
                // usort($close_timing, 'sortByTime');
                sort($open_timing);
                 sort($close_timing);
            }
            $label="";
            foreach ($gradehrsArr as $day => $info) {
                $gopen = $info['open'];
                $gclose = $info['close'];
                $grade = $info['grade'];
                $label = $info['label'];
                $gopenTime = strtotime($gopen);
                $gcloseTime = strtotime($gclose);
        
                array_push($gopen_timing, $gopenTime);
                array_push($gclose_timing, ($gcloseTime));
                array_push($ggrade, $grade);
            }
            sort($gopen_timing);
            sort($gclose_timing);
            // usort($gopen_timing, 'sortByTime');
            // usort($gclose_timing, 'sortByTime');
            function getGradeByTimeopen($time, $timeRanges)
            {
                foreach ($timeRanges as $key => $range) {
                    $openTime = strtotime($range['open']);
                    $closeTime = strtotime($range['close']);
                    $currentTime = $time;

                    if ($currentTime >= $openTime && $currentTime < $closeTime) {
                        return $range['grade'];
                    }
                }
                return null; // Return null if no matching grade is found
            }
            function getGradeByTimeclose($time, $timeRanges)
            {
                foreach ($timeRanges as $key => $range) {
                    $openTime = strtotime($range['open']);
                    $closeTime = strtotime($range['close']);
                    $currentTime = $time;

                    if ($currentTime > $openTime && $currentTime <= $closeTime) {
                        return $range['grade'];
                    }
                }
                return null; // Return null if no matching grade is found
            }

            function getLabelByTimeopen($time, $timeRanges)
            {
                foreach ($timeRanges as $key => $range) {
                    $openTime = strtotime($range['open']);
                    $closeTime = strtotime($range['close']);
                    $currentTime = $time;

                    if ($currentTime >= $openTime && $currentTime < $closeTime) {
                        return $range['label'];
                    }
                }
                return null; // Return null if no matching grade is found
            }

            function getLabelByTimetimeclose($time, $timeRanges)
            {
                foreach ($timeRanges as $key => $range) {
                    $openTime = strtotime($range['open']);
                    $closeTime = strtotime($range['close']);
                    $currentTime = $time;

                    if ($currentTime > $openTime && $currentTime <= $closeTime) {
                        return $range['label'];
                    }
                }
                return null; // Return null if no matching grade is found
            }
            $timeRanges = $gradehrsArr;
            
        }
        foreach ($open_timing as $i => $openTime) {
            $t = date("g:i A", $openTime);
            $u = date("g:i A", $close_timing[$i]);
    
            $gradeIndex = array_search($openTime, $gopen_timing);
            $gr = 2;
            if (($package === 'group' || $is_unlimited_type == 'group') && $count > 0) {
                //if ($openTime >= $gopenTime && $openTime < $gcloseTime || ($gopen_timing[$i])) {
                if ($gopenTime && $gcloseTime || ($gopen_timing[$i])) {
                    $timeToFindGrade = $openTime;
                    $grade = getGradeByTimeopen($timeToFindGrade, $timeRanges);
                    $label = getLabelByTimeopen($timeToFindGrade, $timeRanges);
                    $data = $wpdb->get_row("SELECT * FROM " . DB_GRADE_SESSIONS . " WHERE ID = '" . $grade . "'");
                    $lower_grade = $data->lower_grade;
                    $upper_grade = $data->upper_grade;
                    if ($lower_grade) {
                        if ($upper_grade != '') {
                            if($label !=""){
                                $gradeText = ' (Grade ' . $lower_grade . '-' . $upper_grade . ')'. '('. $label .')';
                            }else{
                                $gradeText = ' (Grade ' . $lower_grade . '-' . $upper_grade . ')';
                            }
                            
                        } else {
                            if($label !=""){
                                $gradeText = ' (Grade ' . $lower_grade . ')' . '('. $label .')';
                            }else{
                                $gradeText = ' (Grade ' . $lower_grade . ')';
                            }
                            
                        }
                    } else {
                        $gradeText = '('. $mainlabel .')';
                    }
                } else {
                    $gradeText = '('. $mainlabel .')';
                }
    
                $finalStartTimeArr[] = '<option value="' . date("G:i", $openTime) . '">' . $t . $gradeText . '</option>';
            } else {
                if($mainlabel !=""){
                    $mainlabel2 = '('. $mainlabel .')';
                }else{
                    $mainlabel2 = "";
                }
                $finalStartTimeArr[] = '<option value="' . date("G:i", $openTime) . '">' . $t .$mainlabel2. ' </option>';
            }
            $gradeIndex = array_search($close_timing[$i], $gopen_timing); //array_search($close_timing[$i], $gclose_timing);
            if (($package === 'group' || $is_unlimited_type == 'group') && $count > 0) {
                if ($gopenTime &&  $gcloseTime || ($gclose_timing[$i])) {
                    $timeToFindGrade = $close_timing[$i];
                    $grade = getGradeByTimeclose($timeToFindGrade, $timeRanges);
                    $label = getLabelByTimetimeclose($timeToFindGrade, $timeRanges);
                    $data = $wpdb->get_row("select * from " . DB_GRADE_SESSIONS . " where ID = '" . $grade . "'");
                    $lower_grade = $data->lower_grade;
                    $upper_grade = $data->upper_grade;
                    if ($lower_grade) {
                        if ($upper_grade != '') {
                            if($label !=""){
                                $gradeText = ' (Grade ' . $lower_grade . '-' . $upper_grade . ')'. '('. $label .')';
                            }else{
                                $gradeText = ' (Grade ' . $lower_grade . '-' . $upper_grade . ')';
                            }
                            // $gradeText = ' (Grade ' . $lower_grade . '-' . $upper_grade . ')';
                        } else {
                            if($label !=""){
                                $gradeText = ' (Grade ' . $lower_grade . ')' . '('. $label .')';
                            }else{
                                $gradeText = ' (Grade ' . $lower_grade . ')';
                            }
                            // $gradeText = ' (Grade ' . $lower_grade . ')';
                        }
                    } else {
                        $gradeText ='';
                    }
                } else {
                    $gradeText = '';
                }
                $finalEndTimeArr[] = '<option value="' . date("G:i", $close_timing[$i]) . '">' . $u . $gradeText . '</option>';
            } else {
                
                if($mainlabel !=""){
                    $mainlabel1 = '('. $mainlabel .')';
                }else{
                    $mainlabel1 = "";
                }
                $finalEndTimeArr[] = '<option value="' . date("G:i", $close_timing[$i]) . '">' . $u . $mainlabel1 . ' </option>';
            }
        
            

        }
        function sortByTime($a, $b)
        {
            return $a - $b;
        }
        $location = json_decode($location->working_hours, TRUE);
        foreach ($hrsArr as $day => $values) {
            $day_name = $day;
            $dayn = ucfirst($day_name);
            if ($dayn == $dayOfWeek) { // Capitalize the day name for readability
                $open_time = $values["open"];
                $close_time = $values["close"];
                $package = $values["package"];
            }
        }
        $user_id = $_POST['user_id'];
        $package = $package;
        if ($package == 'both') {
            $myCredits = $wpdb->get_results("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = '$user_id'   and is_cancelled=0", ARRAY_A);
        } else {
            $myCredits = $wpdb->get_results("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = '$user_id' and (package_hidden_name='$package' or (`package_hidden_name`='unlimited' and `is_unlimited_type`='$package'))  and is_cancelled=0", ARRAY_A);
        }
        foreach ($myCredits as $key => $value) {
            # code...
            if ($value['package_hidden_name'] != 'unlimited' && $value['credits'] <= 0) {
                unset($myCredits[$key]);
            }
        }
        $now = new DateTime("now", new DateTimeZone(DEFAULT_TIMEZONE));
        $current_date = strtotime($now->format('Y-m-d'));

        $responseArr = array();
        foreach ($myCredits as $key => $myCredit) {

            if ($myCredit['is_unlimited_type']) {
                // if( strtotime($myCredit['expiry']) <= $current_date) continue;
                $session_name = $myCredit['is_unlimited_type'];
            } else {
                if ($myCredit['credits'] <= 0) continue;
                $session_name = $myCredit['package_hidden_name'];
            }

            $session = $wpdb->get_row("SELECT * FROM " . DB_PACKAGE_SESSIONS . " WHERE session_type = '$package'", ARRAY_A);

            $form_id = $myCredit['gf_form_id'];
            $entry = GFAPI::get_entry($myCredit['gform_entry_id']);
            $form = GFFormsModel::get_form_meta($form_id);

            if (in_array($form_id, [GF_GROUP_FORM_ID, GF_INDIVIDUAL_FORM_ID, GF_UNLIMITED_FORM_ID])) {
                $field = RGFormsModel::get_field($form, 1);
                $planLabel = $field->label;

                $first_name = rgar($entry, '8.3');
                $last_name = rgar($entry, '8.6');
                $fullName = $first_name . " " . $last_name;
            } else if ($form_id == GF_TEAM_FORM_ID) {
                $planLabel = 'Team Instruction Session';
                $fullName = rgar($entry, '16');
            }

            //$responseArr[] = array("purchase_id" => $myCredit['id'], "order_id" => $myCredit['order_id'], "fullName" => $fullName, "session_id" => $session['id'], "session_name" => $session_name, "planLabel" => $planLabel, "is_unlimited_type" => $myCredit['is_unlimited_type']);
        }
        //$responseArr2 = '-- Choose --';

        foreach ($responseArr as $key => $single) {
            $planName = $single['is_unlimited_type'] ? ucfirst($single['is_unlimited_type']) : "";
            $responseArr2 .= '<option value=' . $single['purchase_id'] . '|' . $single['session_id'] . '>Order #' . $single['order_id'] . " - " . $planName . " " . $single['planLabel'] . '</option>';
        }
        //------------------------Package----------------------------------------,'package'=>$responseArr2

    }

    if (count($finalEndTimeArr) > 0 && count($finalStartTimeArr) > 0) {
        echo json_encode(['status' => TRUE, 'start_timings' => $finalStartTimeArr, 'end_timings' => $finalEndTimeArr]);
        die();
    } else {
        echo json_encode(['status' => FALSE, 'message' => 'Location is closed on selected date']);
        die();
    }
}




add_action('wp_ajax_nopriv_save_appointment', 'save_appointment');
add_action('wp_ajax_save_appointment', 'save_appointment');
function save_appointment()
{

    filter_var_array($_POST, FILTER_SANITIZE_STRING);

    global $wpdb;

    // $user_id = get_current_user_id();
    $user_id = my_simple_crypt($_POST['encrypted_user_id'], 'd');

    parse_str($_POST['form_data'], $form_data); //This will convert the string to array

    // PASS TO MULTIPLE BOOKING VALIDATION FUNCTION
    $is_Valid = validate_multiple_booking($form_data);
    if ($is_Valid) {

        if (count($form_data['order_session']) > 0) {

            foreach ($form_data['order_session'] as $main_index => $single_appt) {

                $date = date("Y-m-d", strtotime($form_data['appointment_date'][$main_index]));

                // Calculate the current date and the next week's date
                $now = new DateTime("now", new DateTimeZone(DEFAULT_TIMEZONE));
                $current_date = strtotime($now->format('Y-m-d'));
                $next_week_date = strtotime("+7 days", $current_date);
            
                // Validate if the chosen date is at least one week from the current date
                if (strtotime($date) < $next_week_date) {
                    $response->status = false;
                    $response->message = "The selected appointment date must be at least 7 days from today.";
                    echo json_encode($response);
                    die(); // Stop further execution if validation fails
                }

                $date = date("Y-m-d", strtotime($form_data['appointment_date'][$main_index]));

                // Change TimeZone
                $now = new DateTime("now", new DateTimeZone(DEFAULT_TIMEZONE));
                $current_date = strtotime($now->format('Y-m-d'));
                $current_time = strtotime($now->format('H:m'));

                $response = new stdClass();

                // if(strtotime($date) == $current_date && $current_time > strtotime(CANCELLATION_CUT_OFF_TIME)){
                //     $response->status = false;
                //     $response->message = "Appointment booking not available for today.";
                // }
                //  else{

                $session = explode('|', $single_appt);
                $session_id = $session[1];
                $purchase_id = $session[0];

                $query = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE id = " . $purchase_id;
                $credits_detail = $wpdb->get_row($query);

                $user_id = $credits_detail->customer_id;

                $app_start = $form_data['appointment_start_time'][$main_index];
                $app_end = $form_data['appointment_end_time'][$main_index];

                $app_time = $app_start . " - " . $app_end;
                $queryChildId = "SELECT id FROM " . DB_CHILD_DETAILS . " WHERE user_id=" . $user_id . " AND CONCAT(first_name,' ',last_name ) LIKE '%" . $form_data['order_child'][$main_index] . "%'";
                $childId_detail = $wpdb->get_row($queryChildId);
                $queryChildjersey_size = "SELECT jersey_size FROM " . DB_CHILD_DETAILS . " WHERE user_id=" . $user_id . " AND CONCAT(first_name,' ',last_name ) LIKE '%" . $form_data['order_child'][$main_index] . "%'";
                $childId_jersey_sizedetail = $wpdb->get_row($queryChildjersey_size);
                $queryChildjersey_first_name = "SELECT first_name,last_name FROM " . DB_CHILD_DETAILS . " WHERE user_id=" . $user_id . " AND CONCAT(first_name,' ',last_name ) LIKE '%" . $form_data['order_child'][$main_index] . "%'";
                $childId_jersey_first_name = $wpdb->get_row($queryChildjersey_first_name);
                $appointmentPlatform = 1;
                $isBwc = get_user_meta($user_id, 'isBwc', true);
                if ($isBwc == 1) {
                    $appointmentPlatform = 2;
                }else{
                    $appointmentPlatform = 1;
                }
                $data = array(
                    'unq_id' => substr(my_simple_crypt(time() . $main_index, 'e'), 0, 6),
                    'customer_id' => $user_id,
                    'session_id' => $session_id,
                    'purchase_credits_id' => $purchase_id,
                    'location_id' => $form_data['location_id'][$main_index],
                    'child_id_name' => $form_data['order_child'][$main_index],
                    'child_id' => $childId_detail->id,
                    'appointment_date' => $date,
                    'cust_appointment_time' => $app_time,
                    'comments' => $form_data['comments'][$main_index],
                    'appointmentPlatform' => $appointmentPlatform
                );

                // checck uniqueness
                // $uniqueChkQry = "SELECT * FROM ".DB_APPOINTMENTS.
                //     " WHERE child_id = ".$childId_detail->id.
                //     " AND location_id = ".$form_data['location_id'][$main_index]." 
                //     AND appointment_date = '".$date."' 
                //     AND cust_appointment_time = '".$app_time."'";
                // $uniqueData = $wpdb->get_results($uniqueChkQry);
                // // print_r($uniqueChkQry);die();
                // if($uniqueData){

                //     $response->status = false;
                //     $response->message = "Already exists";
                //     echo json_encode($response);
                //     die();
                // }
                // checck uniqueness

                $format = array('%s', '%d');

                if ($credits_detail->is_unlimited_type) {
                    $query = "SELECT * FROM " . DB_APPOINTMENTS . " JOIN " . DB_WC_GF_CUSTOMER_PURCHASES . " as cp ON cp.id = " . DB_APPOINTMENTS . ".purchase_credits_id WHERE cp.is_unlimited_type is NOT NULL AND cp.id = " . $purchase_id . " AND " . DB_APPOINTMENTS . ".is_cancelled = 0 AND cp.is_cancelled = 0 AND " . DB_APPOINTMENTS . ".appointment_date = '" . $date . "'";
                    $current_booking = $wpdb->get_results($query);

                    if ($current_booking) {
                        $response->status = false;
                        $response->message = APPT_UTLD_DAILY_LIMIT;
                        $response->infofailure = APPT_UTLD_DAILY_LIMIT_MESSAGE;
                    } else {

                        // if(strtotime($credits_detail->expiry) >= $current_date){
                        if ($wpdb->insert(DB_APPOINTMENTS, $data, $format)) {
                            $response->status = true;
                            $response->message = APPT_SUCCESS;
                        } else {
                            $response->status = false;
                            $response->message = APPT_FAILURE;
                            $response->infofailure = APPT_INFO_FAILURE;
                        }
                        // }else{
                        //  $response->status = false;
                        //    $response->message = APPT_ULTD_EXPIRED;
                        // }
                    }
                } else {

                    if ($credits_detail->credits > 0) {

                        if ($wpdb->insert(DB_APPOINTMENTS, $data, $format)) {
                            $credits = $credits_detail->credits - 1;
                            $response->status = true;
                            $response->message = APPT_SUCCESS;
                            $wpdb->update(DB_WC_GF_CUSTOMER_PURCHASES, array('credits' => $credits), array('id' => $purchase_id));
                        } else {
                            $response->status = false;
                            $response->message = APPT_FAILURE;
                            $response->infofailure = APPT_INFO_FAILURE;
                        }
                    } else {
                        $response->status = false;
                        $response->message = APPT_NO_CREDITS;
                        $response->infofailure = APPT_NO_CREDITS_MESSAGE;
                    }
                }

                if ($response->status) {

                    $user = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = $user_id");
                    $email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 6", ARRAY_A);
                    $location = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id = " . $form_data['location_id'][$main_index]);
                    $cust_msg = $email_user['body'];
                    $cust_subject = $email_user['subject'];
                    $cust_email = $user->user_email;
                    $location_name = $location->name;

                    preg_match_all('/{(.*?)}/', $cust_msg, $matches);
                    $split_time = explode(' - ', $app_time);
                    $current_app_time = date('g:i A', strtotime($split_time[0])) . " - " . date('g:i A', strtotime($split_time[1]));
                    if (in_array("customer_name", $matches[1])) {
                        $cust_msg = str_replace('{customer_name}', $user->display_name, $cust_msg);
                    }

                    if (in_array("appointment_date", $matches[1])) {

                        $cust_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($date)), $cust_msg);
                    }
                    if (in_array("location_name", $matches[1])) {
                        $cust_msg = str_replace('{location_name}', $location_name, $cust_msg);
                    }
                    if (in_array("appointment_time", $matches[1])) {
                        $cust_msg = str_replace('{appointment_time}', $current_app_time, $cust_msg);
                    }

                    if (in_array("credits", $matches[1])) {
                        if ($credits_detail->is_unlimited_type) {
                            $cust_msg = str_replace('{credits}', "Not available", $cust_msg);
                        } else {
                            $cust_msg = str_replace('{credits}', $credits_detail->credits - 1, $cust_msg);
                        }
                    }
                    if (in_array("package", $matches[1])) {
                        if ($credits_detail->is_unlimited_type) {
                            $package = "Unlimited Instruction";
                            if ($credits_detail->package_hidden_name == 'group') {
                                $package .= "(Group)";
                            } else if ($credits_detail->package_hidden_name == 'individual') {
                                $package .= "(Individual)";
                            }
                        } else {
                            if ($credits_detail->package_hidden_name == 'group') {
                                $package = "Group Instruction";
                            } else if ($credits_detail->package_hidden_name == 'individual') {
                                $package = "Individual Instruction";
                            }
                        }
                        $cust_msg = str_replace('{package}', $package, $cust_msg);
                    }
                    if (in_array("child_name", $matches[1])) {
                        $cust_msg = str_replace('{child_name}', $data['child_id_name'], $cust_msg);
                    }

                    $headers = array();
                    $headers[] = 'Content-Type: text/html; charset=UTF-8';
                    $headers[] = 'From: ShootInSchool <noreply@shootinschool.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;
                        //Twilio message
                        $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($user->ID, '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);
                                }
                            }
                            //Twilio message
                            // $args = array(
                            //     'number_to'=> fetchCountryMobileCode($user->ID) . $phone[0],
                            //     'message' => $cust_msg_sms
                            // );

                            // twl_send_sms( $args );
                            $phones = [];
                            if (!in_array($phone[0], $phones)) {

                                try {
                                    $number = fetchCountryMobileCode($user->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() );

                                }
                            }
                        }
                    }

                    $sessioncount = $wpdb->get_row("SELECT COUNT(id) as count_session FROM " . DB_APPOINTMENTS . " WHERE child_id=" . $childId_detail->id . " AND is_cancelled = 0", ARRAY_A);
                    $sessions_count = $sessioncount['count_session'];

                    $query1 = "SELECT *,app.appointment_date as app_created,cp.created_at as purchased_date,cp.id as purchased_id FROM " . DB_APPOINTMENTS . " AS app LEFT JOIN " . DB_WC_GF_CUSTOMER_PURCHASES . " as cp ON cp.id = app.purchase_credits_id WHERE app.is_cancelled = 0 AND app.child_id = " . $childId_detail->id . " AND cp.id=" . $purchase_id;

                    $cust_review = $wpdb->get_row($query1);
                    // print_r($countSession);die();
                    if ($sessions_count == 1) {
                        // $email_admin = $wpdb->get_row("SELECT * FROM ".DB_EMAILS." WHERE id = 42",ARRAY_A);
                        // $admin_msg = $email_admin['body'];
                        // $admin_email = get_option('admin_email');
                        // $admin_subject = $email_admin['subject'];
                        // preg_match_all('/{(.*?)}/', $admin_msg, $matches);
                        // if(in_array("jersey_size", $matches[1])){
                        //     $admin_msg = str_replace('{jersey_size}',$childId_jersey_sizedetail->jersey_size,$admin_msg);
                        // }
                        // if(in_array("customer_name", $matches[1])){
                        // 	$name = $childId_jersey_first_name->first_name." ".$childId_jersey_first_name->last_name;
                        //     $admin_msg = str_replace('{customer_name}',$name,$admin_msg);
                        // }
                        // if(in_array("location", $matches[1])){
                        // 	 $admin_msg = str_replace('{location}',$location_name,$admin_msg);
                        // }
                        // if(in_array("time", $matches[1])){
                        //     $admin_msg = str_replace('{time}',$current_app_time,$admin_msg);
                        // }
                        // $headers = array();
                        // $headers[] = 'Content-Type: text/html; charset=UTF-8';
                        // $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
                        // $args1 = array(
                        //     'role' => 'administrator',
                        //     'orderby' => 'user_nicename',
                        //     'order' => 'ASC'
                        // );
                        // $administrator = get_users($args1);
                        // foreach ($administrator as $user) {
                        //     $admin_id=$user->ID;
                        //     if($email_admin['notify_via_email']==1){
                        //         try {
                        //             //code...
                        //             wp_mail( $user->user_email, $admin_subject,$admin_msg ,$headers);

                        //         } catch (Exception $th) {
                        //             //throw $th;
                        //         }
                        //     }
                        // }
                    }
                    // else {
                    if ($cust_review->credits == 2) {


                        $email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 43", ARRAY_A);
                        $admin_msg = $email_admin['body'];
                        $admin_email = get_option('admin_email');
                        $admin_subject = $email_admin['subject'];
                        $user = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = $user_id");
                        preg_match_all('/{(.*?)}/', $admin_msg, $matches);
                        if (in_array("customer_name", $matches[1])) {
                            $admin_msg = str_replace('{customer_name}', $user->display_name, $admin_msg);
                        }
                        $headers = array();
                        $headers[] = 'Content-Type: text/html; charset=UTF-8';
                        $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
                        $headers[] = 'Cc: zastein13@gmail.com';
                        $headers[] = 'Cc: coachfabozzi@gmail.com';
                        $headers[] = 'Cc: kswanberg5@gmail.com';
                        $headers[] = 'Cc: mpassalacqua523@gmail.com';
                        $args1 = array(
                            'role' => 'administrator',
                            'orderby' => 'user_nicename',
                            'order' => 'ASC'
                        );
                        if (!$credits_detail->is_unlimited_type) {
                            $administrator = get_users($args1);
                            foreach ($administrator as $user) {
                                $admin_id = $user->ID;
                                if ($email_admin['notify_via_email'] == 1) {
                                    try {

                                        //code...
                                        wp_mail($user->user_email, $admin_subject, $admin_msg, $headers);
                                    } catch (Exception $th) {
                                        //throw $th;
                                    }
                                }
                            }
                        }
                    }

                    // foreach ($noti_count as $value) {

                    $dateRegistered = new DateTime($cust_review->app_created);
                    // $queryCheck = "SELECT id,start_credits,package_hidden_name,credits FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = $customer_id GROUP BY order_id  ORDER BY id DESC";

                    if ($cust_review->package_hidden_name == 'group' || $cust_review->package_hidden_name == 'individual') {
                        // if(($cust_review->credits == 2 && $cust_review->start_credits == 5) || ($cust_review->credits == 2 && $cust_review->start_credits == 4) || ($cust_review->credits == 1 && $cust_review->start_credits == 3) || ($cust_review->credits == 1 && $cust_review->start_credits == 2) || ($cust_review->credits == 5 && $cust_review->start_credits == 10) || ($cust_review->credits == 4 && $cust_review->start_credits == 9) || ($cust_review->credits == 4 && $cust_review->start_credits == 8) || ($cust_review->credits == 3 && $cust_review->start_credits == 7) || ($cust_review->credits == 3 && $cust_review->start_credits == 6)) {
                        if (($cust_review->credits == 3 && $cust_review->start_credits == 5) || ($cust_review->credits == 2 && $cust_review->start_credits == 4) || ($cust_review->credits == 2 && $cust_review->start_credits == 3) || ($cust_review->credits == 1 && $cust_review->start_credits == 2) || ($cust_review->credits == 5 && $cust_review->start_credits == 10) || ($cust_review->credits == 5 && $cust_review->start_credits == 9) || ($cust_review->credits == 4 && $cust_review->start_credits == 8) || ($cust_review->credits == 4 && $cust_review->start_credits == 7) || ($cust_review->credits == 3 && $cust_review->start_credits == 6)) {
                            $email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 44", ARRAY_A);
                            $admin_msg = $email_admin['body'];
                            $admin_email = get_option('admin_email');
                            $admin_subject = $email_admin['subject'];

                            $user = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = $user_id");
                            preg_match_all('/{(.*?)}/', $admin_msg, $matches);
                            if (in_array("customer_name", $matches[1])) {
                                $admin_msg = str_replace('{customer_name}', $user->display_name, $admin_msg);
                            }
                            $headers = array();
                            $headers[] = 'Content-Type: text/html; charset=UTF-8';
                            $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
                            $headers[] = 'Cc: zastein13@gmail.com';
                            $headers[] = 'Cc: coachfabozzi@gmail.com';
                            $headers[] = 'Cc: kswanberg5@gmail.com';
                            $headers[] = 'Cc: mpassalacqua523@gmail.com';
                            $args1 = array(
                                'role' => 'administrator',
                                'orderby' => 'user_nicename',
                                'order' => 'ASC'
                            );
                            $administrator = get_users($args1);
                            foreach ($administrator as $user) {
                                $admin_id = $user->ID;
                                if ($email_admin['notify_via_email'] == 1) {
                                    wp_mail($user->user_email, $admin_subject, $admin_msg, $headers);
                                }
                            }
                        }
                    } else if ($cust_review->package_hidden_name == 'unlimited') {
                        $purchased_date = $cust_review->purchased_date;
                        $app_created = $cust_review->app_created;
                        $diff = abs(strtotime($purchased_date) - strtotime($app_created));
                        $years = floor($diff / (365 * 60 * 60 * 24));
                        $months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
                        if ($months >= 4) {
                            if ($cust_review->is_send_mail == 0) {
                                $email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 44", ARRAY_A);
                                $admin_msg = $email_admin['body'];
                                $admin_email = get_option('admin_email');
                                $admin_subject = $email_admin['subject'];

                                $user = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = $user_id");
                                preg_match_all('/{(.*?)}/', $admin_msg, $matches);
                                if (in_array("customer_name", $matches[1])) {
                                    $admin_msg = str_replace('{customer_name}', $user->display_name, $admin_msg);
                                }
                                $headers = array();
                                $headers[] = 'Content-Type: text/html; charset=UTF-8';
                                $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
                                $headers[] = 'Cc: zastein13@gmail.com';
                                $headers[] = 'Cc: coachfabozzi@gmail.com';
                                $headers[] = 'Cc: kswanberg5@gmail.com';
                                $headers[] = 'Cc: mpassalacqua523@gmail.com';
                                $args1 = array(
                                    'role' => 'administrator',
                                    'orderby' => 'user_nicename',
                                    'order' => 'ASC'
                                );
                                $administrator = get_users($args1);
                                foreach ($administrator as $user) {
                                    $admin_id = $user->ID;
                                    if ($email_admin['notify_via_email'] == 1) {
                                        wp_mail($user->user_email, $admin_subject, $admin_msg, $headers);
                                    }
                                }
                                $args = array("is_send_mail" => 1);
                                $where = array("id" => $cust_review->purchased_id);
                                $sql = $wpdb->update(DB_WC_GF_CUSTOMER_PURCHASES, $args, $where);
                                // $wpdb->query($wpdb->prepare("UPDATE ".DB_WC_GF_CUSTOMER_PURCHASES." SET is_send_mail=1 WHERE id=".$cust_review->purchased_id));
                            }
                        }
                    }

                    // }

                    /* Admin */
                    $email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 7", ARRAY_A);
                    $admin_msg = $email_admin['body'];
                    $admin_email = get_option('admin_email');
                    $admin_subject = $email_admin['subject'];
                    $user = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = $user_id");
                    preg_match_all('/{(.*?)}/', $admin_msg, $matches);

                    $split_time = explode(' - ', $app_time);
                    $current_app_time = date('g:i A', strtotime($split_time[0])) . " - " . date('g:i A', strtotime($split_time[1]));
                    if (in_array("customer_name", $matches[1])) {
                        $admin_msg = str_replace('{customer_name}', $user->display_name, $admin_msg);
                    }

                    if (in_array("appointment_date", $matches[1])) {
                        $admin_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($date)), $admin_msg);
                    }
                    if (in_array("appointment_time", $matches[1])) {
                        $admin_msg = str_replace('{appointment_time}', $current_app_time, $admin_msg);
                    }
                    if (in_array("location_name", $matches[1])) {
                        $admin_msg = str_replace('{location_name}', $location_name, $admin_msg);
                    }

                    if (in_array("credits", $matches[1])) {
                        if ($credits_detail->is_unlimited_type) {
                            $admin_msg = str_replace('{credits}', "Not available", $admin_msg);
                        } else {
                            $admin_msg = str_replace('{credits}', $credits_detail->credits - 1, $admin_msg);
                        }
                    }
                    if (in_array("package", $matches[1])) {
                        if ($credits_detail->is_unlimited == 1) {
                            $package = "Unlimited Instruction";
                            if ($credits_detail->package_hidden_name == 'group') {
                                $package .= "(Group)";
                            } else if ($credits_detail->package_hidden_name == 'individual') {
                                $package .= "(Individual)";
                            }
                        } else {
                            if ($credits_detail->package_hidden_name == 'group') {
                                $package = "Group Instruction";
                            } else if ($credits_detail->package_hidden_name == 'individual') {
                                $package = "Individual Instruction";
                            }
                        }
                        $admin_msg = str_replace('{package}', $package, $admin_msg);
                    }
                    if (in_array("child_name", $matches[1])) {
                        $admin_msg = str_replace('{child_name}', $data['child_id_name'], $admin_msg);
                    }


                    // $admin_msg = wpautop($content);
                    $headers = array();
                    $headers[] = 'Content-Type: text/html; charset=UTF-8';
                    $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
                    $args1 = array(
                        'role' => 'administrator',
                        'orderby' => 'user_nicename',
                        'order' => 'ASC'
                    );
                    $administrator = get_users($args1);
                    foreach ($administrator as $user) {
                        $admin_id = $user->ID;
                        if ($email_admin['notify_via_email'] == 1) {
                            try {
                                //code...
                                wp_mail($user->user_email, $admin_subject, $admin_msg, $headers);
                            } catch (Exception $th) {
                                //throw $th;
                            }
                        }
                        if ($email_admin['notify_via_sms'] == 1) {
                            $admin_msg_sms = $admin_msg;
                            $admin_msg_sms = str_replace('<br>', "\n", $admin_msg_sms);
                            $admin_msg_sms = str_replace('&nbsp', " ", $admin_msg_sms);
                            preg_match_all('/<(.*?)>/', $admin_msg_sms, $sms_matches);
                            foreach ($sms_matches[0] as $match) {

                                if ($match == "</p>") {
                                    $admin_msg_sms = str_replace($match, "\n", $admin_msg_sms);
                                } else {
                                    $admin_msg_sms = str_replace($match, '', $admin_msg_sms);
                                }
                            }
                            //Twilio message
                            $phone = get_user_meta($admin_id, $key = 'billing_phone');
                            if (count($phone) > 0) {
                                // $args = array(
                                //     'number_to'=> fetchCountryMobileCode($admin_id) . $phone[0],
                                //     'message' => $admin_msg_sms
                                // );
                                // twl_send_sms( $args );
                                $phones = [];
                                if (!in_array($phone[0], $phones)) {

                                    try {
                                        $number = fetchCountryMobileCode($admin_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" => $admin_msg_sms, "from" => $twilio_number]
                                        );

                                        array_push($phones, $phone[0]);
                                    } catch (Exception $e) {
                                        // die( $e->getCode() . ' : ' . $e->getMessage() );

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        echo json_encode($response);
    }

    die();
}

add_action('wp_ajax_nopriv_render_clone_appointment', 'render_clone_appointment');
add_action('wp_ajax_render_clone_appointment', 'render_clone_appointment');
function render_clone_appointment()
{

    global $wpdb;

    parse_str($_POST['form_data'], $form_data); //This will convert the string to array
    $clone_counter = (int)$_POST['clone_counter'];

    // PASS TO MULTIPLE BOOKING VALIDATION FUNCTION
    $is_Valid = validate_multiple_booking($form_data);

    // $user_id = get_current_user_id();
    $user_id = $_POST['user_id'];

    
    $myCredits = $wpdb->get_results("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id = '$user_id' and is_cancelled=0", ARRAY_A);

    foreach ($myCredits as $key => $value) {
        # code...
        if (
            $value['package_hidden_name'] != 'unlimited'
            && $value['credits'] <= 0
        ) {
            unset($myCredits[$key]);
        }
    }
    // Change TimeZone
    $now = new DateTime("now", new DateTimeZone(DEFAULT_TIMEZONE));
    $current_date = strtotime($now->format('Y-m-d'));

    $responseArr = array();
    foreach ($myCredits as $key => $myCredit) {

        if ($myCredit['is_unlimited_type']) {
            // if( strtotime($myCredit['expiry']) <= $current_date) continue;
            $session_name = $myCredit['is_unlimited_type'];
        } else {
            if ($myCredit['credits'] <= 0) continue;
            $session_name = $myCredit['package_hidden_name'];
        }

        $session = $wpdb->get_row("SELECT * FROM " . DB_PACKAGE_SESSIONS . " WHERE session_type = '$session_name'", ARRAY_A);

        $form_id = $myCredit['gf_form_id'];
        $entry = GFAPI::get_entry($myCredit['gform_entry_id']);
        $form = GFFormsModel::get_form_meta($form_id);
//GF_GROUP_FORM_ID, GF_PERSONAL_FORM_ID, GF_INDIVIDUAL_FORM_ID, GF_UNLIMITED_FORM_ID, GF_GF_BWC_FORM_ID, GF_GF_BWC_UNLIMITED_FORM_ID, GF_GF_BWC_BOWLING_FORM_ID, GF_GF_BWC_FIT_FORM_ID, GF_GF_BWC_IN_GYM_FORM_ID, GF_GF_BWC_SPECIALTY_FORM_ID
        if (in_array($form_id, [GF_GROUP_FORM_ID, GF_INDIVIDUAL_FORM_ID, GF_UNLIMITED_FORM_ID, GF_GF_BWC_FORM_ID, GF_GF_BWC_UNLIMITED_FORM_ID, GF_GF_BWC_BOWLING_FORM_ID, GF_GF_BWC_FIT_FORM_ID, GF_GF_BWC_IN_GYM_FORM_ID, GF_GF_BWC_SPECIALTY_FORM_ID])) {
           // $field = RGFormsModel::get_field($form, 1);
            $planLabel = $field->label;
           // $field = RGFormsModel::get_field($form, 1);
			// $planHiddenName = rgar($entry, '9');
			$planData = rgar($entry, '1');
			$sanitizedPlanData = explode(chr(1), str_replace(array('|'), chr(1), $planData));
            $first_name = rgar($entry, '8.3');
            $last_name = rgar($entry, '8.6');
            $fullName = $first_name . " " . $last_name;
        } else if ($form_id == GF_TEAM_FORM_ID) {
            $planLabel = 'Team Instruction Session';
            $fullName = rgar($entry, '16');
        }
        $ab = 0;
        $responseArr[] = array("purchase_id" => $myCredit['id'], "order_id" => $myCredit['order_id'], "fullName" => $fullName, "session_id" => $session['id'], "session_name" => $session_name, "planLabel" => $planLabel, "is_unlimited_type" => $myCredit['is_unlimited_type'],"unlimitedTypelabel" => $sanitizedPlanData[0]);
    }

    if (class_exists('GFCommon')  && count($myCredits) > 0) {

        $encrypted_user_id = my_simple_crypt($user_id);

        ob_start();
?>

        <div class="outerGroup">
            <!-- First Form Instance-->
            <?php if ($clone_counter > 0) { ?>
                <div class="close-row row">
                    <div class="pull-right">
                        <div class="form-group custom-parsley">
                            <button type="button" class="btn btn-danger btn-sm" onclick="this.parentNode.parentNode.parentNode.parentNode.remove();">X</button>
                        </div>
                    </div>
                </div>
            <?php } ?>

            <div class="row">

                <div class="col-md-4">
                    <div class="form-group custom-parsley">
                        <input type="hidden" name="order_session[]" class="order_session">
                        <label for="">Please ensure that you select the right package </label>
                        <select name="session_sel[]" class="form-control session_sel" onchange="getChildren(this)" required>
                            <option value=""> -- Choose an Active Session -- </option>
                            <?php foreach ($responseArr as $key => $single) { ?>
                                <option value="<?php echo $single['purchase_id'] . '|' . $single['session_id'] ?>">
                                <?php $planName = $single['is_unlimited_type'] ? ucfirst($single['unlimitedTypelabel']) : ""; ?>
                                    Order <?php echo "#" . $single['order_id'] . " - " . $planName . " " . $single['planLabel']; ?>
                                </option>
                            <?php } ?>
                        </select>

                    </div>
                </div>
                <?php
                $current_user = wp_get_current_user();

                if (user_can($current_user, 'administrator') ||  user_can($current_user, 'siab_sub_admin')) {
                ?>
                    <div class="col-md-4">
                        <div class="form-group custom-parsley">
                            <label for="">Appointment Date<div class="tool"> <img src="https://img.icons8.com/flat_round/64/000000/question-mark.png" style="width: 18px;
                        margin-left: 7px;">
                                    <span class="tooltiptext" style="margin-left: -387px;"> <i class="fa fa-times close" onclick="this.parentNode.remove();" aria-hidden="true"></i> We release our schedule 1 week at a time, from Monday-Sunday. Every Sunday at 12:00pm the next week will become available.</span>
                                </div></label>
                            <input type="hidden" class="user_sel" name="user_id" value="<?php echo $user_id; ?>">
                            <input type="text" class="form-control date_sel" name="appointment_date[]" placeholder="-- Choose Date --" onchange="enableLocations_admin(this)" required autocomplete="off" disabled="disabled">
                            <!-- <span class="tooltiptext_firsttime appt_date" style="display:none;">We release our schedule 1 week at a time, from Monday-Sunday. Every Sunday at 12:00pm the next week will become available.</span> -->
                        </div>
                    </div>
                <?php } else { ?>
                    <div class="col-md-4">
                        <div class="form-group custom-parsley">
                            <label for="">Appointment Date<div class="tool"> <img src="https://img.icons8.com/flat_round/64/000000/question-mark.png" style="width: 18px;
                        margin-left: 7px;">
                                    <span class="tooltiptext" style="margin-left: -387px;"> <i class="fa fa-times close" onclick="this.parentNode.remove();" aria-hidden="true"></i> We release our schedule 1 week at a time, from Monday-Sunday. Every Sunday at 12:00pm the next week will become available.</span>
                                </div></label>
                            <input type="hidden" class="user_sel" name="user_id" value="<?php echo $user_id; ?>">
                            <input type="text" class="form-control date_sel" name="appointment_date[]" placeholder="-- Choose Date --" onchange="enableLocations(this)" required autocomplete="off" disabled="disabled">
                            <!-- <span class="tooltiptext_firsttime appt_date" style="display:none;">We release our schedule 1 week at a time, from Monday-Sunday. Every Sunday at 12:00pm the next week will become available.</span> -->
                        </div>
                    </div>
                <?php } ?>
                <div class="col-md-4">
                    <div class="form-group custom-parsley">
                        <label for="">Select a location</label>
                        <select name="location_id[]" class="form-control location_sel" onchange="getTimeSlots(this)" disabled="disabled" required>
                            <option value=""> -- All Locations -- </option>
                        </select>
                    </div>
                </div>



            </div>
            <div class="row">

                <div class="col-md-4">
                    <div class="form-group custom-parsley">
                        <label for="">Appointment Start</label>
                        <select name="appointment_start_time[]" class="form-control slot_sel_start" onchange="getEndTimeSlots(this)" required disabled="disabled">
                            <option value=""> -- Choose -- </option>
                        </select>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group custom-parsley">
                        <label for="">Appointment End <div class="tool"> <img src="https://img.icons8.com/flat_round/64/000000/question-mark.png" style="    width: 18px;
    margin-left: 7px;">
                                <span class="tooltiptext" style="margin-left:18px;"> <i class="fa fa-times close" onclick="this.parentNode.remove();" aria-hidden="true"></i> If you select a Range of Time, we will assume that you are open to do any of the hours in that time frame. For example, if you select 4:00pm-7:00pm, that means you are okay with 4:00-5:00pm, 5:00-6:00pm or 6:00-7:00pm. We will inform you of the time we've assigned to you by 12pm on the day of the session.</span>

                            </div></label>
                        <select name="appointment_end_time[]" class="form-control slot_sel_end" onchange="enablePurchaseOrders(this)" required disabled="disabled">
                            <option value=""> -- Choose -- </option>
                        </select>
                        <!-- <span class="tooltiptext_firsttime appt_end" style="margin-left:-178px; display:none;"> If you select a Range of Time, we will assume that you are open to do any of the hours in that time frame. For example, if you select 4:00pm-7:00pm, that means you are okay with 4:00-5:00pm, 5:00-6:00pm or 6:00-7:00pm. We will inform you of the time we've assigned to you by 12pm on the day of the session.</span> -->
                    </div>
                    
                </div>
                

                <div class="col-md-4 chld_div">
                    <div class="form-group custom-parsley">
                        <label for="">Select a Child</label>
                        <select name="order_child[]" class="form-control purchase_order_sel" onchange="setPurchaseData(this)" disabled="disabled" required>
                            <option value=""> -- Choose Child Name -- </option>
                            <!-- <?php foreach ($responseArr as $key => $single) { ?>
                                <option data-id="<?php echo $single['purchase_id'] . '|' . $single['session_id']; ?>" value="<?php echo $single['fullName']; ?>">
                                    <?php echo $single['fullName']; ?>
                                </option>
                            <?php } ?> -->
                        </select>
                    </div>
                </div>

            </div>
            <div class="row">
                <div class="col-md-12">
                <label for="">All appointments are for a 1-hour session. If you select a range of time, we will assume that you are available for any 1-hour slot in that time range. If you want to book for more than 1 hour, please book another session.</label>
                </div>
            </div>

            <div class="row">
                <div class="col-md-12">
                    <div class="form-group custom-parsley">
                        <label for="">Requests/Comments <div class="tool"> <img src="https://img.icons8.com/flat_round/64/000000/question-mark.png" style="    width: 18px;
    margin-left: 7px;">
                                <span class="tooltiptext"> <i class="fa fa-times close" onclick="this.parentNode.remove();" aria-hidden="true"></i> You are always welcome to leave comments on specific skills you'd like players to work on during sessions. In regards to trainer requests, we will do our very best to accommodate, however, we can never guarantee that a trainer request will be fulfilled.</span>

                            </div></label>
                        <textarea name="comments[]" class="form-control slot_textarea"></textarea>
                        <label for=""> * We will consider, but can not guarantee that all requests will be granted.</label>
                        <!-- <span class="tooltiptext_firsttime appt_comment" style="display:none;"> You are always welcome to leave comments on specific skills you'd like players to work on during sessions. In regards to trainer requests, we will do our very best to accommodate, however, we can never guarantee that a trainer request will be fulfilled.</span> -->
                    </div>
                </div>
            </div>

            <input type="hidden" name="u_id" class="u_id" value="<?php echo $encrypted_user_id; ?>">

        </div>
    <?php

        $renderedHtml = ob_get_clean();
    }
    echo json_encode(['status' => true, 'renderedHtml' => $renderedHtml]);
    die();
}


// MULTIPLE BOOKING VALIDATION CORE FUNCTION
function validate_multiple_booking($form_data)
{

    global $wpdb;

    $clone_counter = (int)$_POST['clone_counter'];

    $data_to_ignore = array();

    if (isset($form_data['order_session']) && count($form_data['order_session']) > 0) {


        // 1) Prepare an array with all existing contents in the booking form
        foreach ($form_data['order_session'] as $main_index => $single_appt) {

            $pur_sess = explode('|', $single_appt);
            $purchase_id = $pur_sess[0];
            $session_id = $pur_sess[1];

            $location_id = $form_data['location_id'][$main_index];
            $appointment_date = $form_data['appointment_date'][$main_index];
            $app_start = $form_data['appointment_start_time'][$main_index];
            $app_end = $form_data['appointment_end_time'][$main_index];
            if (strtotime($app_start) > strtotime($app_end)) {
                echo json_encode(array("status" => FALSE, "message" => 'Start time must be less than End time.'));
                die();
            } else if (strtotime($app_start) == strtotime($app_end)) {
                echo json_encode(array("status" => FALSE, "message" => 'Start time and End time cannot be Same.'));
                die();
            }
            $location_data = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id = " . $form_data['location_id'][$main_index]);


            $query_check = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE id = " . $purchase_id;
            $credits_detail_check = $wpdb->get_row($query_check);

            if (($credits_detail_check->package_hidden_name != "team") && ($credits_detail_check->package_hidden_name != "unlimited")) {
                if ($location_data->blocking_hours) {
                    $blocking_hours = json_decode($location_data->blocking_hours, TRUE);

                    $check_date =  strtolower(date("l", strtotime($appointment_date)));
                    $block_start = $blocking_hours[$check_date]['open'];
                    $block_end = $blocking_hours[$check_date]['close'];

                    //checking blocking time
                    $block_start_frmt = $block_start ? date("g:i A", strtotime($block_start)) : '';
                    $block_end_frmt = $block_end ? date("g:i A", strtotime($block_end)) : '';

                    $blockTime = 0;
                    if (strtotime($block_start) == strtotime($app_start) && strtotime($block_end) == strtotime($app_end)) {

                        $blockTime = 1;
                    } else if (strtotime($block_start) == strtotime($app_start) && strtotime($block_end) > strtotime($app_end)) {

                        $blockTime = 1;
                    } else if (strtotime($block_start) == strtotime($app_start) && strtotime($block_end) < strtotime($app_end)) {

                        $blockTime = 1;
                    } else if (strtotime($block_start) > strtotime($app_start) && strtotime($block_end) == strtotime($app_end)) {

                        $blockTime = 1;
                    } else if (strtotime($block_start) < strtotime($app_start) && strtotime($block_end) == strtotime($app_end)) {

                        $blockTime = 1;
                    } else if (strtotime($block_start) < strtotime($app_start) && strtotime($block_end) > strtotime($app_end)) {

                        $blockTime = 1;
                    } else if (strtotime($block_start) > strtotime($app_start) && strtotime($block_end) < strtotime($app_end)) {

                        $blockTime = 1;
                    } else if (strtotime($block_start) > strtotime($app_start) && strtotime($block_start) < strtotime($app_end)) {

                        $blockTime = 1;
                    } else if (strtotime($block_end) > strtotime($app_start) && strtotime($block_end) < strtotime($app_end)) {

                        $blockTime = 1;
                    }

                    if ($blockTime == 1) {
                        $timings_frmt = $block_start_frmt . ' - ' . $block_end_frmt;
                        echo json_encode(array("status" => FALSE, "message" => 'Group and Individual bookings not available for ' . $timings_frmt . ' time slot', "infofailure" => APPT_INFO_FAILURE_BLOCKED_TIME_SLOT));
                        die();
                    }
                    //checking blocking time ends

                    // if( strtotime($block_start) <= strtotime($app_start) && strtotime($block_end) >= strtotime($app_end) )  {
                    //     echo json_encode(array("status" => FALSE, "message" => 'Personal and Individual bookings not available for the selected time slot'));
                    //     die();
                    // }
                }
            }



            $appointment_time = $app_start . " - " . $app_end;

            // $appointment_time = $form_data['appointment_time'][$main_index];
            $data_to_ignore[] = array("purchase_id" => $purchase_id, "session_id" => $session_id, "location_id" => $location_id, "appointment_date" => $appointment_date, "appointment_time" => $appointment_time);
        }

        $purchase_ids = array_column($data_to_ignore, 'purchase_id');
        $appt_dates = array_column($data_to_ignore, 'appointment_date');

        $credits_on_hold = array();
        foreach ($data_to_ignore as $main_key => $single) {
            $date = date("Y-m-d", strtotime($single['appointment_date']));

            // Change TimeZone
            $now = new DateTime("now", new DateTimeZone(DEFAULT_TIMEZONE));
            $current_date = strtotime($now->format('Y-m-d'));
            $current_time = strtotime($now->format('H:m'));

            $response = new stdClass();

            $current_user = wp_get_current_user();


            if (!in_array('administrator', (array) $current_user->roles) && !in_array('siab_sub_admin', (array) $current_user->roles) && strtotime($date) == $current_date && $current_time > strtotime(CANCELLATION_CUT_OFF_TIME)) {
                // echo json_encode(array("status" => FALSE, "message" => APPT_CANCEL_AFTER_CUTOFF,"infofailure" =>APPT_INFO_FAILURE));
                echo json_encode(array("status" => FALSE, "message" => '', "infofailure" => APPT_INFO_FAILURE));
                die();
            } else {

                $purchase_id = $single['purchase_id'];

                $query = "SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE id = " . $purchase_id;
                $credits_detail = $wpdb->get_row($query);

                if ($credits_detail->is_unlimited_type) {
                    $query = "SELECT * FROM " . DB_APPOINTMENTS . " JOIN " . DB_WC_GF_CUSTOMER_PURCHASES . " as cp ON cp.id = " . DB_APPOINTMENTS . ".purchase_credits_id WHERE cp.is_unlimited_type is NOT NULL AND cp.id = " . $purchase_id . " AND " . DB_APPOINTMENTS . ".is_cancelled = 0 AND " . DB_APPOINTMENTS . ".appointment_date = '" . $date . "'";

                    $current_booking = $wpdb->get_results($query);
                    if ($current_booking) {
                        echo json_encode(array("status" => FALSE, "message" => "You have already booked an Unlimited Session - " . ucfirst($credits_detail->is_unlimited_type) . " for " . $date . ". " . APPT_UTLD_DAILY_LIMIT, "infofailure" => APPT_UTLD_DAILY_LIMIT_MESSAGE));
                        die();
                    } else {
                        // $appt_dates[1] == $appt_dates[0]
                        // get number of similar occurance of purchase_ids
                        $purchaseArrCount = array_count_values($purchase_ids);
                        foreach ($purchaseArrCount as $val => $occurance) {
                            if ($occurance > 1) { // If more than 1 occurance of same purchase_id
                                $match_keys = array_keys($purchase_ids, $val); // get keys of all occurance of same purchase_id
                                if (count($match_keys) > 0) {
                                    $temp_array = [];
                                    foreach ($match_keys as $singleKey) {
                                        if (in_array($appt_dates[$singleKey], $temp_array)) {
                                            echo json_encode(array("status" => FALSE, "message" => APPT_UTLD_DAILY_LIMIT, "infofailure" => APPT_UTLD_DAILY_LIMIT_MESSAGE));
                                            die();
                                        } else {
                                            $temp_array[] = $appt_dates[$singleKey];
                                        }
                                        // if($appt_dates[$singleKey] == $date){
                                        //      // match with today date
                                        //     echo json_encode(array("status" => FALSE, "message" => APPT_UTLD_DAILY_LIMIT));
                                        //     die();
                                        // }
                                    }
                                }
                            }
                        }

                        //if(! strtotime($credits_detail->expiry) >= $current_date){
                        //    echo json_encode(array("status" => FALSE, "message" => APPT_ULTD_EXPIRED));
                        //    die();
                        //}
                    }
                } else {

                    // Update credits on hold
                    $on_holdArr[$purchase_id] = $on_holdArr[$purchase_id] + 1;
                    $actual_rem_credits = $credits_detail->credits;
                    $resultant_credits = $actual_rem_credits - $on_holdArr[$purchase_id];

                    if ($resultant_credits < 0) {
                        echo json_encode(array("status" => FALSE, "message" => APPT_NO_CREDITS, "infofailure" => APPT_NO_CREDITS_MESSAGE));
                        die();
                    }
                }
            }
        }
    }

    return TRUE; // Validation success
}




// add_action('wp_ajax_nopriv_get_date_not_available', 'get_date_not_available');
// add_action('wp_ajax_get_date_not_available', 'get_date_not_available');
// function get_date_not_available(){

//     global $wpdb;

//     $location_id=$_POST['loc_id'];

//     $query = "SELECT * FROM " . DB_INSTRUCTORS_AVAILABILITY . " WHERE location_id = " . $location_id;
//     $timings = $wpdb->get_results($query);

//     if($timings){

//          foreach ($timings as $time) {

//             $day = $time->weekday;
//             if($day == 'sunday'){
//                 $tempArr[] = 0;
//             }
//             if($day == 'monday'){
//                 $tempArr[] = 1;
//             }
//             if($day == 'tuesday'){
//                 $tempArr[] = 2;
//             }
//             if($day == 'wednesday'){
//                 $tempArr[] = 3;
//             }
//             if($day == 'thursday'){
//                 $tempArr[] = 4;
//             }
//             if($day == 'friday'){
//                 $tempArr[] = 5;
//             }
//             if($day == 'saturday'){
//                 $tempArr[] = 6;
//             }
//             $tempArr=array_unique($tempArr);
//         }
//     } else{
//         $tempArr = [];
//     }

//     $response->days = $tempArr;
//     echo json_encode($response);
//     die();

// }

add_action('wp_ajax_nopriv_render_or_append_new_child', 'render_or_append_new_child');
add_action('wp_ajax_render_or_append_new_child', 'render_or_append_new_child');
function render_or_append_new_child()
{
    global $wpdb;
    $isAppend = (int)$_POST['isAppend'];

    $form = GFFormsModel::get_form_meta(GF_CHILD_DETAILS_FORM_ID);
    //    $ordinal_map = [
    //         1 => '1st', 2 => '2nd', 3 => '3rd',4 => '4th',5 => '5th',6 => '6th',7 => '7th',8 => '8th', 9 => '9th',10 => '10th',];





    $jersey_size_options = RGFormsModel::get_field($form, 7);
    $jersey_size_optionsArr = array_column($jersey_size_options->choices, 'text');
    $grade_options = RGFormsModel::get_field($form, 5);
    $grade_optionsArr = array_column($grade_options->choices, 'text');

    // $grade_options = $wpdb->get_results("SELECT * FROM " . DB_GRADE_SESSIONS . " WHERE status = 1");

    if (class_exists('GFCommon')) {

        ob_start();
    ?>

        <div class="outerGroup">

            <!-- First Form Instance-->
            <?php if ($isAppend != 0) { ?>
                <div class="row">
                    <div class="col-md-1 pull-right">
                        <div class="form-group">
                            <button type="button" class="btn btn-danger btn-sm" onclick="this.parentNode.parentNode.parentNode.parentNode.remove();">X</button>
                        </div>
                    </div>
                </div>
            <?php } ?>

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <input type="text" name="first_name[]" maxlength="100" class="form-control" placeholder="Enter First Name" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <input type="text" name="last_name[]" maxlength="100" class="form-control" placeholder="Enter Last Name" required>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <select class="form-control sel_grade" name="grade[]" required>
                            <option value=""> -- Choose Grade -- </option>
                            <?php foreach ($grade_optionsArr as $grade) { ?>
                                <option value="<?php echo $grade; ?>">
                                    <?php echo $grade; ?>
                                </option>
                            <?php } ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <select class="form-control sel_jersey" name="jersey_size[]" required>
                            <option value=""> -- Choose Jersey Size -- </option>
                            <option value="Adult Large">Adult Large</option>
                            <?php foreach ($jersey_size_optionsArr as $jersey) { ?>
                                <option value="<?php echo $jersey; ?>">
                                    <?php echo $jersey; ?>
                                </option>
                            <?php } ?>
                        </select>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <input type="text" name="school_name[]" maxlength="100" class="form-control" placeholder="Enter School Name" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <input type="text" name="child_dob" class="form-control date_sel " id="child_dob" placeholder="YYYY-MM-DD" required>
                    </div>
                </div>
            </div>
            <div class="row">

                <div class="col-md-6">
                    <div class="form-group">
                        <input type="file" name="file[]" id="fileinput" class="fileinput" required>
                    </div>
                </div>
            </div>

        </div>
        <script type="text/javascript">
            var currentYear = new Date().getFullYear();

            jQuery(".date_sel").datepicker({
                changeMonth: true,
                changeYear: true,
                // minDate: new Date(),
                maxDate: new Date(), // December 31 of the current year
                yearRange: (currentYear - 100) + ":" + currentYear,
                dateFormat: "yy-m-dd",
                firstDay: 1
            });
            // getDatePicker([]);
        </script>
    <?php $renderedHtml = ob_get_clean();
    }

    echo json_encode(['status' => true, 'renderedHtml' => $renderedHtml]);
    die();
}



add_action('wp_ajax_nopriv_save_child', 'save_child');
add_action('wp_ajax_save_child', 'save_child');
function save_child()
{

    filter_var_array($_POST, FILTER_SANITIZE_STRING);

    global $wpdb;

    $user_id = get_current_user_id();
    parse_str($_POST['data'], $form_data); //This will convert the string to array
    // parse_str($_FILES['file'], $files); //This will convert the string to array

    $errorFlag = FALSE;
    $key_data = "file";
    foreach ($form_data['first_name'] as $key => $value) {
        $key_data = $key_data . $key;
        if ($_FILES[$key_data]['name'][$key] != '') {

            $uploadedfile = $_FILES[$key_data];
            $upload_overrides = array('test_form' => false);

            $movefile = wp_handle_upload($uploadedfile, $upload_overrides);
            if ($movefile && !isset($movefile['error'])) {
                $imageurl = $movefile['url'];
            } else {
               //$response = "sadasd";
            }
        }

        $first_name = $value;
        $last_name = $form_data['last_name'][$key];
        $query = "SELECT id FROM " . DB_CHILD_DETAILS . " WHERE user_id = '$user_id' AND LOWER(first_name) = LOWER('$first_name') AND LOWER(last_name) = LOWER('$last_name')";
        $data = $wpdb->get_row($query);

        if ($wpdb->num_rows == 0) {

            $data = array(
                'user_id' => $user_id,
                'first_name' => $first_name,
                'last_name' => $last_name,
                'grade' => $form_data['grade'][$key],
                'jersey_size' => $form_data['jersey_size'][$key],
                'child_type' => 'group',
                'school_name' => $form_data['school_name'][$key],
                'child_dob' => $form_data['child_dob'],
                'profile_image' => $imageurl,
            );

            if (!$wpdb->insert(DB_CHILD_DETAILS, $data)) {
                $errorFlag = TRUE;
            }
        } else {
            $errorFlag = TRUE;
        }
    }
    $response = new stdClass();
    if ($errorFlag) {
        $response->status = false;
        $response->message = CHILD_FAILURE;
    } else {
        $response->status = true;
        $response->message = CHILD_SUCCESS;
    }
    // $response='sdfsef';

    echo json_encode($response);
    die();
}

add_action('wp_ajax_nopriv_get_child', 'get_child');
add_action('wp_ajax_get_child', 'get_child');
function get_child()
{

    global $wpdb;
    $pur_sess_id =  explode("|", $_POST['pur_sess_id']);

    if (isset($_POST['user_id']) && $_POST['user_id']) {
        $user_id = $_POST['user_id'];
    } else {
        $user_id = get_current_user_id();
    }

    $myCredit = $wpdb->get_row("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE id = '$pur_sess_id[0]'");


    $canAddOtherChild = FALSE;
    $entry = GFAPI::get_entry($myCredit->gform_entry_id);

    if ($myCredit->is_unlimited_type) {
        $first_name = rgar($entry, '8.3');
        $last_name = rgar($entry, '8.6');
        $fullName = $first_name . " " . $last_name;

        $session_name = $myCredit->is_unlimited_type;
        $canAddOtherChild = TRUE;
    } else if ($myCredit->package_hidden_name == 'team') {
        $fullName = rgar($entry, '16');

        $session_name = $myCredit->package_hidden_name;
    } else {

        $first_name = rgar($entry, '8.3');
        $last_name = rgar($entry, '8.6');
        $fullName = $first_name . " " . $last_name;

        $session_name = $myCredit->package_hidden_name;
        $canAddOtherChild = TRUE;
    }

    $session = $wpdb->get_row("SELECT * FROM " . DB_PACKAGE_SESSIONS . " WHERE session_type = '$session_name'", ARRAY_A);

    $date_first = $myCredit->created_at;
    $date_second = date('Y-m-d H:i:s', strtotime('+5 minutes', strtotime($myCredit->created_at)));

    if ($myCredit->package_hidden_name == 'individual' || $myCredit->package_hidden_name == 'group') {
        $allChilds = $wpdb->get_results("SELECT * FROM " . DB_CHILD_DETAILS . " WHERE user_id = '$user_id' AND (child_type ='group' OR child_type ='individual')");
    } else if ($myCredit->package_hidden_name == 'unlimited') {
        $allChilds = $wpdb->get_results("SELECT * FROM " . DB_CHILD_DETAILS . " WHERE user_id = '$user_id' AND child_type ='unlimited'");
        // if (count($allChilds) >= 1) {
        //     $allChilds = $wpdb->get_results("SELECT * FROM " . DB_CHILD_DETAILS . " WHERE user_id = '$user_id' AND child_type ='unlimited' AND purchase_id='$myCredit->id'");
        // }
    } else {
        $allChilds = $wpdb->get_results("SELECT * FROM " . DB_CHILD_DETAILS . " WHERE user_id = '$user_id' AND child_type ='$myCredit->package_hidden_name'");
    }

    ob_start(); ?>

    <option value=""> -- Choose Child Name -- </option>
    <?php if ($canAddOtherChild) { ?>
        <?php foreach ($allChilds as $allChild) {
            $fullName = $allChild->first_name . " " . $allChild->last_name; ?>
            <option data-id="<?php echo $pur_sess_id[0] . '|' . $session['id']; ?>" value="<?php echo $fullName; ?>"> <?php echo $fullName; ?> </option>
        <?php }
    } else { ?>

        <option data-id="<?php echo $pur_sess_id[0] . '|' . $session['id']; ?>" value="<?php echo $fullName; ?>"> <?php echo $fullName; ?> </option>

<?php }

    $renderedHtml = ob_get_clean();
    echo json_encode(['status' => true, 'renderedHtml' => $renderedHtml]);
    die();
}