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/appointments.php
<?php
// ******************** APPOINTMENTS *************************
require __DIR__ . '/vendor/autoload.php';

// Use the REST API Client to make requests to the Twilio REST API
use Twilio\Rest\Client;

// Your Account SID and Auth Token from twilio.com/console
$account_sid = 'AC64179cdbbfaf94565db9e0ff1cb2cbf8';
$auth_token = 'b2e7db835adc20c3d057a986dbc57811';
// 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 = "+12073869345";
if (!class_exists('WP_List_Table')) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

function render_siab_appointments()
{

    class Siab_appointments_Table extends WP_List_Table
    {
        /**
         * Prepare the items for the table to process
         *
         * @return Void
         */
        public function prepare_items()
        {
            $columns = $this->get_columns();
            $hidden = $this->get_hidden_columns();
            $sortable = $this->get_sortable_columns();

            $data = $this->table_data();
            usort($data, array(&$this, 'sort_data'));

            $perPage = 100;
            $currentPage = $this->get_pagenum();
            $totalItems = count($data);
            $this->set_pagination_args(array(
                'total_items' => $totalItems,
                'per_page' => $perPage,
            ));

            $data = array_slice($data, (($currentPage - 1) * $perPage), $perPage);

            $this->_column_headers = array($columns, $hidden, $sortable);
            $this->items = $data;
        }

        /**
         * Override the parent columns method. Defines the columns to use in your listing table
         *
         * @return Array
         */
        public function get_columns()
        {
            $columns = array(
                'child_id_name' => 'Child Name',
                'grade' => 'Grade',
                'location_name' => 'Location',
                'session_name' => 'Instruction Type',
                'appointment_date' => 'Appointment Date',
                'cust_appointment_time' => 'Appointment Time',
                'appointment_time' => 'Assigned Time',
                'instructor_id' => 'Assigned Instructor',
                'comments' => 'Comments',
                'is_cancelled' => 'Status',
                'status' => 'Modify Status',
                'actions' => 'Actions',
            );

            return $columns;
        }

        /**
         * Define which columns are hidden
         *
         * @return Array
         */
        public function get_hidden_columns()
        {
            return array();
        }

        /**
         * Define the sortable columns
         *
         * @return Array
         */
        public function get_sortable_columns()
        {
            return array(
                'child_id_name' => array('child_id_name', false),
                'grade' => array('grade', false),
                'session_name' => array('session_name', false),
                'instructor_id' => array('instructor_id', false),
                'appointment_time' => array('appointment_time', false),
                'cust_appointment_time' => array('cust_appointment_time', false),
            );
        }

        /**
         * Get the table data
         *
         * @return Array
         */
        private function table_data()
        {
            global $wpdb;

            $where = 'WHERE ';

            // if ((!empty($_GET['start_date']) && !empty($_GET['end_date']) ) || !empty($_GET['status'])) {
            //     $where .=DB_APPOINTMENTS.'.instructor_id IS NULL';

            // }
            if (!empty($_GET['status'])) {
                // $where .=' AND ';
                if ($where != 'WHERE ') {
                    $where .= ' AND ';
                }
                if ($_GET['status'] == "booked") {
                    $where .= DB_APPOINTMENTS . '.is_cancelled = 0 AND ' . DB_APPOINTMENTS . '.instructor_id IS NULL';
                } else if ($_GET['status'] == "cancelled") {
                    $where .= DB_APPOINTMENTS . '.is_cancelled = 1';
                } else if ($_GET['status'] == "except_cancelled") {
                    $where .= DB_APPOINTMENTS . '.is_cancelled != 1';
                } else if ($_GET['status'] == "attended") {
                    $where .= DB_APPOINTMENTS . '.has_attended = 1';
                } else if ($_GET['status'] == "assigned") {
                    $where .= DB_APPOINTMENTS . '.instructor_id IS NOT NULL AND ' . DB_APPOINTMENTS . '.is_approved = 0 AND (' . DB_APPOINTMENTS . '.has_attended IS NULL OR ' . DB_APPOINTMENTS . '.has_attended = 0)';
                } else if ($_GET['status'] == "approved") {
                    $where .= DB_APPOINTMENTS . '.instructor_id IS NOT NULL AND ' . DB_APPOINTMENTS . '.is_approved = 1 AND (' . DB_APPOINTMENTS . '.has_attended IS NULL OR ' . DB_APPOINTMENTS . '.has_attended = 0)';
                }
            } else {
                $where .= DB_APPOINTMENTS . '.is_cancelled != 1';
            }
            // if ((!empty($_GET['start_date']) && !empty($_GET['end_date']) ) && !empty($_GET['status'])) {
            //     if($_GET['status'] !='all'){
            //         $where .=' AND ';
            //     }
            // }
            if (!empty($_GET['start_date']) && !empty($_GET['end_date'])) {
                if ($where != "WHERE ") {
                    $where .= ' AND ';
                }

                $start_date = $_GET['start_date'];
                $end_date = $_GET['end_date'];
                $where .= DB_APPOINTMENTS . '.appointment_date  >= CAST("' . $start_date . '" AS DATE) AND ' . DB_APPOINTMENTS . '.appointment_date  <= CAST("' . $end_date . '" AS DATE)';
            } else {
                if ($where != "WHERE ") {
                    $where .= ' AND ';
                }
                // $dd = date('d') - 1;
                $start_date = date('Y-m-d', strtotime(date('Y-m-d')));
                $end_date = date('Y-m-d', strtotime(date('Y-m-d')));
                $where .= DB_APPOINTMENTS . '.appointment_date  >= CAST("' . $start_date . '" AS DATE) AND ' . DB_APPOINTMENTS . '.appointment_date  <= CAST("' . $end_date . '" AS DATE)';
            }
            if (!empty($_GET['location'])) {
                if ($where != "WHERE ") {
                    $where .= ' AND ';
                }

                $location = $_GET['location'];
                $where .= DB_APPOINTMENTS . '.location_id  = ' . $location . ' ';
            }

            if (!empty($_GET['type'])) {
                if ($where != "WHERE ") {
                    $where .= ' AND ';
                }

                $type = $_GET['type'];
                $where .= DB_APPOINTMENTS . '.session_id  = ' . $type . ' ';
            }

            if ($where == "WHERE ") {
                // $where = '';
                $where1 = $where;
                $where2 = $where;
                // $where = '';

                $where1 .= '(' . DB_APPOINTMENTS . '.instructor_id IS NULL OR ' . DB_APPOINTMENTS . '.session_id=2)';
                $where2 .= DB_APPOINTMENTS . '.instructor_id IS NOT NULL AND ' . DB_APPOINTMENTS . '.session_id != 2';
            } else {
                $where1 = $where;
                $where2 = $where;

                $where1 .= " AND (" . DB_APPOINTMENTS . ".instructor_id IS NULL OR " . DB_APPOINTMENTS . ".session_id=2)";
                $where2 .= " AND " . DB_APPOINTMENTS . '.instructor_id IS NOT NULL AND ' . DB_APPOINTMENTS . '.session_id != 2';
            }


            // $where .= 'SELECT appointment_time FROM '.DB_APPOINTMENTS.' WHERE session_id = 1 AND appointment_time IS NOT NULL AND instructor_id IS NOT NULL)'

            // ONLY_FULL_GROUP_BY,

            $query1 = "SELECT *," . DB_APPOINTMENTS . ".id as appointments_id,cl.name as location_name FROM " . DB_APPOINTMENTS . " JOIN " . DB_USERS . "
				as us ON us.ID = " . DB_APPOINTMENTS . ".customer_id JOIN " . DB_PACKAGE_SESSIONS . " as ps
				ON ps.id = " . DB_APPOINTMENTS . ".session_id JOIN " . DB_COACHING_LOCATIONS . " as cl ON cl.id = " . DB_APPOINTMENTS . ".location_id
				LEFT JOIN ( SELECT MAX(id) as max_id, appointment_id,status
		              FROM " . DB_APPOINTMENT_MODIFY . "
		              GROUP BY  " . DB_APPOINTMENT_MODIFY . ".appointment_id
		             ) as appmodi ON (appmodi.appointment_id = " . DB_APPOINTMENTS . ".id)
				LEFT JOIN " . DB_APPOINTMENT_MODIFY . " as cd ON (cd.id = appmodi.max_id)" . $where1 . " ORDER BY " . DB_APPOINTMENTS . ".id DESC";

            $query2 = "SELECT *,GROUP_CONCAT(" . DB_APPOINTMENTS . ".id) as group_ids," . DB_APPOINTMENTS . ".id as appointments_id,cl.name as location_name FROM " . DB_APPOINTMENTS . " JOIN " . DB_USERS . "
			as us ON us.ID = " . DB_APPOINTMENTS . ".customer_id JOIN " . DB_PACKAGE_SESSIONS . " as ps
			ON ps.id = " . DB_APPOINTMENTS . ".session_id JOIN " . DB_COACHING_LOCATIONS . " as cl ON cl.id = " . DB_APPOINTMENTS . ".location_id
			LEFT JOIN ( SELECT MAX(id) as max_id, appointment_id,status
				  FROM " . DB_APPOINTMENT_MODIFY . "
				  GROUP BY  " . DB_APPOINTMENT_MODIFY . ".appointment_id
				 ) as appmodi ON (appmodi.appointment_id = " . DB_APPOINTMENTS . ".id)
			LEFT JOIN " . DB_APPOINTMENT_MODIFY . " as cd ON (cd.id = appmodi.max_id)" . $where2 . " GROUP BY
			" . DB_APPOINTMENTS . ".location_id," . DB_APPOINTMENTS . ".instructor_id," . DB_APPOINTMENTS . ".appointment_time," . DB_APPOINTMENTS . ".appointment_date," . DB_APPOINTMENTS . ".session_id," . DB_APPOINTMENTS . ".is_cancelled ORDER BY " . DB_APPOINTMENTS . ".id DESC";

            $data1 = $wpdb->get_results($query1, ARRAY_A);
            // echo $wpdb->last_query;
            $data2 = $wpdb->get_results($query2, ARRAY_A);
            // echo $wpdb->last_query;
            // $new_data_arr = [];

            foreach ($data2 as $key1 => $item) {
                global $wpdb;
                $appointment_id =  $item['appointments_id'];
                $instructorIds = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE appt_id = '$appointment_id' ");

                // $query = "SELECT child_id_name,comments FROM " . DB_APPOINTMENTS . "  JOIN " . DB_APPOINTMENT_INSTRUCTORS . "
                // as ins ON ins.appt_id = " . DB_APPOINTMENTS . ".id 
                // 	WHERE ins.instructor_id = " . $item['instructor_id'] . " AND
                // 	location_id = " . $item['location_id'] . " AND appointment_date = '" . $item['appointment_date'] . "'
                // 	AND session_id = 1 AND appointment_time ='" . $item['appointment_time'] . "'";
                $query = "SELECT child_id_name,comments FROM " . DB_APPOINTMENTS . "
                    WHERE instructor_id = " . $item['instructor_id'] . " AND
                    location_id = " . $item['location_id'] . " AND appointment_date = '" . $item['appointment_date'] . "'
                    AND session_id = 1 AND appointment_time ='" . $item['appointment_time'] . "'";



                $childrens = $wpdb->get_results($query, ARRAY_A);
                $child_data = "";
                $comment_data = "";
                // var_dump(count($childrens));
                if (count($childrens) > 1) {

                    $child_data = "<div style='margin-left:8px'><ul style='list-style-type:circle'>";
                    $comment_data = "<div style='margin-left:8px'><ul style='list-style-type:circle'>";
                    foreach ($childrens as $key2 => $child) {
                        $child_data .= "<li>" . $child['child_id_name'] . "</li>";

                        $comment_data .= "<li>" . $child['comments'] . "</li>";
                    }
                    $child_data .= "</ul></div>";
                    $comment_data .= "</ul></div>";
                    $data2[$key1]['child_id_name'] = $child_data;
                    $data2[$key1]['comments'] = $comment_data;

                    // $data[$key1]['comments'] = $comment_data;

                }
                array_push($data1, $data2[$key1]);
                // }
            }

            function comparator($object1, $object2)
            {
                return $object1['appointments_id'] < $object2['appointments_id'];
            }
            usort($data1, 'comparator');

            // $data3 = array();
            // $current = array();
            // foreach ($data1 as $key => $value) {
            //     if(!in_array($value['appointments_id'],$current)){
            //         array_push($data3,$value);
            //     }
            //     array_push($current,$value['appointments_id']);
            // }

            return $data1;
        }

        /**
         * Define what data to show on each column of the table
         *
         * @param  Array $item        Data
         * @param  String $column_name - Current column name
         *
         * @return Mixed
         */
        public function column_default($item, $column_name)
        {
            global $wpdb;
            $ordinal_map = [];
            for ($i = 1; $i <= 50; $i++) {
                if ($i % 10 === 1 && $i !== 11) {
                    $ordinal = $i . 'st';
                } elseif ($i % 10 === 2 && $i !== 12) {
                    $ordinal = $i . 'nd';
                } elseif ($i % 10 === 3 && $i !== 13) {
                    $ordinal = $i . 'rd';
                } else {
                    $ordinal = $i . 'th';
                }
                $ordinal_map[$i] = $ordinal;
            }
            switch ($column_name) {

                case 'child_id_name':
                    if ($item['appointmentPlatform'] == 1) {
                        return $item[$column_name] . " <b>(SHOOTIN SCHOOL)</b>";
                    } else {
                        return $item[$column_name] . " <b>(BWC)</b>";
                    }
                case 'comments':
                case 'location_name':
                case 'session_name':
                    return $item[$column_name];
                case 'cust_appointment_time':
                case 'appointment_time':
                    if (!empty($item[$column_name])) {
                        $cust_split = explode(' - ', $item[$column_name]);
                        $app_time = date('g:i A', strtotime($cust_split[0])) . " - " . date('g:i A', strtotime($cust_split[1]));
                        return $app_time;
                    } else {
                        return '-';
                    }

                case 'grade':

                    $child = explode(' ', $item['child_id_name']);
                    if (count($child) > 1) {
                        $query = "SELECT * FROM " . DB_CHILD_DETAILS . " WHERE first_name='" . $child[0] . "' AND last_name='" . $child[1] . "' AND user_id = " . $item['customer_id'];
                        $children = $wpdb->get_row($query, ARRAY_A);

                        if ($children) {
                            return $children['grade'];
                            // break;
                        }
                    } else if (count($child) > 0) {
                        $query = "SELECT * FROM " . DB_CHILD_DETAILS . " WHERE first_name='" . $child[0] . "' AND user_id = " . $item['customer_id'];
                        $children = $wpdb->get_row($query, ARRAY_A);

                        if ($children) {
                            return $children['grade'];
                            // break;
                        }
                    }

                    return '';
                    // break;
                case 'appointment_date':
                    $appointment_id =  $item['appointments_id'];
                    $instructorIds = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE appt_id = '$appointment_id' ");
                    return date('l, F d Y ', strtotime($item[$column_name]));
                case 'is_cancelled':
                    $appointment_id =  $item['appointments_id'];
                    $instructorIds = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE appt_id = '$appointment_id' ");
                    if ($item['is_approved'] == 0 && $item['is_cancelled'] == 0 && count($instructorIds) > 0) {
                        return "Instructor Assigned";
                    } else if ($item['is_cancelled'] == 0) {
                        $appointment_id =  $item['appointments_id'];
                        $instructorIds = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE appt_id = '$appointment_id' ");
                        if (count($instructorIds) == 0) {
                            return "Booked";
                        } else if ($item['has_attended'] != null && $item['has_attended'] == 1) {
                            return "Attended";
                        } else if ($item['has_attended'] != null && $item['has_attended'] == 0) {
                            return "Not Attended";
                        } else if ($item['is_approved'] == 1) {
                            return " Approved";
                        } else {
                            return " Instructor Assigned";
                        }
                    } else {
                        return "Cancelled";
                    }
                case 'instructor_id':
                    $appointment_id =  $item['appointments_id'];
                    $instructorIds = $wpdb->get_results("SELECT instructor_id FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE appt_id = '$appointment_id' ");

                    $name = "";
                    if (count($instructorIds) > 0) {
                        foreach ($instructorIds as $instructors) {
                            $user = get_user_by('id', $instructors->instructor_id);
                            $name .=  nl2br($user->display_name . "," . "\n");
                        }
                        return rtrim($name, ',');
                    } else {
                        return "- No Instructor Assigned -";
                    }
                case 'status':
                    if ($item['status'] != null) {
                        if ($item['status'] == 0) {
                            return "Request sent";
                        } else if ($item['status'] == 1) {
                            return " Request Approved";
                        } else {
                            return "Request Rejected";
                        }
                    } else {
                        return '-';
                    }
                default:
                    return print_r($item, true);
            }

            $postNumber++;
        }

        function column_actions($item)
        {

            $actions = array();

            if ($item["is_cancelled"] == 1 || $item['has_attended'] != null && in_array($item['has_attended'], [0, 1])) {
                echo '- Not Available -';
            } else if ($item["is_cancelled"] == 0) {
                if ($item['instructor_id'] && $user = get_user_by('id', $item['instructor_id'])) {
                    if ($item["session_id"] == 3 && $item["team_child_details"] != "") { //Team
                        if (($item['status'] == 0) && ($item['status'] != "")) {
                            if ($item['session_name'] == "Individual Instruction") {
                                $actions = array(
                                    'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . $item["appointments_id"] . ')" >Assign Instructor</button>'),
                                    'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time</button>'),
                                    'Accept Time Change' => sprintf('<button class="btn btn-success btn-xs" onclick="openappointmentApproveModal(' . $item["appointments_id"] . ')" >Accept Time Change</button>'),
                                    'Reject Time Change' => sprintf('<button class="btn btn-danger btn-xs" onclick="openappointmentRejectModal(' . $item["appointments_id"] . ')" >Reject Time Change</button>'),
                                    'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item["appointments_id"] . ')">Cancel</button>'),
                                    'View Team Details' => sprintf('<button class="btn btn-info btn-xs" onclick="viewTeamDetailsModel(' . $item["appointments_id"] . ')">View</button>'),
                                );
                            } else {
                                $actions = array(
                                    'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . $item["appointments_id"] . ')" >Assign Instructor</button>'),
                                    'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time</button>'),
                                    'Accept Time Change' => sprintf('<button class="btn btn-success btn-xs" onclick="openappointmentApproveModal(' . $item["appointments_id"] . ')" >Accept Time Change</button>'),
                                    'Reject Time Change' => sprintf('<button class="btn btn-danger btn-xs" onclick="openappointmentRejectModal(' . $item["appointments_id"] . ')" >Reject Time Change</button>'),
                                    'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item["appointments_id"] . ')">Cancel</button>'),
                                    'View Team Details' => sprintf('<button class="btn btn-info btn-xs" onclick="viewTeamDetailsModel(' . $item["appointments_id"] . ')">View</button>'),
                                );
                            }
                        } else {
                            if ($item['session_name'] == "Individual Instruction") {
                                $actions = array(
                                    'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . $item["appointments_id"] . ')" >Assign Instructor</button>'),
                                    'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time</button>'),
                                    'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item["appointments_id"] . ')">Cancel</button>'),
                                    'View Team Details' => sprintf('<button class="btn btn-info btn-xs" onclick="viewTeamDetailsModel(' . $item["appointments_id"] . ')">View</button>'),
                                );
                            } else {
                                $actions = array(
                                    'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . $item["appointments_id"] . ')" >Assign Instructor</button>'),
                                    'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time</button>'),
                                    'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item["appointments_id"] . ')">Cancel</button>'),
                                    'View Team Details' => sprintf('<button class="btn btn-info btn-xs" onclick="viewTeamDetailsModel(' . $item["appointments_id"] . ')">View</button>'),
                                );
                            }
                        }
                    } else {

                        if ($item['group_ids']) {
                            if ($item['session_name'] == "Individual Instruction") {
                                $actions = array(
                                    'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick=openAssignModalNew("' . $item['group_ids'] . '")>Assign Instructor</button>'),
                                    'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time10</button>'),
                                    'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick=openCancelModal("' . $item['group_ids'] . '")>Cancel</button>'),
                                );
                            } else {
                                $actions = array(
                                    'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick=openAssignModalNew("' . $item['group_ids'] . '")>Assign Instructor</button>'),
                                    'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time</button>'),
                                    'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick=openCancelModal("' . $item['group_ids'] . '")>Cancel</button>'),
                                );
                            }
                        } else {
                            if ($item['session_name'] == "Individual Instruction") {
                                $actions = array(
                                    'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . $item["appointments_id"] . ')" >Assign Instructor</button>'),
                                    'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time</button>'),
                                    'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item["appointments_id"] . ')">Cancel</button>'),
                                );
                            } else {
                                $actions = array(
                                    'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . $item["appointments_id"] . ')" >Assign Instructor</button>'),
                                    'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time7</button>'),
                                    'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item["appointments_id"] . ')">Cancel</button>'),
                                );
                            }
                        }
                    }
                } else {
                    if ($item["session_id"] == 3 && $item["team_child_details"] != "") { //Team
                        if ($item['session_name'] == "Individual Instruction") {
                            $actions = array(
                                'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . $item["appointments_id"] . ')" >Assign Instructor</button>'),
                                // 'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time6</button>'),
                                'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item["appointments_id"] . ')">Cancel</button>'),
                                'View Team Details' => sprintf('<button class="btn btn-info btn-xs" onclick="viewTeamDetailsModel(' . $item["appointments_id"] . ')">View</button>'),
                            );
                        } else {
                            $actions = array(
                                'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . $item["appointments_id"] . ')" >Assign Instructor</button>'),
                                // 'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time5</button>'),
                                'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item["appointments_id"] . ')">Cancel</button>'),
                                'View Team Details' => sprintf('<button class="btn btn-info btn-xs" onclick="viewTeamDetailsModel(' . $item["appointments_id"] . ')">View</button>'),
                            );
                        }
                    } else {
                        if ($item['group_ids']) {
                            if (($item['status'] == 0) && ($item['status'] != "")) {
                                if ($item['session_name'] == "Individual Instruction") {
                                    $actions = array(
                                        'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . strval($item["group_ids"]) . ')">Assign Instructor</button>'),
                                        'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item['group_ids'] . ')" >Modify Appxointment Time</button>'),
                                        'Accept Time Change' => sprintf('<button class="btn btn-success btn-xs" onclick="openappointmentApproveModal(' . $item["appointments_id"] . ')" >Accept Time Change' . $item["status"] . '</button>'),
                                        'Reject Time Change' => sprintf('<button class="btn btn-danger btn-xs" onclick="openappointmentRejectModal(' . $item["appointments_id"] . ')" >Reject Time Change</button>'),
                                        'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item['group_ids'] . ')">Cancel</button>'),
                                    );
                                } else {
                                    $actions = array(
                                        'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . strval($item["group_ids"]) . ')">Assign Instructor</button>'),
                                        // 'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item['group_ids'] . ')" >Modify Appxointment Time</button>'),
                                        'Accept Time Change' => sprintf('<button class="btn btn-success btn-xs" onclick="openappointmentApproveModal(' . $item["appointments_id"] . ')" >Accept Time Change' . $item["status"] . '</button>'),
                                        'Reject Time Change' => sprintf('<button class="btn btn-danger btn-xs" onclick="openappointmentRejectModal(' . $item["appointments_id"] . ')" >Reject Time Change</button>'),
                                        'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item['group_ids'] . ')">Cancel</button>'),
                                    );
                                }
                            } else {
                                if ($item['session_name'] == "Individual Instruction") {
                                    $actions = array(
                                        'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . strval($item["group_ids"]) . ')">Assign Instructor</button>'),
                                        'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item['group_ids'] . ')" >Modify Appointment Time</button>'),
                                        'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item['group_ids'] . ')">Cancel</button>'),
                                    );
                                } else {
                                    $actions = array(
                                        'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . strval($item["group_ids"]) . ')">Assign Instructor</button>'),
                                        'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item['group_ids'] . ')" >Modify Appointment Time</button>'),
                                        'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item['group_ids'] . ')">Cancel</button>'),
                                    );
                                }
                            }
                        } else {
                            if (($item['status'] == 0) && ($item['status'] != "")) {
                                if ($item['session_name'] == "Individual Instruction") {
                                    $actions = array(
                                        'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . $item["appointments_id"] . ')" >Assign Instructor</button>'),
                                        'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time</button>'),
                                        'Accept Time Change' => sprintf('<button class="btn btn-success btn-xs" onclick="openappointmentApproveModal(' . $item["appointments_id"] . ')" >Accept Time Change</button>'),
                                        'Reject Time Change' => sprintf('<button class="btn btn-danger btn-xs" onclick="openappointmentRejectModal(' . $item["appointments_id"] . ')" >Reject Time Change</button>'),
                                        'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item["appointments_id"] . ')">Cancel</button>'),
                                    );
                                } else {
                                    $actions = array(
                                        'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . $item["appointments_id"] . ')" >Assign Instructor</button>'),
                                        // 'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time</button>'),
                                        'Accept Time Change' => sprintf('<button class="btn btn-success btn-xs" onclick="openappointmentApproveModal(' . $item["appointments_id"] . ')" >Accept Time Change</button>'),
                                        'Reject Time Change' => sprintf('<button class="btn btn-danger btn-xs" onclick="openappointmentRejectModal(' . $item["appointments_id"] . ')" >Reject Time Change</button>'),
                                        'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item["appointments_id"] . ')">Cancel</button>'),
                                    );
                                }
                            } else {
                                if ($item['session_name'] == "Individual Instruction") {
                                    $actions = array(
                                        'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . $item["appointments_id"] . ')" >Assign Instructor</button>'),
                                        'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time</button>'),
                                        'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item["appointments_id"] . ')">Cancel</button>'),
                                    );
                                } else {
                                    $actions = array(
                                        'Assign Instructor' => sprintf('<button class="btn btn-success btn-xs" onclick="openAssignModalNew(' . $item["appointments_id"] . ')" >Assign Instructor</button>'),
                                        'Modify Appointment Time' => sprintf('<button class="btn btn-primary btn-xs" onclick="openModifyAppointmentTimeModal(' . $item["appointments_id"] . ')" >Modify Appointment Time</button>'),
                                        'Cancel' => sprintf('<button class="btn btn-danger btn-xs" onclick="openCancelModal(' . $item["appointments_id"] . ')">Cancel</button>'),
                                    );
                                }
                            }
                        }
                    }
                }
            }

            return sprintf(
                // '%1$s <span style="color:silver">(Edit:%2$s)</span>%3$s',
                /*$1%s*/
                // $item['title'],
                /*$2%s*/
                // $item['id'],
                /*$3%s*/
                $this->row_actions($actions)
            );
        }

        /**
         * Allows you to sort the data by the variables set in the $_GET
         *
         * @return Mixed
         */
        private function sort_data($a, $b)
        {
            // Set defaults
            $orderby = 'id';
            $order = 'asc';

            // If orderby is set, use this as the sort column
            if (!empty($_GET['orderby'])) {
                $orderby = $_GET['orderby'];
            }

            // If order is set use this as the order
            if (!empty($_GET['order'])) {
                $order = $_GET['order'];
            }

            if ($orderby == 'instructor_id') {

                if ($a['instructor_id'] && $user = get_user_by('id', $a['instructor_id'])) {
                    if ($b['instructor_id'] && $user2 = get_user_by('id', $b['instructor_id'])) {
                        $result = strcmp($user->display_name, $user2->display_name);
                    } else {
                        $result = 1;
                    }
                } else {
                    $result = -1;
                }
            } else if ($orderby == 'appointment_time') {
                $start1 = explode(' - ', $a['appointment_time']);
                $start2 = explode(' - ', $b['appointment_time']);

                $date1 = strtotime($a['appointment_date']);
                $date2 = strtotime($b['appointment_date']);

                $result = strcmp($date1, $date2);

                if ($result == 0) {
                    $result = strcmp(strtotime($start1[0]), strtotime($start2[0]));
                } else {
                    $result = strcmp($date1, $date2);
                }
            } else if ($orderby == 'cust_appointment_time') {
                $start1 = explode(' - ', $a['cust_appointment_time']);
                $start2 = explode(' - ', $b['cust_appointment_time']);

                $date1 = strtotime($a['cust_appointment_time']);
                $date2 = strtotime($b['cust_appointment_time']);

                $result = strcmp($date1, $date2);

                if ($result == 0) {
                    $result = strcmp(strtotime($start1[0]), strtotime($start2[0]));
                } else {
                    $result = strcmp($date1, $date2);
                }
            } else {
                $result = strcmp($a[$orderby], $b[$orderby]);
            }

            if ($order == 'desc') {
                return -$result;
            }

            return $result;
        }
    }
    $importedListTable = new Siab_appointments_Table();
    $importedListTable->prepare_items();

    //get all the locations
    global $wpdb;
    $locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . 'WHERE (`platform` = 1 OR `platform` = 3)', ARRAY_A);

    $instruction_types = $wpdb->get_results("SELECT * FROM " . DB_PACKAGE_SESSIONS, ARRAY_A);

    $permittedLocs = array();
    foreach ($locations as $loc) {
        $permittedLocs[] = array('id' => $loc['id'], "name" => $loc['name']);
    }
    $apptstatus = 'except_cancelled';
    //$start_date ='';
    //$end_date ='';
    $apptlocation = '';
    $apptype = '';
    $dd = date('d') - 1;

    if (!empty($_GET['status'])) {
        $apptstatus = $_GET['status'];
    }
    if (!empty($_GET['start_date'])) {
        $start_date = $_GET['start_date'];
    } else {
        $start_date = date('Y-m-d');
    }
    if (!empty($_GET['end_date'])) {
        $end_date = $_GET['end_date'];
    } else {
        $end_date = date('Y-m-d');
    }
    if (!empty($_GET['location'])) {
        $apptlocation = $_GET['location'];
    }
    if (!empty($_GET['type'])) {
        $apptype = $_GET['type'];
    }

?>

    <div class="wrap">
        <style type="text/css">
            #actions {
                width: 16%;
            }

            .widefat {
                border-spacing: 0;
                width: 90%;
                clear: both;
                margin-left: 58px;
                /* align-content: center; */
            }

            .displaying-num {
                display: none !important;
            }
        </style>
        <div class="css_loader">Loading&#8230;</div>
        <div class="alert alert-info" role="alert">
            <h3> Appointments Management</h3>
            <button class="add-new-h2 btn btn-success send_approval_nootifications" onclick="SendaprovalNotifications()" type="button">Send Assigned Notifications </button>
        </div>
        <div class="container" style="margin-top:19px;width:90%">
            <label>Status</label>
            <select name="status" id="appt_status">
                <option value="all" <?php if ($apptstatus == 'all') {
                                        echo "selected";
                                    } ?>> All</option>
                <option value="booked" <?php if ($apptstatus == 'booked') {
                                            echo "selected";
                                        } ?>> Booked</option>
                <option value="assigned" <?php if ($apptstatus == 'assigned') {
                                                echo "selected";
                                            } ?>> Assigned</option>
                <option value="approved" <?php if ($apptstatus == 'approved') {
                                                echo "selected";
                                            } ?>> Approved</option>
                <option value="attended" <?php if ($apptstatus == 'attended') {
                                                echo "selected";
                                            } ?>> Attended</option>
                <option value="cancelled" <?php if ($apptstatus == 'cancelled') {
                                                echo "selected";
                                            } ?>> Cancelled</option>
                <option value="except_cancelled" <?php if ($apptstatus == 'except_cancelled') {
                                                        echo "selected";
                                                    } ?>> All Except Cancelled</option>
            </select>
            <label>Start Date</label>
            <input type="date" value="<?php echo $start_date; ?>" name="start_date" id="start_date" placeholder="Start Date">
            <label>End Date</label>
            <input type="date" value="<?php echo $end_date; ?>" name="end_date" id="end_date" placeholder="End Date">
            <label>Location</label>
            <select name="location" id="appt_location">
                <option value=""> -- All Locations -- </option>
                <?php foreach ($permittedLocs as $key => $value) { ?>
                    <option value=<?= $value['id'] ?> <?php if ($apptlocation == $value['id']) {
                                                            echo "selected";
                                                        } ?>> <?= $value['name'] ?></option>
                <?php } ?>
            </select>
            <label>Instruction Type</label>
            <select name="type" id="appt_type">
                <option value=""> -- All Types -- </option>
                <?php foreach ($instruction_types as $key => $value) { ?>
                    <option value=<?= $value['id'] ?> <?php if ($apptype == $value['id']) {
                                                            echo "selected";
                                                        } ?>> <?= $value['session_name'] ?></option>
                <?php } ?>
            </select>
            <input class="btn btn-primary btn-sm" type="button" value="Apply" onclick="ApplyFilter()">
            <a class="btn btn-default btn-sm" href="admin.php?page=siab-appointments"> Reset</a>
            <hr>

            <div class="pull-right">
                <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#openMergeAppointmentsModal">
                    Merge Sessions
                </button>
                <a class="btn btn-success btn-sm" href="admin.php?page=make_an_appointment"> Make an Appointment </a>
            </div>

        </div>
        <?php $importedListTable->display(); ?>
    </div>

    <div class="modal" id="appointmentModal" role="dialog">
        <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Cancel Appointment</h4>
                </div>
                <div class="modal-body">
                    <div class="cancel-msg"></div>
                    <p>Are you sure want to cancel this Customer Appointment ?</p>
                    <div id="cancelmsg"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" id="cancelbtn" data-appointment_id="" class="btn btn-primary" onclick="cancelAppoint(this)">Yes</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal" id="appointmentApproveModal" role="dialog">
        <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Approve Appointment Time Change</h4>
                </div>
                <div class="modal-body">
                    <div class="cancel-msg"></div>
                    <p>Are you sure want to approve the time change ?</p>
                    <div id="cancelmsg"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" id="aprveTime" data-appointment_id="" class="btn btn-primary" onclick="approveTimeAppoint(this)">Yes</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal" id="appointmentRejectModal" role="dialog">
        <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Reject Appointment Time Change</h4>
                </div>
                <div class="modal-body">
                    <div class="cancel-msg"></div>
                    <p>Are you sure want to reject time change ?</p>
                    <div id="cancelmsg"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" id="rejectTime" data-appointment_id="" class="btn btn-primary" onclick="rejectTimeAppoint(this)">Yes</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
                </div>
            </div>
        </div>
    </div>


    <!-- Instructor Assign Modal start-->
    <div id="assignModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Assign an Instructor</h4>
                </div>
                <div class="modal-body" id="appendAssignDiv">
                    <!-- Append Here -->
                </div>


                <div class="modal-footer">
                    <button type="button" onclick="assignInstructor_new()" class="btn btn-primary">Assign</button>
                    <button type="button" class="btn btn-info" data-dismiss="modal">Close</button>
                </div>
            </div>

        </div>
    </div>
    <!-- Instructor Assign Modal End-->

    <!-- Admin making appointment time change -->
    <div id="modifyAppointmentTimeModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Modify Appointment Time </h4>
                </div>
                <div class="appendDiv">
                    <!-- Append Here -->
                </div>
            </div>

        </div>
    </div>
    <!-- Admin making appointment time change -->

    <div class="modal fade" id="addChildDetailsModal" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title"> View children team personal details</h4>
                </div>
                <div class="modal-body" id="appendChildDetailsDiv">
                    <!-- Append Here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" onclick="addChildDetails();">Update</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Merge Sessions Modal start-->
    <?php
    global $wpdb;
    $query = "SELECT appts.child_id_name,appts.appointment_date, appts.appointment_time, GROUP_CONCAT(appts.id SEPARATOR '|') AS grouped_appts_ids, COUNT(appts.id) as occurance, ps.session_name FROM " . DB_APPOINTMENTS . " AS appts JOIN " . DB_PACKAGE_SESSIONS . " as ps ON ps.id = appts.session_id  JOIN " . DB_APPOINTMENT_INSTRUCTORS . "
    as ins ON ins.appt_id = appts.id  WHERE  ps.session_type = 'group' AND appts.appointment_date >='" . $start_date . "' AND appts.appointment_date <='" . $end_date . "' AND appts.is_cancelled = 0 AND appts.has_attended IS NULL AND ins.instructor_id IS NOT NULL GROUP BY appts.id ORDER BY appts.appointment_date DESC";
    // $query = "SELECT appts.child_id_name,appts.appointment_date, appts.appointment_time, GROUP_CONCAT(appts.id SEPARATOR '|') AS grouped_appts_ids, COUNT(appts.id) as occurance, ps.session_name FROM " . DB_APPOINTMENTS . " AS appts JOIN " . DB_PACKAGE_SESSIONS . " as ps ON ps.id = appts.session_id WHERE appts.is_cancelled = 0 AND ps.session_type = 'personal' AND appts.appointment_date >= '" . $start_date . "' AND appts.appointment_date <= '" . $end_date . "' AND appts.has_attended IS NULL AND appts.id NOT IN (" . $appointment_ids . ") GROUP BY appts.id ORDER BY appts.id DESC";
    $fetchAppts = $wpdb->get_results($query, ARRAY_A);
    // echo "<pre>";
    // print_r($query);
    ?>

    <div id="openMergeAppointmentsModal" class="modal fade" role="dialog">
        <div class="css_loader">Loading&#8230;</div>
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Merge Booked Sessions</h4>
                </div>
                <form id="mergeSessionsFormId">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h4>Choose an Session</h4>
                                <select name="sel_first_session" id="sel_first_session" onchange="first_session_change();">
                                    <option value=""> -- Choose an Session -- </option>
                                    <?php foreach ($fetchAppts as $single) { ?>
                                        <option value="<?php echo $single['grouped_appts_ids'] . '|' . $single['occurance']; ?>">
                                            <?php
                                            $split_time = explode(' - ', $single['appointment_time']);
                                            $current_app_time = date('g:i A', strtotime($split_time[0])) . " - " . date('g:i A', strtotime($split_time[1]));

                                            ?>
                                            <?php echo $single['child_id_name']; ?> - <?php echo date('l, F d Y ', strtotime($single['appointment_date'])); ?>
                                        </option>
                                    <?php } ?>
                                </select>

                                <br /><br />

                                <div id="f_add_details"></div>
                            </div>
                            <div class="col-md-6" id="appendMergeDiv">
                                <!-- Append Here -->
                                <h4>Choose Session to be Merged</h4>
                            </div>
                        </div>

                        <div id="insDiv">
                            <!-- Append Instructor Selection -->
                        </div>
                        <div id="AssignMessage2">

                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" onclick="mergeSessions()" class="btn btn-primary">Merge Sessions</button>
                        <button type="button" class="btn btn-info" data-dismiss="modal">Close</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <!-- Merge Sessions Modal End-->

    <?php }
add_action('wp_ajax_nopriv_cancelapproveAppoint', 'cancelapproveAppoint');
add_action('wp_ajax_cancelapproveAppoint', 'cancelapproveAppoint');
function cancelapproveAppoint()
{
    global $wpdb;
    $appointment_id = $_POST['appointment_id'];

    $appointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id =" . $appointment_id, ARRAY_A);
    $purchase_id = $appointment['purchase_credits_id'];
    $cancelled_by = $_POST['cancelled_by'];

    $user_id = $appointment['customer_id'];
    $purchase_id = $appointment['purchase_credits_id'];

    $statusFlag = false;
    $charged = false;
    if (isset($_POST['savedCard_id2'])) {
        $encrypted_savedCard_id = $_POST['savedCard_id2'];
        $savedCard_id = my_simple_crypt($encrypted_savedCard_id, 'd');

        require_once YITH_WCSTRIPE_DIR . 'includes/class-yith-stripe-api.php';
        require_once YITH_WCSTRIPE_DIR . 'includes/class-yith-stripe-gateway.php';

        $fetch_yith_gateway = new YITH_WCStripe_Gateway();
        $fetch_yith_gateway->init_stripe_sdk();
        // $fetch_if_test_or_live = $fetch_yith_gateway->env;

        // // N.B : For testing purposes ONLY
        // if($fetch_if_test_or_live == 'live'){
        //     echo "You are running on LIVE Stripe Instance";
        //     return;
        // }
        // // N.B : For testing purposes ONLY

        // $private_key = $fetch_yith_gateway->private_key;

        $customer = YITH_WCStripe()->get_customer()->get_usermeta_info($user_id);

        $response = YITH_Stripe_API::charge(array(
            "amount" => 3500,
            "currency" => "usd",
            "customer" => $customer['id'],
            "source" => $savedCard_id,
            "description" => "Charged for Not Attending Booked Session",
        ));

        if ($response['status'] == 'succeeded') {

            $args = array(
                'appointment_id' => $appointment_id,
                'user_id' => $user_id,
                'stripe_charge_id' => $response['id'],
                'charge_amount' => '$35',
                'charge_status' => 'Manual Charge Success',
                'remarks' => "Charged for Not Attending Booked Session",
            );

            $sqlInsert = $wpdb->insert(DB_CANCELLATION_CHARGE, $args);

            $statusFlag = true;
            $charged = true;
        }
    } else {
        $statusFlag = true;
    }

    $result = $wpdb->get_row("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE id =" . $purchase_id, ARRAY_A);
    if ($result['is_unlimited_type'] == null) {
        $credit = $result['credits'] + 1;
        $wpdb->update(DB_WC_GF_CUSTOMER_PURCHASES, array('credits' => $credit), array('id' => $purchase_id));
    }
    $query = "SELECT * FROM " . DB_APPOINTMENTS . " JOIN " . DB_USERS . "
		as us ON us.ID = " . DB_APPOINTMENTS . ".customer_id JOIN " . DB_PACKAGE_SESSIONS . " as ps
		ON ps.id = " . DB_APPOINTMENTS . ".session_id WHERE " . DB_APPOINTMENTS . ".id ='" . $appointment_id . "' GROUP BY " . DB_APPOINTMENTS . ".id";
    $data = $wpdb->get_row($query, ARRAY_A);

    $instructor = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = " . $appointment['instructor_id']);
    $instructor_name = $instructor->display_name;
    $wpdb->update(DB_APPOINTMENTS, array('is_cancelled' => 0, 'instructor_id' => null, 'assigned_instructor' => null), array('id' => $appointment_id));

    echo json_encode(['status' => true, 'message' => 'Appointment has been Rejected']);

    die();
}
add_action('wp_ajax_nopriv_approveAppoint', 'approveAppoint');
add_action('wp_ajax_approveAppoint', 'approveAppoint');
function approveAppoint()
{

    global $wpdb;
    $appointment_id = $_POST['appointment_id'];
    $user_id = get_current_user_id();
    $appointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id =" . $appointment_id, ARRAY_A);
    $purchase_id = $appointment['purchase_credits_id'];
    $cancelled_by = $_POST['cancelled_by'];
    $result = $wpdb->get_row("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE id =" . $purchase_id, ARRAY_A);
    // if ($result['is_unlimited_type'] == null) {
    //     $credit = $result['credits'];
    //     $wpdb->update(DB_WC_GF_CUSTOMER_PURCHASES, array('credits' => $credit), array('id' => $purchase_id));
    // }
    $query = "SELECT * FROM " . DB_APPOINTMENTS . " JOIN " . DB_USERS . "
	    as us ON us.ID = " . DB_APPOINTMENTS . ".customer_id JOIN " . DB_PACKAGE_SESSIONS . " as ps
		ON ps.id = " . DB_APPOINTMENTS . ".session_id  JOIN " . DB_APPOINTMENT_INSTRUCTORS . "
        as ins ON ins.appt_id = " . DB_APPOINTMENTS . ".id  WHERE " . DB_APPOINTMENTS . ".id ='" . $appointment_id . "' GROUP BY " . DB_APPOINTMENTS . ".id";
    $data = $wpdb->get_row($query, ARRAY_A);

    $instructor = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = " . $user_id);
    $instructor_name = $instructor->display_name;
    $wpdb->update(DB_APPOINTMENTS, array('is_cancelled' => 0, 'is_approved' => 1), array('id' => $appointment_id));
    $wpdb->update(DB_APPOINTMENT_INSTRUCTORS, array('is_approved' => 1), array("instructor_id" => $user_id, "appt_id" => $appointment_id));
    $location = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id = " . $data['location_id']);
    $location_name = $location->name;
    // Instructor Email
    // $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 4", ARRAY_A);
    // $inst_msg = $email_instructor['body'];
    // $inst_subject = $email_instructor['subject'];
    // $inst_email = $instructor->user_email;

    // $location = $wpdb->get_row("SELECT * FROM ".DB_COACHING_LOCATIONS." WHERE id = ".$data['location_id']);
    // $location_name = $location->name;
    // $split_time = explode(' - ',$data['appointment_time']);
    // $current_app_time = date('g:i A',strtotime($split_time[0]))." - ".date('g:i A',strtotime($split_time[1]));

    // preg_match_all('/{(.*?)}/', $inst_msg, $matches);

    // if (in_array("customer_name", $matches[1])) {
    //     $inst_msg = str_replace('{customer_name}', $data['display_name'], $inst_msg);
    // }
    // if (in_array("appointment_date", $matches[1])) {
    //     $inst_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($data['appointment_date'])), $inst_msg);
    // }
    // if (in_array("appointment_time", $matches[1])) {
    //     $inst_msg = str_replace('{appointment_time}', $current_app_time, $inst_msg);
    // }
    // if (in_array("instructor_name", $matches[1])) {
    //     $inst_msg = str_replace('{instructor_name}', $instructor_name, $inst_msg);
    // }
    // if (in_array("location_name", $matches[1])) {
    //     $inst_msg = str_replace('{location_name}', $location_name, $inst_msg);
    // }

    // $headers[] = 'Content-Type: text/html; charset=UTF-8';
    // $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
    // if($email_instructor['notify_via_email'] == 1){
    //     wp_mail($inst_email, $inst_subject, $inst_msg, $headers);
    // }

    // if($email_instructor['notify_via_sms'] == 1){
    //     $inst_msg_sms=$inst_msg;
    //     $inst_msg_sms = str_replace('<br>',"\n",$inst_msg_sms);
    //     $inst_msg_sms = str_replace('&nbsp'," ",$inst_msg_sms);
    //     preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
    //     $phone = get_user_meta( $user_id, 'billing_billing_phone');
    //     if(count($phone)>0){
    //         foreach($sms_matches[0] as $match){
    //             $inst_msg_sms = str_replace($match,'',$inst_msg_sms);
    //         }
    //         //Twilio message
    //         $args = array(
    //             'number_to'=> fetchCountryMobileCode($user_id) . $phone[0],
    //             'message' => $inst_msg_sms
    //         );
    //         twl_send_sms( $args );
    //     }
    // }

    // Customer Email
    $email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 40", ARRAY_A);
    $cust_msg = $email_user['body'];
    $cust_email = $data['user_email'];
    $cust_subject = $email_user['subject'];

    preg_match_all('/{(.*?)}/', $cust_msg, $matches);
    $split_time = explode(' - ', $data['cust_appointment_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}',  $data['display_name'], $cust_msg);
    }
    if (in_array("appointment_date", $matches[1])) {
        $cust_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($data['appointment_date'])), $cust_msg);
    }
    if (in_array("appointment_time", $matches[1])) {
        $cust_msg = str_replace('{appointment_time}', $current_app_time, $cust_msg);
    }
    if (in_array("instructor_name", $matches[1])) {
        $cust_msg = str_replace('{instructor_name}', $instructor_name, $cust_msg);
    }

    if (in_array("location_name", $matches[1])) {
        $cust_msg = str_replace('{location_name}', $location_name, $cust_msg);
    }

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

    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($data['customer_id'], 'billing_billing_phone');
        if (count($phone) > 0) {
            foreach ($sms_matches[0] as $match) {
                $cust_msg_sms = str_replace($match, '', $cust_msg_sms);
            }
            //Twilio message
            $args = array(
                'number_to' => fetchCountryMobileCode($data['customer_id']) . $phone[0],
                'message' => $cust_msg_sms
            );
            twl_send_sms($args);
        }
    }

    echo json_encode(['status' => true, 'message' => 'Approved Successfully']);
    die();
}

add_action('wp_ajax_nopriv_cancel_appointments', 'cancel_appointments');
add_action('wp_ajax_cancel_appointments', 'cancel_appointments');
function cancel_appointments()
{

    global $wpdb;
    $appointment_id = $_POST['appointment_id'];
    $appointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id =" . $appointment_id, ARRAY_A);
    $purchase_id = $appointment['purchase_credits_id'];
    $cancelled_by = $_POST['cancelled_by'];
    $result = $wpdb->get_row("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE id =" . $purchase_id, ARRAY_A);
    if ($result['is_unlimited_type'] == null) {
        $credit = $result['credits'] + 1;
        $wpdb->update(DB_WC_GF_CUSTOMER_PURCHASES, array('credits' => $credit), array('id' => $purchase_id));
    }
    $query = "SELECT * FROM " . DB_APPOINTMENTS . " JOIN " . DB_USERS . "
	as us ON us.ID = " . DB_APPOINTMENTS . ".customer_id JOIN " . DB_PACKAGE_SESSIONS . " as ps
	ON ps.id = " . DB_APPOINTMENTS . ".session_id WHERE " . DB_APPOINTMENTS . ".id ='" . $appointment_id . "' GROUP BY " . DB_APPOINTMENTS . ".id";
    $data = $wpdb->get_row($query, ARRAY_A);

    $instructor = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = " . $appointment['instructor_id']);
    $instructor_name = $instructor->display_name;
    $wpdb->update(DB_APPOINTMENTS, array('is_cancelled' => 1, 'instructor_id' => null, 'assigned_instructor' => $appointment['instructor_id']), array('id' => $appointment_id));
    $wpdb->query("DELETE FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE `appt_id` = '$appointment_id'");
    if ($cancelled_by == 0) {
        /* Customer */
        $customer_name = $data['display_name'];
        $cust_email = $data['user_email'];
        $appointment_date = $data['appointment_date'];
        $appointment_time = $data['cust_appointment_time'];

        $email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 2", ARRAY_A);
        $cust_msg = $email_user['body'];
        $cust_subject = $email_user['subject'];

        preg_match_all('/{(.*?)}/', $cust_msg, $matches);
        $split_time = explode(' - ', $appointment_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}', $customer_name, $cust_msg);
        }
        if (in_array("appointment_date", $matches[1])) {
            $cust_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($appointment_date)), $cust_msg);
        }
        if (in_array("appointment_time", $matches[1])) {
            $cust_msg = str_replace('{appointment_time}', $current_app_time, $cust_msg);
        }
        if (in_array("appointment_id", $matches[1])) {
            $cust_msg = str_replace('{appointment_id}', $appointment_id, $cust_msg);
        }
        if (in_array("instructor_name", $matches[1])) {
            $cust_msg = str_replace('{instructor_name}', $instructor_name, $cust_msg);
        }
        if (in_array("child_name", $matches[1])) {
            $cust_msg = str_replace('{child_name}', $data['child_id_name'], $cust_msg);
        }
        $locationid = $data['location_id'];
        $loc = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id =" . $locationid, ARRAY_A);

        if (in_array("location", $matches[1])) {
            $cust_msg = str_replace('{location}', $loc['name'], $cust_msg);
        }

        $charges = $wpdb->get_row("SELECT * FROM " . DB_CANCELLATION_CHARGE . " WHERE appointment_id =" . $appointment_id, ARRAY_A);

        if ($charges) {
            $chrg = 0;
        } else {
            $chrg = $charges['charge_amount'];
        }
        if (in_array("charge", $matches[1])) {
            $cust_msg = str_replace('{charge}', $chrg, $cust_msg);
        }
        if (in_array("credits", $matches[1])) {
            $cust_msg = str_replace('{credits}', $credit, $cust_msg);
        }

        $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;

            $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($data['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($data['ID']) . $phone[0],
                //     'message' => $cust_msg_sms
                // );
                // twl_send_sms($args);
                $phones = [];
                if (!in_array($phone[0], $phones)) {
                    // wp_mail($inst_email, "test Message from phone--".$phone[0], $inst_msg, $headers);
                    // $args = array(
                    //     'number_to' => fetchCountryMobileCode($value->ID) . $phone[0],
                    //     'message' => $inst_msg_sms
                    // );
                    try {
                        $number = fetchCountryMobileCode($data['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() );

                    }
                }
            }
        }

        /* if instructor already assigned*/

        if ($data['instructor_id']) {
            $wpdb->update(DB_APPOINTMENTS, array('is_cancelled' => 1, 'instructor_id' => null, 'assigned_instructor' => $data['instructor_id']), array('id' => $appointment_id));
            // $apptID = $appointment_modify['id'];
            $wpdb->query("DELETE FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE `appt_id` = '$appointment_id'");
            // $instructor = get_user_by('ID', $data['instructor_id'])->data;
            $inst_email = $instructor->user_email;
            // $instructor_name = $instructor->display_name;
            $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 3", ARRAY_A);
            $inst_msg = $email_instructor['body'];
            $inst_subject = $email_instructor['subject'];

            preg_match_all('/{(.*?)}/', $inst_msg, $matches);

            if (in_array("customer_name", $matches[1])) {
                $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
            }
            if (in_array("appointment_date", $matches[1])) {
                $inst_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($appointment_date)), $inst_msg);
            }
            if (in_array("appointment_time", $matches[1])) {
                $inst_msg = str_replace('{appointment_time}', $current_app_time, $inst_msg);
            }
            if (in_array("appointment_id", $matches[1])) {
                $inst_msg = str_replace('{appointment_id}', $appointment_id, $inst_msg);
            }
            if (in_array("instructor_name", $matches[1])) {
                $inst_msg = str_replace('{instructor_name}', $instructor_name, $inst_msg);
            }
            if (in_array("child_name", $matches[1])) {
                $inst_msg = str_replace('{child_name}', $data['child_id_name'], $inst_msg);
            }
            if (in_array("location", $matches[1])) {
                $inst_msg = str_replace('{location}', $loc['name'], $inst_msg);
            }

            $headers[] = 'Content-Type: text/html; charset=UTF-8';
            $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
            if ($email_instructor['notify_via_email'] == 1) {
                try {
                    //code...
                    wp_mail($inst_email, $inst_subject, $inst_msg, $headers);
                } catch (Exception $th) {
                    //throw $th;
                }
            }
            if ($email_instructor['notify_via_sms'] == 1) {
                $inst_msg_sms = $inst_msg;
                $inst_msg_sms = str_replace('<br>', "\n", $inst_msg_sms);
                $inst_msg_sms = str_replace('&nbsp', " ", $inst_msg_sms);
                preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
                $phone = get_user_meta($data['instructor_id'], 'billing_billing_phone');
                if (count($phone) > 0) {
                    foreach ($sms_matches[0] as $match) {

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

                        try {
                            $number = fetchCountryMobileCode($rowData['instructor_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" => $inst_msg_sms, "from" => $twilio_number]
                            );
                            array_push($phones, $phone[0]);
                        } catch (Exception $e) {
                            // die( $e->getCode() . ' : ' . $e->getMessage() );

                        }
                    }
                }
            }
        }
    } else {

        /* Customer */
        $customer_name = $data['display_name'];
        $cust_email = $data['user_email'];
        $appointment_date = $data['appointment_date'];
        $appointment_time = $data['appointment_time'];

        // $email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 11", ARRAY_A);
        // $cust_msg = $email_user['body'];
        // $cust_subject = $email_user['subject'];

        // preg_match_all('/{(.*?)}/', $cust_msg, $matches);

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

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

        // 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($data['ID'],'billing_billing_phone');
        //     if(count($phone)>0){
        //         foreach($sms_matches[0] as $match){
        //             $cust_msg_sms = str_replace($match,'',$cust_msg_sms);
        //         }
        //         //Twilio message
        //         $args = array(
        //             'number_to'=> fetchCountryMobileCode(data['ID']) . $phone[0],
        //             'message' => $cust_msg_sms
        //         );
        //         twl_send_sms( $args );
        //     }
        // }
        /* Admin **/
        // $email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 12", 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("customer_name", $matches[1])){
        //     $admin_msg = str_replace('{customer_name}',$customer_name,$admin_msg);
        // }
        // if(in_array("appointment_date", $matches[1])){
        //     $admin_msg = str_replace('{appointment_date}',date('l, F d Y ', strtotime($appointment_date)),$admin_msg);
        // }
        // if(in_array("appointment_time", $matches[1])){
        //     $admin_msg = str_replace('{appointment_time}',$appointment_time,$admin_msg);
        // }
        // if (in_array("appointment_id", $matches[1])) {
        //     $admin_msg = str_replace('{appointment_id}', $appointment_id,$admin_msg);
        // }
        // if(in_array("instructor_name", $matches[1])){
        //     $admin_msg = str_replace('{instructor_name}',$instructor_name,$admin_msg);
        // }

        // $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){
        //         wp_mail( $user->user_email, $admin_subject,$admin_msg ,$headers);
        //     }
        //     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){
        //         $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 );

        //     }
        //  }
        // }
    }

    echo json_encode(['status' => true, 'message' => 'Your Appointment has been cancelled successfully.']);
    die();
}

add_action('wp_ajax_nopriv_render_cancel_modal', 'render_cancel_modal');
add_action('wp_ajax_render_cancel_modal', 'render_cancel_modal');

function render_cancel_modal()
{
    $appointment_id = $_REQUEST['appointments_id'];
    global $wpdb;
    $appointment_split = explode(",", $appointment_id);
    // var_dump($appointment_split);
    // exit();
    if (count($appointment_split) > 1) {
        ob_start();
    ?>
        <div class="row ">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="">Select an Appointment to cancel</label>
                    <select onchange="appendid(this)" name="cust_appointment_id" id="del_appointment_id" class="form-control" required>
                        <option value="0"> -- Choose Appointment -- </option>
                        <?php foreach ($appointment_split as $app_id_val) {
                            $get_appt = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id = $app_id_val ");
                            $cust_split = explode(' - ', $get_appt->appointment_time);
                            $app_time = date('g:i A', strtotime($cust_split[0])) . " - " . date('g:i A', strtotime($cust_split[1]));
                            // return $app_time;
                        ?>
                            <option value="<?php echo $get_appt->id; ?>"> <?php echo $get_appt->child_id_name . "(" . $app_time . ")"; ?> </option>
                        <?php } ?>
                    </select>
                </div>
            </div>
        </div>

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


add_action('wp_ajax_nopriv_render_ins_assign_modal', 'render_ins_assign_modal');
add_action('wp_ajax_render_ins_assign_modal', 'render_ins_assign_modal');
function render_ins_assign_modal()
{

    $appointment_id = $_REQUEST['appointment_id'];
    global $wpdb;
    $appointment_split = explode(",", $appointment_id);
    // var_dump($appointment_split);
    if (count($appointment_split) > 1) {
        ob_start();
    ?>
        <div class="row ">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="">Select Appointment</label>
                    <select onchange="appendAssignInfo(this)" name="cust_appointment_id" id="cust_appointment_id" class="form-control" required>
                        <option value=""> -- Choose Appointment -- </option>
                        <?php foreach ($appointment_split as $app_id_val) {
                            $get_appt = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id = $app_id_val ");
                        ?>
                            <option value="<?php echo $get_appt->id; ?>"> <?php echo $get_appt->child_id_name . "(" . $get_appt->appointment_time . ")"; ?> </option>
                        <?php } ?>
                    </select>
                </div>
            </div>
        </div>

    <?php
        $html = ob_get_clean();
        echo json_encode(['status' => true, 'renderedHtml' => $html, 'flag' => 1]);
        die();
    } else {

        // exit();
        $getAppointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id = '$appointment_id' ");

        $location_id = $getAppointment->location_id;
        $session_id = $getAppointment->session_id;
        $date = date("Y-m-d", strtotime($getAppointment->appointment_date));

        $appointment_time = $getAppointment->cust_appointment_time;
        $app_split = explode(' - ', $getAppointment->cust_appointment_time);
        // Convert the date string into a unix timestamp.

        $start = $app_split[0];
        $end = $app_split[1];
        $timings = [];

        if ($start != "" && $end != "") {
            $AddMins = 60 * 60;
            $StartTime = strtotime($start);
            $EndTime = strtotime($end);

            while ($StartTime < $EndTime) {
                $t = date("G:i", $StartTime);
                $u = date("G:i", ($StartTime + $AddMins));
                $slot = $t . ' - ' . $u;

                if (strtotime($app_split[0]) <= $StartTime && strtotime($app_split[1]) >= ($StartTime + $AddMins)) {

                    array_push($timings, $slot);
                }
                $StartTime += $AddMins;
            }
        }


        ob_start(); ?>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
        <div class="row timingRow">
            <input type="hidden" id="pass_appointment_id" value="<?php echo $appointment_id; ?>">
            <input type="hidden" id="location_id" value="<?php echo $location_id; ?>">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="">Select Time slot</label>
                    <select name="assign_instructor_time" id="assign_instructor_time" class="form-control" onchange="getInstructorListing(this)" required>
                        <option value=""> -- Choose Time Slot -- </option>
                        <?php
                        foreach ($timings as $key => $value) {
                            $cust_split = explode(' - ', $value);
                            $app_time = date('g:i A', strtotime($cust_split[0])) . " - " . date('g:i A', strtotime($cust_split[1]));
                            echo "<option value='" . $value . "'>" . $app_time . "</option>";
                        }
                        ?>
                    </select>
                </div>
            </div>
            <div class="col-md-12 insblock" style="display: none;">
                <div class="form-group">
                    <label for="">Select Instructor</label><br>
                    <select name="assign_instructor[]" id="assign_instructor" multiple="multiple" class="form-control" required>


                    </select>
                </div>
            </div>
            <div class="col-md-12">
                <p id="AssignMessage"></p>
            </div>
        </div>

    <?php $renderedHtml = ob_get_clean();

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

add_action('wp_ajax_nopriv_render_ins_assign_modal_new', 'render_ins_assign_modal_new');
add_action('wp_ajax_render_ins_assign_modal_new', 'render_ins_assign_modal_new');
function render_ins_assign_modal_new()
{

    $appointment_id = $_REQUEST['appointment_id'];
    global $wpdb;
    $appointment_split = explode(",", $appointment_id);
    // var_dump($appointment_split);
    if (count($appointment_split) > 1) {
        ob_start();
    ?>
        <div class="row ">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="">Select Appointment</label>
                    <select onchange="appendAssignInfo(this)" name="cust_appointment_id" id="cust_appointment_id" class="form-control" required>
                        <option value=""> -- Choose Appointment -- </option>
                        <?php foreach ($appointment_split as $app_id_val) {
                            $get_appt = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id = $app_id_val ");
                        ?>
                            <option value="<?php echo $get_appt->id; ?>"> <?php echo $get_appt->child_id_name . "(" . $get_appt->appointment_time . ")"; ?> </option>
                        <?php } ?>
                    </select>
                </div>
            </div>
        </div>

    <?php
        $html = ob_get_clean();
        echo json_encode(['status' => true, 'renderedHtml' => $html, 'flag' => 1]);
        die();
    } else {

        // exit();
        $getAppointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id = '$appointment_id' ");

        $instructors = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE appt_id = '$appointment_id' ");
        $location_id = $getAppointment->location_id;
        $session_id = $getAppointment->session_id;
        $date = date("Y-m-d", strtotime($getAppointment->appointment_date));

        $appointment_time = $getAppointment->appointment_time;
        $app_split = explode(' - ', $getAppointment->cust_appointment_time);
        // Convert the date string into a unix timestamp.

        $start = $app_split[0];
        $end = $app_split[1];
        $timings = [];

        if ($start != "" && $end != "") {
            $AddMins = 60 * 60;
            $StartTime = strtotime($start);
            $EndTime = strtotime($end);

            while ($StartTime < $EndTime) {
                $t = date("G:i", $StartTime);
                $u = date("G:i", ($StartTime + $AddMins));
                $slot = $t . ' - ' . $u;

                if (strtotime($app_split[0]) <= $StartTime && strtotime($app_split[1]) >= ($StartTime + $AddMins)) {

                    array_push($timings, $slot);
                }
                $StartTime += $AddMins;
            }
        }


        ob_start(); ?>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
        <div class="row timingRow">
            <input type="hidden" id="pass_appointment_id" value="<?php echo $appointment_id; ?>">
            <input type="hidden" id="location_id" value="<?php echo $location_id; ?>">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="">Select Time slot</label>
                    <select name="assign_instructor_time" id="assign_instructor_time" class="form-control" onchange="getInstructorListing(this)" required>
                        <option value=""> -- Choose Time Slot -- </option>
                        <?php


                        foreach ($timings as $key => $value) {
                            $selected = "";
                            if ($appointment_time == $value) {

                                $selected = "selected";
                            }
                            $cust_split = explode(' - ', $value);
                            $app_time = date('g:i A', strtotime($cust_split[0])) . " - " . date('g:i A', strtotime($cust_split[1]));
                            echo "<option " . $selected . " value='" . $value . "'>" . $app_time . "</option>";
                        }
                        ?>
                    </select>
                </div>
            </div>
            <?php if (count($instructors) > 0) { ?>
                <script>
                    jQuery("#assign_instructor_time").trigger("change");
                </script>
            <?php } ?>

            <div class="col-md-12 insblock" style="display: none;">
                <div class="form-group">
                    <label for="">Select Instructor</label><br>
                    <select name="assign_instructor[]" id="assign_instructor" multiple="multiple" class="form-control" required>


                    </select>
                </div>
            </div>
            <div class="col-md-12">
                <p id="AssignMessage"></p>
            </div>
        </div>

    <?php $renderedHtml = ob_get_clean();

        echo json_encode(['status' => true, 'renderedHtml' => $renderedHtml]);
        die();
    }
}
add_action('wp_ajax_nopriv_render_ins_assign_modal_newIndividual', 'render_ins_assign_modal_newIndividual');
add_action('wp_ajax_render_ins_assign_modal_newIndividual', 'render_ins_assign_modal_newIndividual');
function render_ins_assign_modal_newIndividual()
{

    $appointment_id = $_REQUEST['appointment_id'];
    global $wpdb;
    $appointment_split = explode(",", $appointment_id);
    // var_dump($appointment_split);
    if (count($appointment_split) > 1) {
        ob_start();
    ?>
        <div class="row ">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="">Select Appointment</label>
                    <select onchange="appendAssignInfo(this)" name="cust_appointment_id" id="cust_appointment_id" class="form-control" required>
                        <option value=""> -- Choose Appointment -- </option>
                        <?php foreach ($appointment_split as $app_id_val) {
                            $get_appt = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id = $app_id_val ");
                        ?>
                            <option value="<?php echo $get_appt->id; ?>"> <?php echo $get_appt->child_id_name . "(" . $get_appt->appointment_time . ")"; ?> </option>
                        <?php } ?>
                    </select>
                </div>
            </div>
        </div>

    <?php
        $html = ob_get_clean();
        echo json_encode(['status' => true, 'renderedHtml' => $html, 'flag' => 1]);
        die();
    } else {

        // exit();
        $getAppointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id = '$appointment_id' ");

        $instructors = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE appt_id = '$appointment_id' ");
        $location_id = $getAppointment->location_id;
        $session_id = $getAppointment->session_id;
        $date = date("Y-m-d", strtotime($getAppointment->appointment_date));

        $appointment_time = $getAppointment->appointment_time;
        $app_split = explode(' - ', $getAppointment->cust_appointment_time);
        // Convert the date string into a unix timestamp.

        $start = $app_split[0];
        $end = $app_split[1];
        $timings = [];

        if ($start != "" && $end != "") {
            $AddMins = 60 * 60;
            $StartTime = strtotime($start);
            $EndTime = strtotime($end);

            while ($StartTime < $EndTime) {
                $t = date("G:i", $StartTime);
                $u = date("G:i", ($StartTime + $AddMins));
                $slot = $t . ' - ' . $u;

                if (strtotime($app_split[0]) <= $StartTime && strtotime($app_split[1]) >= ($StartTime + $AddMins)) {

                    array_push($timings, $slot);
                }
                $StartTime += $AddMins;
            }
        }


        ob_start(); ?>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
        <div class="row timingRow">
            <input type="hidden" id="pass_appointment_id" value="<?php echo $appointment_id; ?>">
            <input type="hidden" id="location_id" value="<?php echo $location_id; ?>">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="">Select Time slot</label>
                    <select name="assign_instructor_time" id="assign_instructor_time" class="form-control" onchange="getInstructorListing(this)" required>
                        <option value=""> -- Choose Time Slot -- </option>
                        <?php


                        foreach ($timings as $key => $value) {
                            $selected = "";
                            if ($appointment_time == $value) {

                                $selected = "selected";
                            }
                            $cust_split = explode(' - ', $value);
                            $app_time = date('g:i A', strtotime($cust_split[0])) . " - " . date('g:i A', strtotime($cust_split[1]));
                            echo "<option " . $selected . " value='" . $value . "'>" . $app_time . "</option>";
                        }
                        ?>
                    </select>
                </div>
            </div>
            <?php if (count($instructors) > 0) { ?>
                <script>
                    jQuery("#assign_instructor_time").trigger("change");
                </script>
            <?php } ?>

            <div class="col-md-12 insblock" style="display: none;">
                <div class="form-group">
                    <label for="">Select Instructor</label><br>
                    <select name="assign_instructor[]" id="assign_instructor" class="form-control" required>


                    </select>
                </div>
            </div>
            <div class="col-md-12">
                <p id="AssignMessage"></p>
            </div>
        </div>

    <?php $renderedHtml = ob_get_clean();

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

add_action('wp_ajax_nopriv_render_instructor_list', 'render_instructor_list');
add_action('wp_ajax_render_instructor_list', 'render_instructor_list');
function render_instructor_list()
{
    global $wpdb;
    $appointment_id = $_POST['appointment_id'];
    $location_id = $_POST['location_id'];
    $appointment_time = $_POST['timing'];
    $getAppointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id = '$appointment_id' ");
    $appointment_date = $getAppointment->appointment_date;
    $session_id = $getAppointment->session_id;
    $date = date("Y-m-d", strtotime($getAppointment->appointment_date));
    $unixTimestamp = strtotime($date);
    $dayOfWeek = date("l", $unixTimestamp);
    $weekday = strtolower($dayOfWeek);
    // 1) Get availabilities of all instructors on selected date
    $query = "SELECT *, instructor_id as ins_id FROM " . DB_INSTRUCTORS_AVAILABILITY . " WHERE location_id = " . $location_id . " AND weekday = '$weekday'";
    $timings = $wpdb->get_results($query);

    $inst_array = [];
    foreach ($timings as $key => $time) {
        $query = "SELECT count(*) FROM " . DB_INSTRUCTORS_OFF_DAYS . " WHERE off_day = '$date' AND instructor_id = '$time->instructor_id'";
        $rowCount = $wpdb->get_var($query);

        // 2) Loop through timings and Omit OFF Days
        if ($rowCount > 0) {
            continue;
        }
        $app_split = explode(' - ', $appointment_time);
        $start = date("G:i", strtotime($time->start_time));
        $close = date("G:i", strtotime($time->end_time));
        $AddMins = 60 * 60;

        if ($start != "" && $close != "") {


            if (strtotime($app_split[0]) >= strtotime($start) && strtotime($app_split[1]) <= strtotime($close)) {
                $obj = new stdClass();
                $obj->instructor_id = $time->instructor_id;
                $us = get_userdata($obj->instructor_id);
                $obj->name = $us->display_name;
                array_push($inst_array, $obj);
            }
        }
    } ?>

    <?php

    foreach ($inst_array as $instructor) {
        $getInstAppt = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENTS . "  JOIN " . DB_APPOINTMENT_INSTRUCTORS . "
        as ins ON ins.appt_id = " . DB_APPOINTMENTS . ".id  WHERE appointment_date= '" . $appointment_date . "'  AND " . DB_APPOINTMENTS . ".id !='" . $appointment_id . "' AND " . DB_APPOINTMENTS . ".location_id !='" . $location_id . "'
         AND ins.is_cancelled=0 AND ins.has_attended=0 AND ins.instructor_id =" . $instructor->instructor_id . " AND(appointment_time ='" . $appointment_time . "' OR cust_appointment_time ='" . $appointment_time . "')", ARRAY_A);
        // echo $wpdb->last_query;
        // die();
        // echo "<pre>";
        // print_r($getInstAppt);
        if (empty($getInstAppt)) {
            echo "<option value='" . $instructor->instructor_id . "'>" . $instructor->name . "</option>";
        }
    }
    $renderedHtml = ob_get_clean();

    $instructors = $wpdb->get_results("SELECT instructor_id FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE appt_id = '$appointment_id' ");
    $insData = [];
    if (count($instructors) > 0) {
        foreach ($instructors as $ins) {
            array_push($insData, $ins->instructor_id);
        }
    }


    echo json_encode(['status' => true, 'renderedHtml' => $renderedHtml, 'instructors' => $insData]);
    die();
}
add_action('wp_ajax_nopriv_render_ins_assign_modal_timings', 'render_ins_assign_modal_timings');
add_action('wp_ajax_render_ins_assign_modal_timings', 'render_ins_assign_modal_timings');
function render_ins_assign_modal_timings()
{
    $instructor_id = $_POST['instructor_id'];
    $appointment_id = $_POST['appointment_id'];

    global $wpdb;
    $appointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id = '$appointment_id' ");

    $date = date("Y-m-d", strtotime($appointment->appointment_date));

    // $appointment_time = $getAppointment->appointment_time;

    // 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);

    $location_id = $appointment->location_id;
    $query = "SELECT * FROM " . DB_INSTRUCTORS_AVAILABILITY . " WHERE instructor_id=" . $instructor_id . " AND location_id=" . $location_id . " AND weekday = '$weekday'";
    $inst_timings = $wpdb->get_row($query);

    $app_split = explode(' - ', $appointment->cust_appointment_time);

    $start = $inst_timings->start_time;
    $end = $inst_timings->end_time;
    $timings = [];

    if ($start != "" && $end != "") {
        $AddMins = 60 * 60;
        $StartTime = strtotime($start);
        $EndTime = strtotime($end);

        while ($StartTime < $EndTime) {
            $t = date("G:i", $StartTime);
            $u = date("G:i", ($StartTime + $AddMins));
            $slot = $t . ' - ' . $u;

            if (strtotime($app_split[0]) <= $StartTime && strtotime($app_split[1]) >= ($StartTime + $AddMins)) {

                if ($appointment->instructor_id == $instructor_id && $appointment->id == $appointment_id) {
                    if ($appointment->appointment_time != $slot) {
                        array_push($timings, $slot);
                    }
                } else {
                    array_push($timings, $slot);
                }
            }
            $StartTime += $AddMins;
        }
    }

    ob_start();
    ?>
    <option value="">-- Choose Time Slot --</option>
    <?php
    foreach ($timings as $key => $value) {

        $cust_split = explode(' - ', $value);
        $app_time = date('g:i A', strtotime($cust_split[0])) . " - " . date('g:i A', strtotime($cust_split[1]));
        echo "<option value='" . $value . "'>" . $app_time . "</option>";
    }

    ?>

    <?php
    $renderedHtml = ob_get_clean();

    echo json_encode(['status' => true, 'renderedHtml' => $renderedHtml]);
    die();
}
add_action('wp_ajax_nopriv_get_availability_message', 'get_availability_message');
add_action('wp_ajax_get_availability_message', 'get_availability_message');
function get_availability_message()
{
    $instructor_id = $_POST['inst_id'];
    $appointment_time = $_POST['appointment_time'];
    $appointment_id = $_POST['appointment_id'];

    global $wpdb;
    $appointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id = '$appointment_id' ");

    $appointment_date = $appointment->appointment_date;
    // $appointment_time = $appointment->appointment_time;

    $getInstAppt = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENTS . " WHERE appointment_date= '" . $appointment_date . "' AND appointment_time='" . $appointment_time . "' AND session_id=2 AND is_cancelled=0 AND has_attended IS NULL AND instructor_id =" . $instructor_id, ARRAY_A);

    // var_dump($getInstAppt);
    // exit();
    if (count($getInstAppt) > 0) {
        // $wpdb->update(DB_APPOINTMENTS, array("instructor_id"=>NULL,'assigned_instructor'=>NULL), array("id" => $getInstAppt[0]['id']));
        $instructor = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = '$instructor_id' ");

        $inst_split = explode(' - ', $appointment_time);
        $app_time = date('g:i A', strtotime($inst_split[0])) . " - " . date('g:i A', strtotime($inst_split[1]));

        $message = $instructor->display_name . " has an appointment already at " . $app_time . ". Click Assign if you wish to override the existing appointment.";
    } else {
        if ($appointment->session_id == 2) {
            $getInstAppt = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENTS . " WHERE appointment_date= '" . $appointment_date . "' AND appointment_time='" . $appointment_time . "' AND is_cancelled=0 AND has_attended IS NULL AND instructor_id =" . $instructor_id, ARRAY_A);
            if (count($getInstAppt) > 0) {
                $instructor = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = '$instructor_id' ");

                $inst_split = explode(' - ', $appointment_time);
                $app_time = date('g:i A', strtotime($inst_split[0])) . " - " . date('g:i A', strtotime($inst_split[1]));

                $message = $instructor->display_name . " has appointments already at " . $app_time . ". Click Assign if you wish to override the existing appointment.";
            }
        } else {
            $getInstAppt = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENTS . " WHERE appointment_date= '" . $appointment_date . "' AND location_id=" . $appointment->location_id . " AND appointment_time='" . $appointment_time . "' AND session_id != 2 AND is_cancelled=0 AND has_attended IS NULL AND instructor_id =" . $instructor_id, ARRAY_A);

            // var_dump("SELECT * FROM " . DB_APPOINTMENTS . " WHERE appointment_date= '" . $appointment_date . "' AND location_id=".$appointment->location_id." AND appointment_time='" . $appointment_time . "' AND session_id != 2 AND is_cancelled=0 AND has_attended IS NULL AND instructor_id =" . $instructor_id);
            // exit();
            if (count($getInstAppt) >= 4) {
                // $wpdb->update(DB_APPOINTMENTS, array("instructor_id"=>NULL,'assigned_instructor'=>NULL), array("id" => $getInstAppt[0]['id']));
                $instructor = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = '$instructor_id' ");

                $inst_split = explode(' - ', $appointment_time);
                $app_time = date('g:i A', strtotime($inst_split[0])) . " - " . date('g:i A', strtotime($inst_split[1]));

                $message = $instructor->display_name . " has a group session of " . count($getInstAppt) . " players at " . $app_time . ". Click Assign to add this player into the group.";
            } else {
                $message = "";
            }
        }
    }

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

add_action('wp_ajax_nopriv_get_merge_message', 'get_merge_message');
add_action('wp_ajax_get_merge_message', 'get_merge_message');
function get_merge_message()
{
    $instructor_id = $_POST['instructor_id'];
    $appointment_id = $_POST['appointment_id'];
    $sec_appointment_id = $_POST['sec_appointment_id'];

    global $wpdb;
    $appointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id =" . $appointment_id);

    $appointment_date = $appointment->appointment_date;
    $appointment_time = $appointment->appointment_time;

    $getInstAppt = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENTS . " WHERE appointment_date= '" . $appointment_date . "' AND location_id=" . $appointment->location_id . " AND appointment_time='" . $appointment_time . "' AND session_id != 2 AND is_cancelled=0 AND has_attended IS NULL AND instructor_id =" . $instructor_id, ARRAY_A);

    // var_dump($getInstAppt);
    // exit();
    if (count($getInstAppt) >= 4) {
        // $wpdb->update(DB_APPOINTMENTS, array("instructor_id"=>NULL,'assigned_instructor'=>NULL), array("id" => $getInstAppt[0]['id']));
        $instructor = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = '$instructor_id' ");

        $inst_split = explode(' - ', $appointment_time);
        $app_time = date('g:i A', strtotime($inst_split[0])) . " - " . date('g:i A', strtotime($inst_split[1]));

        $message = $instructor->display_name . " has a group session of " . count($getInstAppt) . " players at " . $app_time . ". Click Merge Sessions to add this player into the group.";
    } else {
        $message = "";
    }
    echo json_encode(['status' => true, 'message' => $message]);
    die();
}

add_action('wp_ajax_nopriv_instructor_assign', 'instructor_assign');
add_action('wp_ajax_instructor_assign', 'instructor_assign');
function instructor_assign()
{
    $appointment_id = $_REQUEST['pass_appointment_id'];
    $instructor_id = $_REQUEST['instructor_id'];
    $appointment_time = $_REQUEST['appointment_time'];

    global $wpdb;
    $token = my_simple_crypt(time());
    $verification_approve_url = site_url('wp-admin/admin-ajax.php?action=ctoken&status=1&token=' . $token);
    $verification_cancel_url = site_url('wp-admin/admin-ajax.php?action=ctoken&status=0&token=' . $token);

    $getAppointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " JOIN " . DB_USERS . " as us ON us.ID = " . DB_APPOINTMENTS . ".customer_id WHERE " . DB_APPOINTMENTS . ".id =" . $appointment_id, ARRAY_A);
    if ($getAppointment['approval_notification_status'] == 2) {
        if ($getAppointment['instructor_id']) {
            $instructor = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = " . $getAppointment['instructor_id']);
            $customer = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = " . $getAppointment['customer_id'], ARRAY_A);
            $customer_name = $customer['display_name'];

            $instructor_name = $instructor->display_name;
            $inst_email = $instructor->user_email;

            // $instructor_name = $instructor->display_name;
            $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 3", ARRAY_A);
            $inst_msg = $email_instructor['body'];
            $inst_subject = $email_instructor['subject'];

            $inst_split = explode(' - ', $getAppointment['appointment_time']);
            $app_time = date('g:i A', strtotime($inst_split[0])) . " - " . date('g:i A', strtotime($inst_split[1]));

            preg_match_all('/{(.*?)}/', $inst_msg, $matches);

            if (in_array("customer_name", $matches[1])) {
                $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
            }
            if (in_array("appointment_date", $matches[1])) {
                $inst_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($getAppointment['appointment_date'])), $inst_msg);
            }
            if (in_array("appointment_time", $matches[1])) {
                $inst_msg = str_replace('{appointment_time}', $app_time, $inst_msg);
            }
            if (in_array("appointment_id", $matches[1])) {
                $inst_msg = str_replace('{appointment_id}', $getAppointment['id'], $inst_msg);
            }
            if (in_array("instructor_name", $matches[1])) {
                $inst_msg = str_replace('{instructor_name}', $instructor_name, $inst_msg);
            }

            $locationid = $getAppointment['location_id'];
            $loc = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id =" . $locationid, ARRAY_A);

            if (in_array("location", $matches[1])) {
                $inst_msg = str_replace('{location}', $loc['name'], $inst_msg);
            }

            if (in_array("child_name", $matches[1])) {
                $inst_msg = str_replace('{child_name}', $getAppointment['child_id_name'], $inst_msg);
            }

            $headers[] = 'Content-Type: text/html; charset=UTF-8';
            $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
            if ($email_instructor['notify_via_email'] == 1) {
                try {
                    //code...

                    wp_mail($inst_email, $inst_subject, $inst_msg, $headers);
                } catch (Exception $th) {
                    //throw $th;
                }
            }
            if ($email_instructor['notify_via_sms'] == 1) {
                $inst_msg_sms = $inst_msg;
                $inst_msg_sms = str_replace('<br>', "\n", $inst_msg_sms);
                $inst_msg_sms = str_replace('&nbsp', " ", $inst_msg_sms);
                preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
                $phone = get_user_meta($data['instructor_id'], 'billing_billing_phone');
                if (count($phone) > 0) {
                    foreach ($sms_matches[0] as $match) {

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

                        try {
                            $number = fetchCountryMobileCode($rowData['instructor_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" => $inst_msg_sms, "from" => $twilio_number]
                            );
                            array_push($phones, $phone[0]);
                        } catch (Exception $e) {
                            // die( $e->getCode() . ' : ' . $e->getMessage() );

                        }
                    }
                }
            }
        }
    }
    $appointment_date = $getAppointment['appointment_date'];
    // $appointment_time = $getAppointment['appointment_time'];

    if ($getAppointment['session_id'] == 2) {
        $getInstAppt = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENTS . " WHERE appointment_date= '" . $appointment_date . "' AND appointment_time='" . $appointment_time . "' AND " . DB_APPOINTMENTS . ".instructor_id =" . $instructor_id, ARRAY_A);

        if (count($getInstAppt) > 0) {
            foreach ($getInstAppt as $key => $getAppt) {
                $wpdb->update(DB_APPOINTMENTS, array("instructor_id" => null, 'assigned_instructor' => null, 'is_approved' => 0, 'appointment_time' => null), array("id" => $getAppt['id']));
            }
        }
    } else {
        $getInstAppt = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENTS . " WHERE session_id=2 AND appointment_date= '" . $appointment_date . "' AND appointment_time='" . $appointment_time . "' AND " . DB_APPOINTMENTS . ".instructor_id =" . $instructor_id, ARRAY_A);

        if (count($getInstAppt) > 0) {
            $wpdb->update(DB_APPOINTMENTS, array("instructor_id" => null, 'assigned_instructor' => null, 'is_approved' => 0, 'appointment_time' => null), array("id" => $getInstAppt[0]['id']));
        }
    }

    $sqlUpdate = $wpdb->update(DB_APPOINTMENTS, array("instructor_id" => $instructor_id, "token" => $token, "is_approved" => 0, 'appointment_time' => $appointment_time, 'approval_notification_status' => 1), array("id" => $appointment_id));

    $instructor = get_user_by('ID', $instructor_id);
    $email = $instructor->user_email;
    $instructor_name = $instructor->display_name;

    $customer_name = $getAppointment['display_name'];

    $cust_split = explode(' - ', $appointment_time);
    $app_time = date('g:i A', strtotime($cust_split[0])) . " - " . date('g:i A', strtotime($cust_split[1]));

    //     if ($sqlUpdate) {

    //         //Instructor Email
    //         $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 25", ARRAY_A);
    //         $inst_msg = $email_instructor['body'];
    //         $inst_subject = $email_instructor['subject'];
    //         $inst_email = $instructor->user_email;

    //         $location = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id = " . $getAppointment['location_id']);
    //         $location_name = $location->name;

    //         preg_match_all('/{(.*?)}/', $inst_msg, $matches);

    //         if (in_array("customer_name", $matches[1])) {
    //             $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
    //         }
    //         if (in_array("child_name", $matches[1])) {
    //             $inst_msg = str_replace('{child_name}', $getAppointment['child_id_name'], $inst_msg);
    //         }
    //         if (in_array("appointment_date", $matches[1])) {
    //             $inst_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($appointment_date)), $inst_msg);
    //         }
    //         if (in_array("appointment_time", $matches[1])) {
    //             $inst_msg = str_replace('{appointment_time}', $app_time, $inst_msg);
    //         }
    //         if (in_array("instructor_name", $matches[1])) {
    //             $inst_msg = str_replace('{instructor_name}', $instructor_name, $inst_msg);
    //         }
    //         if (in_array("location_name", $matches[1])) {
    //             $inst_msg = str_replace('{location_name}', $location_name, $inst_msg);
    //         }

    //         if (in_array("login_link", $matches[1])) {
    //             $inst_msg = str_replace('{login_link}', 'https://shootinschool.com/wp-admin', $inst_msg);
    //         }

    //         $inst_msg_sms = $inst_msg;
    //         if (in_array("verification_approve_url", $matches[1])) {
    //             $inst_msg_sms = str_replace('{verification_approve_url}', $verification_approve_url, $inst_msg_sms);
    //             $inst_msg_sms = str_replace('{verification_cancel_url}', $verification_cancel_url, $inst_msg_sms);
    //             $inst_msg = str_replace('{verification_approve_url}', '<a target="_blank" href="' . $verification_approve_url . '"> Approve</a><br>', $inst_msg);
    //             $inst_msg = str_replace('{verification_cancel_url}', '<a target="_blank" href="' . $verification_cancel_url . '"> Approve</a><br>', $inst_msg);
    //         }

    //         $headers[] = 'Content-Type: text/html; charset=UTF-8';
    //         $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
    //         if ($email_instructor['notify_via_email'] == 1) {
    //             try {
    //                 //code...
    //                 wp_mail($inst_email, $inst_subject, $inst_msg, $headers);

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

    //         if ($email_instructor['notify_via_sms'] == 1) {

    //             $inst_msg_sms = str_replace('<br>', "\n", $inst_msg_sms);
    //             $inst_msg_sms = str_replace('&nbsp', " ", $inst_msg_sms);
    //             preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
    //             $phone = get_user_meta($instructor_id, 'billing_billing_phone');
    //             if (count($phone) > 0) {
    //                 foreach ($sms_matches[0] as $match) {

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

    //                     try{
    //                         $number = fetchCountryMobileCode($instructor_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" => $inst_msg_sms, "from" => $twilio_number] );
    //                         array_push($phones,$phone[0]);
    //                     }catch (Exception $e) {
    //                             // die( $e->getCode() . ' : ' . $e->getMessage() );

    //                     }

    //                 }
    //             }
    //         }
    //     }

    echo json_encode(['status' => true, 'message' => 'Instructor has been assigned successfully']);
    die();
}
add_action('wp_ajax_nopriv_instructor_assign_new', 'instructor_assign_new');
add_action('wp_ajax_instructor_assign_new', 'instructor_assign_new');
function instructor_assign_new()
{
    // die("ssss");
    $appointment_id = $_REQUEST['pass_appointment_id'];
    $instructor_id = $_REQUEST['instructor_id'];
    $appointment_time = $_REQUEST['appointment_time'];


    global $wpdb;
    $wpdb->query("DELETE FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE `appt_id` = '$appointment_id'");





    $getAppointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " JOIN " . DB_USERS . " as us ON us.ID = " . DB_APPOINTMENTS . ".customer_id WHERE " . DB_APPOINTMENTS . ".id =" . $appointment_id, ARRAY_A);

    $appointment_date = $getAppointment['appointment_date'];
    // $appointment_time = $getAppointment['appointment_time'];

    if ($getAppointment['session_id'] == 2) {
        $getInstAppt = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENTS . " WHERE appointment_date= '" . $appointment_date . "' AND appointment_time='" . $appointment_time . "' AND " . DB_APPOINTMENTS . ".instructor_id =" . $instructor_id, ARRAY_A);

        if (count($getInstAppt) > 0) {
            foreach ($getInstAppt as $key => $getAppt) {

                $aid = $getAppt['id'];
                $wpdb->query("DELETE FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE `appt_id` = '$aid'");
                $wpdb->update(DB_APPOINTMENTS, array("instructor_id" => null, 'assigned_instructor' => null, 'is_approved' => 0, 'appointment_time' => null), array("id" => $getAppt['id']));
                // $wpdb->update(DB_APPOINTMENTS, array('is_approved' => 0, 'appointment_time' => null), array("id" => $getAppt['id']));
            }
        }
    } else {
        $getInstAppt = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENTS . " WHERE session_id=2 AND appointment_date= '" . $appointment_date . "' AND appointment_time='" . $appointment_time . "' AND " . DB_APPOINTMENTS . ".instructor_id =" . $instructor_id, ARRAY_A);

        if (count($getInstAppt) > 0) {
            $aid = $getInstAppt[0]['id'];
            $wpdb->query("DELETE FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE `appt_id` = '$aid'");
            $wpdb->update(DB_APPOINTMENTS, array("instructor_id" => null, 'assigned_instructor' => null, 'is_approved' => 0, 'appointment_time' => null), array("id" => $getAppt['id']));
            $wpdb->update(DB_APPOINTMENTS, array('is_approved' => 0, 'appointment_time' => null), array("id" => $getInstAppt[0]['id']));
        }
    }

    $wpdb->update(DB_APPOINTMENTS, array('instructor_id' => null), array("id" => $appointment_id));
    if (is_array($instructor_id)) {
        if (count($instructor_id) > 0) {

            foreach ($instructor_id as $ins) {
                if (count($instructor_id) == 1) {
                    $wpdb->update(DB_APPOINTMENTS, array('instructor_id' => $ins), array("id" => $appointment_id));
                }
                $args = array(
                    "appt_id" => $appointment_id,
                    "instructor_id" => $ins,
                    "approval_notification_status" => 1,
                );
                $wpdb->insert(DB_APPOINTMENT_INSTRUCTORS, $args);
            }
        }
    } else {
        // $wpdb->update(DB_APPOINTMENTS, array('instructor_id' => null), array("id" => $appointment_id));
        $wpdb->update(DB_APPOINTMENTS, array('instructor_id' => $instructor_id), array("id" => $appointment_id));
        $args = array(
            "appt_id" => $appointment_id,
            "instructor_id" => $instructor_id,
            "approval_notification_status" => 1,
        );
        $wpdb->insert(DB_APPOINTMENT_INSTRUCTORS, $args);
    }


    // if ($getAppointment['approval_notification_status'] == 2) {
    // if ($getAppointment['instructor_id']) {

    $customer = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = " . $getAppointment['customer_id'], ARRAY_A);
    $customer_name = $customer['display_name'];
    if (is_array($instructor_id)) {
        if (count($instructor_id) > 0) {


            foreach ($instructor_id as $ins) {
                $token = my_simple_crypt(floor(microtime(true) * 1000));
                $verification_approve_url = site_url('wp-admin/admin-ajax.php?action=ctoken&status=1&token=' . $token);
                $verification_cancel_url = site_url('wp-admin/admin-ajax.php?action=ctoken&status=0&token=' . $token);
                $wpdb->update(DB_APPOINTMENTS, array("token" => $token, "is_approved" => 0, 'appointment_time' => $appointment_time, 'approval_notification_status' => 1), array("id" => $appointment_id));
                $wpdb->update(DB_APPOINTMENT_INSTRUCTORS, array('approval_notification_status' => 1, 'appt_token' => $token), array("instructor_id" => $ins, "appt_id" => $appointment_id));

                $instructor = $wpdb->get_row("SELECT * FROM " . DB_USERS . " JOIN " . DB_APPOINTMENT_INSTRUCTORS . " as dis on dis.instructor_id = " . DB_USERS . ".ID  WHERE " . DB_USERS . ".ID = " . $ins);

                if ($instructor->approval_notification_status == 0) {

                    $instructor_name = $instructor->display_name;
                    $inst_email = $instructor->user_email;

                    // $instructor_name = $instructor->display_name;
                    $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 4", ARRAY_A);
                    $inst_msg = $email_instructor['body'];
                    $inst_subject = $email_instructor['subject'];

                    $inst_split = explode(' - ', $appointment_time);
                    $app_time = date('g:i A', strtotime($inst_split[0])) . " - " . date('g:i A', strtotime($inst_split[1]));

                    preg_match_all('/{(.*?)}/', $inst_msg, $matches);

                    if (in_array("customer_name", $matches[1])) {
                        $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
                    }
                    if (in_array("appointment_date", $matches[1])) {
                        $inst_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($getAppointment['appointment_date'])), $inst_msg);
                    }
                    if (in_array("appointment_time", $matches[1])) {
                        $inst_msg = str_replace('{appointment_time}', $app_time, $inst_msg);
                    }
                    if (in_array("appointment_id", $matches[1])) {
                        $inst_msg = str_replace('{appointment_id}', $getAppointment['id'], $inst_msg);
                    }
                    if (in_array("instructor_name", $matches[1])) {
                        $inst_msg = str_replace('{instructor_name}', $instructor_name, $inst_msg);
                    }

                    $locationid = $getAppointment['location_id'];
                    $loc = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id =" . $locationid, ARRAY_A);

                    if (in_array("location_name", $matches[1])) {
                        $inst_msg = str_replace('{location_name}', $loc['name'], $inst_msg);
                    }

                    if (in_array("child_name", $matches[1])) {
                        $inst_msg = str_replace('{child_name}', $getAppointment['child_id_name'], $inst_msg);
                    }

                    $headers[] = 'Content-Type: text/html; charset=UTF-8';
                    $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';

                    // if ($email_instructor['notify_via_email'] == 1) {

                    //     try {
                    //         //code...

                    //         wp_mail($inst_email, $inst_subject, $inst_msg, $headers);
                    //     } catch (Exception $th) {
                    //         throw $th; 
                    //         die("ss");
                    //     }
                    // }
                    // if ($email_instructor['notify_via_sms'] == 1) {
                    //     $inst_msg_sms = $inst_msg;
                    //     $inst_msg_sms = str_replace('<br>', "\n", $inst_msg_sms);
                    //     $inst_msg_sms = str_replace('&nbsp', " ", $inst_msg_sms);
                    //     preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
                    //     $phone = get_user_meta($data['instructor_id'], 'billing_billing_phone');
                    //     if (count($phone) > 0) {
                    //         foreach ($sms_matches[0] as $match) {

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

                    //             try {
                    //                 $number = fetchCountryMobileCode($rowData['instructor_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" => $inst_msg_sms, "from" => $twilio_number]
                    //                 );
                    //                 array_push($phones, $phone[0]);
                    //             } catch (Exception $e) {
                    //                 // die( $e->getCode() . ' : ' . $e->getMessage() );

                    //             }
                    //         }
                    //     }
                    // }
                }
            }
        }
    } else {
        $ins = $instructor_id;
        $token = my_simple_crypt(floor(microtime(true) * 1000));
        $verification_approve_url = site_url('wp-admin/admin-ajax.php?action=ctoken&status=1&token=' . $token);
        $verification_cancel_url = site_url('wp-admin/admin-ajax.php?action=ctoken&status=0&token=' . $token);
        $wpdb->update(DB_APPOINTMENTS, array("token" => $token, "is_approved" => 0, 'appointment_time' => $appointment_time, 'approval_notification_status' => 1), array("id" => $appointment_id));
        $wpdb->update(DB_APPOINTMENT_INSTRUCTORS, array('approval_notification_status' => 1, 'appt_token' => $token), array("instructor_id" => $ins, "appt_id" => $appointment_id));

        $instructor = $wpdb->get_row("SELECT * FROM " . DB_USERS . " JOIN " . DB_APPOINTMENT_INSTRUCTORS . " as dis on dis.instructor_id = " . DB_USERS . ".ID  WHERE " . DB_USERS . ".ID = " . $ins);

        if ($instructor->approval_notification_status == 0) {

            $instructor_name = $instructor->display_name;
            $inst_email = $instructor->user_email;

            // $instructor_name = $instructor->display_name;
            $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 4", ARRAY_A);
            $inst_msg = $email_instructor['body'];
            $inst_subject = $email_instructor['subject'];

            $inst_split = explode(' - ', $appointment_time);
            $app_time = date('g:i A', strtotime($inst_split[0])) . " - " . date('g:i A', strtotime($inst_split[1]));

            preg_match_all('/{(.*?)}/', $inst_msg, $matches);

            if (in_array("customer_name", $matches[1])) {
                $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
            }
            if (in_array("appointment_date", $matches[1])) {
                $inst_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($getAppointment['appointment_date'])), $inst_msg);
            }
            if (in_array("appointment_time", $matches[1])) {
                $inst_msg = str_replace('{appointment_time}', $app_time, $inst_msg);
            }
            if (in_array("appointment_id", $matches[1])) {
                $inst_msg = str_replace('{appointment_id}', $getAppointment['id'], $inst_msg);
            }
            if (in_array("instructor_name", $matches[1])) {
                $inst_msg = str_replace('{instructor_name}', $instructor_name, $inst_msg);
            }

            $locationid = $getAppointment['location_id'];
            $loc = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id =" . $locationid, ARRAY_A);

            if (in_array("location_name", $matches[1])) {
                $inst_msg = str_replace('{location_name}', $loc['name'], $inst_msg);
            }

            if (in_array("child_name", $matches[1])) {
                $inst_msg = str_replace('{child_name}', $getAppointment['child_id_name'], $inst_msg);
            }

            $headers[] = 'Content-Type: text/html; charset=UTF-8';
            $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
        }
    }
    // }
    // }

    // $instructor = get_user_by('ID', $instructor_id);
    // $email = $instructor->user_email;
    // $instructor_name = $instructor->display_name;

    // $customer_name = $getAppointment['display_name'];

    // $cust_split = explode(' - ', $appointment_time);
    // $app_time = date('g:i A', strtotime($cust_split[0])) . " - " . date('g:i A', strtotime($cust_split[1]));

    echo json_encode(['status' => true, 'message' => 'Instructor has been assigned successfully']);
    die();
}

add_action('wp_ajax_nopriv_SendaprovalNotifications', 'SendaprovalNotifications');
add_action('wp_ajax_SendaprovalNotifications', 'SendaprovalNotifications');
function SendaprovalNotifications()
{

    //     global $wpdb;
    //     $token = my_simple_crypt(time());
    //     $verification_approve_url = site_url('wp-admin/admin-ajax.php?action=ctoken&status=1&token=' . $token);
    //     $verification_cancel_url = site_url('wp-admin/admin-ajax.php?action=ctoken&status=0&token=' . $token);
    //     $get_appointments = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENTS . " JOIN " . DB_USERS . " as us ON us.ID = " . DB_APPOINTMENTS . ".customer_id WHERE approval_notification_status =1", ARRAY_A);

    //     // $wpdb->get_result("SELECT * FROM " . DB_APPOINTMENTS . " WHERE approval_notification_status =1", ARRAY_A);
    //     if(!empty($get_appointments)){

    //         foreach($get_appointments as $appointments){

    //             $instructor_id = $appointments['instructor_id'];
    //             $childname = $appointments['child_id_name'];
    //             $appointment_date = $appointments['appointment_date'];
    //             $appointment_time = $appointments['appointment_time'];
    //             $cust_split = explode(' - ', $appointment_time);
    //             $app_time = date('g:i A', strtotime($cust_split[0])) . " - " . date('g:i A', strtotime($cust_split[1]));
    //             $location = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id = " . $appointments['location_id']);
    //             $location_name = $location->name;
    //             $instructor = get_user_by('ID', $instructor_id);
    //             $email = $instructor->user_email;
    //             $instructor_name = $instructor->display_name;
    //             $customer_name = $appointments->display_name;

    //         //Instructor Email
    //         $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 25", ARRAY_A);
    //         $inst_msg = $email_instructor['body'];
    //         $inst_subject = $email_instructor['subject'];
    //         $inst_email = $instructor->user_email;

    //         preg_match_all('/{(.*?)}/', $inst_msg, $matches);

    //         if (in_array("customer_name", $matches[1])) {
    //             $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
    //         }
    //         if (in_array("child_name", $matches[1])) {
    //             $inst_msg = str_replace('{child_name}', $childname, $inst_msg);
    //         }
    //         if (in_array("appointment_date", $matches[1])) {
    //             $inst_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($appointment_date)), $inst_msg);
    //         }
    //         if (in_array("appointment_time", $matches[1])) {
    //             $inst_msg = str_replace('{appointment_time}', $app_time, $inst_msg);
    //         }
    //         if (in_array("instructor_name", $matches[1])) {
    //             $inst_msg = str_replace('{instructor_name}', $instructor_name, $inst_msg);
    //         }
    //         if (in_array("location_name", $matches[1])) {
    //             $inst_msg = str_replace('{location_name}', $location_name, $inst_msg);
    //         }

    //         if (in_array("login_link", $matches[1])) {
    //             $inst_msg = str_replace('{login_link}', 'https://shootinschool.com/wp-admin', $inst_msg);
    //         }

    //         $inst_msg_sms = $inst_msg;
    //         if (in_array("verification_approve_url", $matches[1])) {
    //             $inst_msg_sms = str_replace('{verification_approve_url}', $verification_approve_url, $inst_msg_sms);
    //             $inst_msg_sms = str_replace('{verification_cancel_url}', $verification_cancel_url, $inst_msg_sms);
    //             $inst_msg = str_replace('{verification_approve_url}', '<a target="_blank" href="' . $verification_approve_url . '"> Approve</a><br>', $inst_msg);
    //             $inst_msg = str_replace('{verification_cancel_url}', '<a target="_blank" href="' . $verification_cancel_url . '"> Approve</a><br>', $inst_msg);
    //         }

    //         $headers[] = 'Content-Type: text/html; charset=UTF-8';
    //         $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
    //         if ($email_instructor['notify_via_email'] == 1) {
    //             try {

    //                 //code...
    //                 wp_mail($inst_email, $inst_subject, $inst_msg, $headers);

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

    //         if ($email_instructor['notify_via_sms'] == 1) {

    //             $inst_msg_sms = str_replace('<br>', "\n", $inst_msg_sms);
    //             $inst_msg_sms = str_replace('&nbsp', " ", $inst_msg_sms);
    //             preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
    //             $phone = get_user_meta($instructor_id, 'billing_billing_phone');
    //             if (count($phone) > 0) {
    //                 foreach ($sms_matches[0] as $match) {

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

    //                     try{
    //                         $number = fetchCountryMobileCode($instructor_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" => $inst_msg_sms, "from" => $twilio_number] );
    //                         array_push($phones,$phone[0]);
    //                     }catch (Exception $e) {
    //                             // die( $e->getCode() . ' : ' . $e->getMessage() );

    //                     }

    //                 }
    //             }
    //         }

    //         $sqlUpdate = $wpdb->update(DB_APPOINTMENTS, array('approval_notification_status' => 2), array("id" => $appointments['id']));

    //         }

    //     }
    //code...
    global $wpdb;

    // get email details

    //    $pending_appintments = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENT_MODIFY." WHERE status=0", ARRAY_A);
    //       // $phones = [];
    //       // $subscribers = [];
    //       foreach ($pending_appintments as $key => $value) {
    //           # code...
    //           $wpdb->update(DB_APPOINTMENTS,array('cust_appointment_time' => $value['suggested_slot']),array('id',$value['appointment_id']));
    //       }

    // get instructors
    $args1 = array(
        'role' => 'siab_instructor',
        'orderby' => 'user_nicename',
        'order' => 'ASC',
    );
    $date = date('Y-m-d');
    // $f_query = "UPDATE ".DB_APPOINTMENTS." SET is_approved = 1 WHERE is_cancelled !=1 AND appointment_date='".$date."' WHERE instructor_id =".$user_id;

    //   $wpdb->update(DB_APPOINTMENTS, array('is_approved' => 1), array('is_cancelled' => 0, 'appointment_date' => $date));
    //   $wpdb->update(DB_APPOINTMENT_MODIFY, array('status' => 1), array('status' => 0));

    $instructors = get_users($args1);
    if ($instructors) {
        foreach ($instructors as $user) {

            $email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 25", ARRAY_A);
            $inst_subject = $email_user['subject'];
            $inst_msg = $email_user['body'];
            $headers = [];
            $headers[] = 'Content-Type: text/html; charset=UTF-8';
            $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
            $user_id = $user->ID;
            $inst_email = "";
            // $approve = '<a target="_blank" href="' . $verification_approve_url . '"> Approve</a>';
            // $cancel = '<a target="_blank" href="' . $verification_cancel_url . '"> Cancel</a>';
            // get todays appointments

            // $query = 'SELECT * FROM ' . DB_APPOINTMENTS . ' WHERE approval_notification_status =1 AND is_cancelled =  0 AND appointment_date="' . $date . '" AND instructor_id="' . $user_id . '" ';
            $query = "SELECT * FROM " . DB_APPOINTMENTS . " JOIN " . DB_USERS . " as us ON us.ID = " . DB_APPOINTMENTS . ".customer_id
            JOIN " . DB_APPOINTMENT_INSTRUCTORS . "
            as ins ON ins.appt_id = " . DB_APPOINTMENTS . ".id  WHERE ins.instructor_id=" . $user_id . " AND ins.approval_notification_status=1 AND ins.is_cancelled =0 AND ins.is_approved =0 ORDER BY ABS(SUBSTRING_INDEX(SUBSTRING_INDEX(appointment_time,'-',1),':',1)) ASC";

            $appointments = $wpdb->get_results($query, ARRAY_A);
            echo "<pre>";
            print_r($appointments);
            // die();
            // error_log(json_encode($query)."----wp_send_schedule_for_the_day");
            $content = "";
            $content_sms = "";
            $details = "";
            $detailsSmsData = "";
            $detailsSms = [];
            $i = 1;
            foreach ($appointments as $appointment) {
                $token = my_simple_crypt(floor(microtime(true) * 1000));
                $verification_approve_url = site_url('wp-admin/admin-ajax.php?action=ctoken&status=1&token=' . $token);
                $verification_cancel_url = site_url('wp-admin/admin-ajax.php?action=ctoken&status=0&token=' . $token);
                error_log(json_encode($query) . "----wp_send_schedule_for_the_day111111");
                $inst_email = $user->user_email;
                // get location detals
                // $location = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id = " . $appointment['location_id']);
                // $location_name = $location->name;
                $instructor_id = $appointment['instructor_id'];
                $childname = $appointment['child_id_name'];
                $appointment_date = $appointment['appointment_date'];
                $appointment_time = $appointment['appointment_time'];
                $cust_split = explode(' - ', $appointment_time);
                $app_time = date('g:i A', strtotime($cust_split[0])) . " - " . date('g:i A', strtotime($cust_split[1]));
                $location = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id = " . $appointment['location_id']);
                $location_name = $location->name;
                $instructor = get_user_by('ID', $instructor_id);
                $email = $instructor->user_email;
                $instructor_name = $instructor->display_name;
                $customer_name = $appointment['display_name'];

                $split_time = explode(' - ', $appointment['appointment_time']);
                $current_app_time = date('g:i A', strtotime($split_time[0])) . " - " . date('g:i A', strtotime($split_time[1]));

                $detailsSmsData .= $i . ". Child Name : " . $childname . "\n" . "Location : " . $location_name . "\n" . "Appointment Date : " . $appointment_date . "\n" . "Appointment Time : " . $current_app_time . "\n\n";
                $details .= "<tr><td><b>Child Name</b></td><td>:</td><td>$childname</td><td><b>Location</b></td><td>:</td><td>$location_name</td><td><b>Appointment Date</b></td><td>:</td><td>$appointment_date</td><td><b>Appointment Time</b></td><td>:</td><td>$current_app_time</td><tr>";
                $sqlUpdate = $wpdb->update(DB_APPOINTMENTS, array('approval_notification_status' => 2, 'token' => $token), array("id" => $appointment['appt_id']));
                $wpdb->update(DB_APPOINTMENT_INSTRUCTORS, array('approval_notification_status' => 2, 'appt_token' => $token), array("instructor_id" => $instructor_id, "appt_id" => $appointment['appt_id']));
                $i++;
                array_push($detailsSms, $detailsSmsData);
            }
            // $links = "<tr><td colspan=7></tr><tr><td colspan=7><b>Please confirm your sessions by clicking here</b> $approve/$cancel</td></tr>";
            $table = "<table>$details</table>";
            // send details
            if (!empty($detailsSms)) {

                // $content = implode("<br/>", $details);
                // $content_sms = implode("<br/>", $details);
                $content = $table;
                $content_sms = $detailsSmsData;

                preg_match_all('/{(.*?)}/', $inst_msg, $matches);
                // preg_match_all('/{(.*?)}/', $inst_msg_sms, $matchesData);
                // $instructor_name = $user->display_name;
                if (in_array("instructor_name", $matches[1])) {
                    $inst_msg = str_replace('{instructor_name}', $user->display_name, $inst_msg);
                    // $inst_msg_sms = str_replace('{instructor_name}', $user->display_name, $inst_msg_sms);
                }
                $inst_msg_sms = $inst_msg;
                if (in_array("content", $matches[1])) {
                    $inst_msg = str_replace('{content}', $content, $inst_msg);
                    // $inst_msg_sms = str_replace('{content}', $content_sms, $inst_msg_sms);
                    $inst_msg_sms = str_replace('{content}', $content_sms, $inst_msg_sms);
                }
                // if (in_array("verification_approve_url", $matches[1])) {
                //     error_log(json_encode($query)."----verification_approve_url");
                //     $inst_msg = str_replace('{verification_approve_url}', $approve, $inst_msg);
                //     // $inst_msg_sms = str_replace('{verification_approve_url}', $approve, $inst_msg_sms);

                // }
                // if (in_array("verification_cancel_url", $matches[1])) {
                //     $inst_msg = str_replace('{verification_cancel_url}', $cancel, $inst_msg);
                //     // $inst_msg_sms = str_replace('{verification_cancel_url}', $cancel, $inst_msg_sms);

                // }

                if (in_array("verification_approve_url", $matches[1])) {
                    $inst_msg_sms = str_replace('{verification_approve_url}', $verification_approve_url, $inst_msg_sms);
                    //   $inst_msg_sms = str_replace('{verification_cancel_url}', $verification_cancel_url, $inst_msg_sms);
                    $inst_msg = str_replace('{verification_approve_url}', '<a target="_blank" href="' . $verification_approve_url . '"> Approve</a><br>', $inst_msg);
                    //   $inst_msg = str_replace('{verification_cancel_url}', '<a target="_blank" href="' . $verification_cancel_url . '"> Cancel</a><br>', $inst_msg);
                    // $inst_msg_sms = str_replace('{verification_approve_url}', '<a target="_blank" href="' . $verification_approve_url . '"> Approve</a><br>', $inst_msg);
                    // $inst_msg_sms = str_replace('{verification_cancel_url}', '<a target="_blank" href="' . $verification_cancel_url . '"> Cancel</a><br>', $inst_msg);
                }

                // send email
                if ($email_user['notify_via_email'] == 1) {
                    try {
                        //code...
                        if ($inst_email != "") {
                            wp_mail($inst_email, $inst_subject, $inst_msg, $headers);
                        }
                    } catch (Exception $th) {
                        //throw $th;
                    }
                }
                // send sms
                if ($email_user['notify_via_sms'] == 1) {

                    $inst_msg_sms = str_replace('<br>', "\n", $inst_msg_sms);
                    $inst_msg_sms = str_replace('&nbsp', " ", $inst_msg_sms);
                    $inst_msg_sms = str_replace(';', " ", $inst_msg_sms);
                    preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);

                    foreach ($sms_matches[0] as $match) {

                        if ($match == "</p>") {
                            $inst_msg_sms = str_replace($match, "\n", $inst_msg_sms);
                        } else {
                            $inst_msg_sms = str_replace($match, '', $inst_msg_sms);
                        }
                    }
                    //Twilio message
                    // $user = get_current_user_id();
                    $phone = get_user_meta($user_id, 'billing_billing_phone');
                    if (count($phone) > 0) {
                        $phones = [];
                        if (!in_array($phone[0], $phones)) {

                            try {
                                if ($inst_email != "") {
                                    $number = fetchCountryMobileCode($user_id) . $phone[0];
                                    //   $number = "+918289899343";
                                    // $json_data = json_encode(['binding_type' => "sms", 'address' => $number]);
                                    // $sid = TWILIO_ID;
                                    // $token = TWILIO_AUTH_TOKEN;
                                    // $notify_sid = TWILIO_NOTIFY_SID;
                                    // $client = new Client($sid, $token);
                                    // $twilio_number = TWILIO_NUMBER;
                                    //                     $request_data = ['toBinding' => $json_data, 'body' => $inst_msg_sms];
                                    //                         // Create a notification
                                    //                         $notification = $client
                                    //                             ->notify->services($notify_sid)
                                    //                             ->notifications->create($request_data);
                                    $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" => $inst_msg_sms, "from" => $twilio_number]
                                    );

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

                            }
                        }
                    }
                }
            }
        }
    }
    echo json_encode(['status' => true, 'message' => 'Notifications Send Successfully']);
    die();
}

add_action('wp_ajax_render_available_timings', 'render_available_timings');
function render_available_timings()
{

    global $wpdb;
    $appointment_id = $_POST['appointment_id'];
    $appointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id =" . $appointment_id, ARRAY_A);
    $location_id = $appointment['location_id'];
    $session_id = $appointment['session_id'];
    $date = $appointment['appointment_date'];

    // 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 availabilities of all instructors on selected date
    $query = "SELECT * FROM " . DB_INSTRUCTORS_AVAILABILITY . " WHERE location_id = " . $location_id . " AND weekday = '$weekday'";
    $timings = $wpdb->get_results($query);

    $start_timing = array();
    $close_timing = array();
    $timing = array();

    foreach ($timings as $time) {

        $query = "SELECT count(*) FROM " . DB_INSTRUCTORS_OFF_DAYS . " WHERE off_day = '$date' AND instructor_id = '$time->instructor_id'";
        $rowCount = $wpdb->get_var($query);

        // 2) Loop through timings and Omit OFF Days
        if ($rowCount > 0) {
            continue;
        }

        $start = $time->start_time;
        $close = $time->end_time;
        if ($start != "" && $close != "") {
            $AddMins = 60 * 60;
            $StartTime = strtotime($start);
            $EndTime = strtotime($close);
            while ($StartTime < $EndTime) {
                array_push($start_timing, $StartTime);
                array_push($close_timing, ($StartTime + $AddMins));
                $StartTime += $AddMins;
            }
        }
    }

    function sortByTime($a, $b)
    {
        return $a - $b;
    }

    usort($start_timing, 'sortByTime');
    usort($close_timing, 'sortByTime');

    for ($i = 0; $i < count($start_timing); $i++) {
        $t = date("G:i", $start_timing[$i]);
        $u = date("G:i", $close_timing[$i]);
        $slot = $t . ' - ' . $u;

        $timing[] = $slot;
    }

    // 3) Retrieve max capacity of selected session type
    $session = $wpdb->get_row("SELECT * FROM " . DB_PACKAGE_SESSIONS . " WHERE id = " . $session_id);
    $max_capacity = (int) $session->max_capacity;
    $final_timing = array();

    // 4) Duplicate existing timings array * max_capacity
    for ($i = 0; $i < $max_capacity; $i++) {
        $final_timing = array_merge($final_timing, $timing);
    }

    // 5) Retrieve existing appointments
    $query = "SELECT appointment_time, appointment_date FROM " . DB_APPOINTMENTS . " WHERE is_cancelled = '0' AND appointment_date = '$date'";
    $current_appointments = $wpdb->get_results($query);
    foreach ($current_appointments as $value) {
        // 6) Omit booked timings, while retaining other instructors availability
        $key = array_search($value->appointment_time, $final_timing);
        if ($key !== false) {
            unset($final_timing[$key]);
        }
    }

    // 7) Remove duplicates
    $final_timing = array_values(array_unique($final_timing));

    // 8) Remove Current Booking Time
    $final_timing = array_diff($final_timing, array($appointment['appointment_time']));

    function sortByTimeSlot($a, $b)
    {
        $a = preg_replace("/[^0-9]/", "", $a);
        $b = preg_replace("/[^0-9]/", "", $b);
        return $a - $b;
    }

    usort($final_timing, function ($a, $b) {
        return (strtotime($a) > strtotime($b));
    });

    $start_timings = [];
    $end_timings = [];
    foreach ($final_timing as $key => $value) {
        # code...
        $cust_split = explode(' - ', $value);
        array_push($start_timings, $cust_split[0]);
        array_push($end_timings, $cust_split[1]);
    }

    $appointment_modify = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENT_MODIFY . " WHERE appointment_id = " . $appointment_id . " AND status = 0", ARRAY_A);

    // 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);

    $open_timing = array();
    $close_timing = array();
    $finalEndTimeArr = '-- Choose --';
    $finalStartTimeArr = '-- Choose --';

    if ($location) {

        $hrsArr = json_decode($location->working_hours, true);
        if ($hrsArr) {
            $open = $hrsArr[$weekday]['open'];
            $close = $hrsArr[$weekday]['close'];

            if ($open != "" && $close != "") {
                $AddMins = 60 * 60;
                $openTime = strtotime($open);
                $closeTime = strtotime($close);
                while ($openTime < $closeTime) {
                    array_push($open_timing, $openTime);
                    array_push($close_timing, ($openTime + $AddMins));
                    $openTime += $AddMins;
                }

                function sortByTime1($a, $b)
                {
                    return $a - $b;
                }

                usort($open_timing, 'sortByTime1');
                usort($close_timing, 'sortByTime1');

                for ($i = 0; $i < count($open_timing); $i++) {
                    $t = date("g:i A", $open_timing[$i]);
                    $u = date("g:i A", $close_timing[$i]);
                    $finalStartTimeArr .= '<option value=' . date("G:i", $open_timing[$i]) . '>' . $t . '</option>';
                    $finalEndTimeArr .= '<option value=' . date("G:i", $close_timing[$i]) . '>' . $u . '</option>';
                }
            }
        }
    }

    ob_start();

    if ($appointment_modify) { ?>

        <div class="modal-body">
            <?php
            $cust_split = explode(' - ', $appointment['cust_appointment_time']);
            $suggested_slot = explode(' - ', $appointment_modify['suggested_slot']);
            ?>
            <p> You have already initiated Appointment time change for
                <?php echo ucfirst($weekday); ?>,
                <?php echo date("F d, Y", strtotime($date)); ?> from <br /><br /> <?php echo date('g:i A', strtotime($cust_split[0])) . " - " . date('g:i A', strtotime($cust_split[1])) ?> TO
                <strong><?php echo date('g:i A', strtotime($suggested_slot[0])) . " - " . date('g:i A', strtotime($suggested_slot[1])) ?></strong>

                <br />
                <hr>
                Customer Approval is in pending stage.
            </p>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-info" data-dismiss="modal">Close</button>
        </div>

    <?php } else { ?>

        <div class="modal-body">
            <?php
            $cust_split = explode(' - ', $appointment['cust_appointment_time']);
            ?>
            <p> Current Appointment Time for
                <?php echo ucfirst($weekday); ?>,
                <?php echo date("F d, Y", strtotime($date)); ?> is
                <strong><?php echo date('g:i A', strtotime($cust_split[0])) . " - " . date('g:i A', strtotime($cust_split[1])) ?></strong>
            </p>
            <hr>
            <div class="row row_modify">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="">Start time</label>
                        <select name="appointment_time" id="new_slot1" class="form-control" required>
                            <option value=""> -- Choose -- </option>
                            <?php // foreach ($start_timings as $time) {
                            //     echo '<option value="'.$time.'"> '.date('g:i A',strtotime($time)).' </option>';
                            // }
                            echo $finalStartTimeArr;
                            ?>
                        </select>
                    </div>
                </div>
                <!-- </div> -->
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="">End time</label>
                        <select name="appointment_time" id="new_slot2" class="form-control" required>
                            <option value=""> -- Choose -- </option>
                            <?php //foreach ($end_timings as $time) {
                            //     echo '<option value="'.$time.'"> '.date('g:i A',strtotime($time)).' </option>';
                            // }
                            echo $finalEndTimeArr;
                            ?>
                        </select>
                    </div>
                </div>
            </div>
            <!-- </div> -->
            <div class="modal-footer">
                <button type="button" id="saveBtn" data-appointment_id="" onclick="saveNewTimings(this)" class="btn btn-primary">Modify Appointment Time</button>
                <button type="button" class="btn btn-info" data-dismiss="modal">Cancel</button>
            </div>

        <?php }

    $renderedHtml = ob_get_clean();

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

add_action('wp_ajax_request_timing_change', 'request_timing_change');
function request_timing_change()
{

    global $wpdb;
    $appointment_id = $_POST['appt_id'];
    $new_slot1 = $_POST['new_slot1'];
    $app_start = $_POST['new_slot1'];
    $new_slot2 = $_POST['new_slot2'];
    $app_end = $_POST['new_slot2'];
    $appointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id =" . $appointment_id, ARRAY_A);
    $date = $appointment['appointment_date'];
    $appointment_date = $appointment['appointment_date'];

    /////////////////Validation starts////////////////
    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 = " . $appointment['location_id']);

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

    // if(($appointment['session_id'] == 1) || ($appointment['session_id'] == 2)){

    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();
        // }
    }
    // }

    ///////////////////////Validation Ends///////////////
    // 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);

    $query = "SELECT DISTINCT * FROM " . DB_USERS . " JOIN " . DB_APPOINTMENTS . " ON " . DB_APPOINTMENTS . ".customer_id=" . DB_USERS . ".ID WHERE " . DB_APPOINTMENTS . ".id=" . $appointment_id;
    $rowData = $wpdb->get_row($query, ARRAY_A);

    $split_time = explode(' - ', $appointment['cust_appointment_time']);
    $current_app_time = date('g:i A', strtotime($split_time[0])) . " - " . date('g:i A', strtotime($split_time[1]));
    $currDateTime = date("l, F d Y", strtotime($date)) . ' : ' . $current_app_time;
    $token = my_simple_crypt(time());

    $verification_url = site_url('wp-admin/admin-ajax.php?status=1&action=ftoken&token=' . $token);
    $rejected_url = site_url('wp-admin/admin-ajax.php?status=2&action=ftoken&token=' . $token);

    $suggested_slot = $new_slot1 . " - " . $new_slot2;
    $args = array(
        "appointment_id" => $appointment_id,
        "suggested_slot" => $suggested_slot,
        "token" => $token,
    );
    if ($wpdb->insert(DB_APPOINTMENT_MODIFY, $args)) {

        $suggested_slot = date('g:i A', strtotime($new_slot1)) . " - " . date('g:i A', strtotime($new_slot2));

        // Email the user
        $email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 17", ARRAY_A);
        $cust_msg = $email_user['body'];
        $cust_subject = $email_user['subject'];
        $email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 49", ARRAY_A);
        $admin_msg = $email_admin['body'];
        $admin_subject = $email_admin['subject'];
        preg_match_all('/{(.*?)}/', $cust_msg, $matches);

        if (in_array("customer_name", $matches[1])) {
            $cust_msg = str_replace('{customer_name}', $rowData['display_name'], $cust_msg);
            $admin_msg = str_replace('{customer_name}', $rowData['display_name'], $admin_msg);
        }
        if (in_array("current_appt_date_time", $matches[1])) {
            $cust_msg = str_replace('{current_appt_date_time}', $currDateTime, $cust_msg);
            $admin_msg = str_replace('{current_appt_date_time}', $currDateTime, $admin_msg);
        }
        if (in_array("new_timeslot", $matches[1])) {
            $cust_msg = str_replace('{new_timeslot}', $suggested_slot, $cust_msg);
            $admin_msg = str_replace('{new_timeslot}', $suggested_slot, $admin_msg);
        }
        if (in_array("child_name", $matches[1])) {
            $cust_msg = str_replace('{child_name}', $appointment['child_id_name'], $cust_msg);
            $admin_msg = str_replace('{child_name}', $appointment['child_id_name'], $admin_msg);
        }
        if (in_array("appointment_time", $matches[1])) {
            $cust_msg = str_replace('{appointment_time}', $current_app_time, $cust_msg);
            $admin_msg = str_replace('{appointment_time}', $current_app_time, $admin_msg);
        }
        if (in_array("appointment_date", $matches[1])) {
            $cust_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($appointment['appointment_date'])), $cust_msg);
            $admin_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($appointment['appointment_date'])), $admin_msg);
        }

        $locationid = $appointment['location_id'];
        $loc = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id =" . $locationid, ARRAY_A);

        if (in_array("location", $matches[1])) {
            $cust_msg = str_replace('{location}', $loc['name'], $cust_msg);
            $admin_msg = str_replace('{location}', $loc['name'], $admin_msg);
        }

        $cust_msg_sms = $cust_msg;

        if (in_array("verification_url", $matches[1])) {
            $cust_msg = str_replace('{verification_url}', '<a target="_blank" href="' . $verification_url . '"> Click </a><br>', $cust_msg);
            $admin_msg = str_replace('{verification_url}', '<a target="_blank" href="' . $verification_url . '"> Click </a><br>', $admin_msg);
        }
        if (in_array("rejected_url", $matches[1])) {
            $cust_msg = str_replace('{rejected_url}', '<a target="_blank" href="' . $rejected_url . '"> Click </a><br>', $cust_msg);
            $admin_msg = str_replace('{rejected_url}', '<a target="_blank" href="' . $rejected_url . '"> Click </a><br>', $admin_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) {
            wp_mail($rowData['user_email'], $cust_subject, $cust_msg, $headers);
        }
        $argsadmin = array(
            'role' => 'administrator',
            'orderby' => 'user_nicename',
            'order' => 'ASC',
        );
        $administrator = get_users($argsadmin);
        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() );

                        }
                    }
                }
            }
        }

        if ($email_user['notify_via_sms'] == 1) {

            if (in_array("verification_url", $matches[1])) {
                $cust_msg_sms = str_replace('{verification_url}', $verification_url, $cust_msg_sms);
            }
            if (in_array("rejected_url", $matches[1])) {
                $cust_msg_sms = str_replace('{rejected_url}', $rejected_url, $cust_msg_sms);
            }
            $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($rowData['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($rowData['ID']) . $phone[0],
                //     'message' => $cust_msg_sms
                // );
                // twl_send_sms($args);
                $phones = [];
                if (!in_array($phone[0], $phones)) {

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

                    }
                }
            }
        }

        echo json_encode(['status' => true, 'message' => 'Customer has notified about Appointment Time Change Suggestion.']);
    } else {
        echo json_encode(['status' => false, 'message' => 'Operation failed.']);
    }

    die();
}
add_action('wp_ajax_instructor_approval', 'instructor_approval');
function instructor_approval()
{

    $appointment_id = $_REQUEST['pass_appointment_id'];
    $instructor_id = $_REQUEST['instructor_id'];
    global $wpdb;
    $getAppointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " JOIN " . DB_USERS . " as us ON us.ID = " . DB_APPOINTMENTS . ".customer_id WHERE " . DB_APPOINTMENTS . ".id =" . $appointment_id, ARRAY_A);
    $instructor = get_user_by('ID', $instructor_id);
    $email = $instructor->user_email;
    $instructor_name = $instructor->display_name;
    $customer_name = $getAppointment['display_name'];
    $appointment_date = $getAppointment['appointment_date'];
    $appointment_time = $getAppointment['appointment_time'];
    $token = my_simple_crypt(time());
    $verification_approve_url = site_url('wp-admin/admin-ajax.php?action=ctoken&status=1&token=' . $token);
    $verification_cancel_url = site_url('wp-admin/admin-ajax.php?action=ctoken&status=0&token=' . $token);

    $sqlUpdate = $wpdb->update(DB_APPOINTMENTS, array("token" => $token), array("id" => $appointment_id));

    if ($sqlUpdate) {

        //Instructor Email
        $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 25", ARRAY_A);
        $inst_msg = $email_instructor['body'];
        $inst_subject = $email_instructor['subject'];
        $inst_email = $instructor->user_email;

        $location = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id = " . $getAppointment['location_id']);
        $location_name = $location->name;

        preg_match_all('/{(.*?)}/', $inst_msg, $matches);
        $inst_split = explode(' - ', $appointment_time);
        $app_time = date('g:i A', strtotime($inst_split[0])) . " - " . date('g:i A', strtotime($inst_split[1]));
        if (in_array("customer_name", $matches[1])) {
            $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
        }
        if (in_array("child_name", $matches[1])) {
            $inst_msg = str_replace('{child_name}', $getAppointment['child_id_name'], $inst_msg);
        }
        if (in_array("appointment_date", $matches[1])) {
            $inst_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($appointment_date)), $inst_msg);
        }
        if (in_array("appointment_time", $matches[1])) {
            $inst_msg = str_replace('{appointment_time}', $app_time, $inst_msg);
        }
        if (in_array("instructor_name", $matches[1])) {
            $inst_msg = str_replace('{instructor_name}', $instructor_name, $inst_msg);
        }
        if (in_array("location_name", $matches[1])) {
            $inst_msg = str_replace('{location_name}', $location_name, $inst_msg);
        }
        if (in_array("login_link", $matches[1])) {
            $inst_msg = str_replace('{login_link}', 'https://shootinschool.com/wp-admin', $inst_msg);
        }

        $inst_msg_sms = $inst_msg;
        if (in_array("verification_approve_url", $matches[1])) {
            $inst_msg_sms = str_replace('{verification_approve_url}', $verification_approve_url, $inst_msg_sms);
            $inst_msg_sms = str_replace('{verification_cancel_url}', $verification_cancel_url, $inst_msg_sms);
            $inst_msg = str_replace('{verification_approve_url}', '<a target="_blank" href="' . $verification_approve_url . '"> Approve</a><br>', $inst_msg);
            $inst_msg = str_replace('{verification_cancel_url}', '<a target="_blank" href="' . $verification_cancel_url . '"> Approve</a><br>', $inst_msg);
        }
        $headers[] = 'Content-Type: text/html; charset=UTF-8';
        $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
        if ($email_instructor['notify_via_email'] == 1) {
            try {
                //code...
                wp_mail($inst_email, $inst_subject, $inst_msg, $headers);
            } catch (Exception $th) {
                //throw $th;
            }
        }

        if ($email_instructor['notify_via_sms'] == 1) {
            //             $inst_msg_sms = $inst_msg;
            $inst_msg_sms = str_replace('<br>', "\n", $inst_msg_sms);
            $inst_msg_sms = str_replace('&nbsp', " ", $inst_msg_sms);
            preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
            $phone = get_user_meta($instructor_id, 'billing_billing_phone');
            if (count($phone) > 0) {
                foreach ($sms_matches[0] as $match) {
                    if ($match == "</p>") {
                        $inst_msg_sms = str_replace($match, "\n", $inst_msg_sms);
                    } else {
                        $inst_msg_sms = str_replace($match, '', $inst_msg_sms);
                    }
                }
                //Twilio message
                // $args = array(
                //     'number_to' => fetchCountryMobileCode($instructor_id) . $phone[0],
                //     'message' => $inst_msg_sms
                // );
                //                 $args = array(
                //                     'number_to' => "+919809144184",
                //                     'message' => $inst_msg_sms
                //                 );
                // twl_send_sms($args);
                $phones = [];
                if (!in_array($phone[0], $phones)) {

                    try {
                        $number = fetchCountryMobileCode($instructor_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" => $inst_msg_sms, "from" => $twilio_number]
                        );
                        array_push($phones, $phone[0]);
                    } catch (Exception $e) {
                        // die( $e->getCode() . ' : ' . $e->getMessage() );

                    }
                }
            }
        }
        echo json_encode(['status' => true, 'message' => 'Instructor has notified about Appointment Approval.']);
    } else {
        echo json_encode(['status' => false, 'message' => 'Operation failed.']);
    }

    die();
}

add_action('wp_ajax_fetch_remaining_appointments', 'fetch_remaining_appointments');
function fetch_remaining_appointments()
{

    global $wpdb;
    $appointment_ids = $_POST['appt_ids'];
    $appointment = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id IN (" . $appointment_ids . ")", ARRAY_A);
    $session_id = $appointment[0]['session_id'];

    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];

    $query = "SELECT appts.child_id_name,appts.appointment_date, appts.appointment_time, GROUP_CONCAT(appts.id SEPARATOR '|') AS grouped_appts_ids, COUNT(appts.id) as occurance, ps.session_name FROM " . DB_APPOINTMENTS . " AS appts JOIN " . DB_PACKAGE_SESSIONS . " as ps ON ps.id = appts.session_id WHERE appts.is_cancelled = 0 AND (ps.session_type = 'group' OR ps.session_type = 'individual') AND appts.appointment_date >= '" . $start_date . "' AND appts.appointment_date <= '" . $end_date . "' AND appts.has_attended IS NULL AND appts.id NOT IN (" . $appointment_ids . ") GROUP BY appts.id ORDER BY appts.id DESC";
    $fetchAppts = $wpdb->get_results($query, ARRAY_A);

    ob_start(); ?>

        <h4>Choose Session to be Merged</h4>
        <select name="sel_second_session" id="sel_second_session" onchange="second_first_change();">
            <option value=""> -- Choose an Session -- </option>
            <?php foreach ($fetchAppts as $single) { ?>
                <option value="<?php echo $single['grouped_appts_ids'] . '|' . $single['occurance']; ?>">
                    <?php echo $single['child_id_name']; ?> - <?php echo date('l, F d Y ', strtotime($single['appointment_date'])); ?>
                </option>
            <?php } ?>
        </select>

        <br /><br />

        <div id="s_add_details"></div>

    <?php $renderedHtml = ob_get_clean();

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

add_action('wp_ajax_fetch_available_instructors', 'fetch_available_instructors');
function fetch_available_instructors()
{

    global $wpdb;
    $appt_ids_one = $_POST['appt_ids_one']; // Parent Session with appointment IDs
    $appt_ids_two = $_POST['appt_ids_two']; // Sessions with appointment IDs to be merged

    $appointment = $wpdb->get_results("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id IN (" . $appt_ids_one . ")");
    $getAppointment = $appointment[0];

    $location_id = $getAppointment->location_id;
    $session_id = $getAppointment->session_id;
    $date = date("Y-m-d", strtotime($getAppointment->appointment_date));

    $appointment_time = $getAppointment->appointment_time;

    // 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 availabilities of all instructors on selected date
    $query = "SELECT *, instructor_id as ins_id FROM " . DB_INSTRUCTORS_AVAILABILITY . " WHERE location_id = " . $location_id . " AND weekday = '$weekday'";
    $timings = $wpdb->get_results($query);

    $dataArr = array();
    foreach ($timings as $time) {

        $query = "SELECT count(*) FROM " . DB_INSTRUCTORS_OFF_DAYS . " WHERE off_day = '$date' AND instructor_id = '$time->instructor_id'";
        $rowCount = $wpdb->get_var($query);

        // 2) Loop through timings and Omit OFF Days
        if ($rowCount > 0) {
            continue;
        }

        $start = $time->start_time;
        $close = $time->end_time;
        if ($start != "" && $close != "") {
            $AddMins = 60 * 60;
            $StartTime = strtotime($start);
            $EndTime = strtotime($close);
            while ($StartTime < $EndTime) {
                $t = date("g:i A", $StartTime);
                $u = date("g:i A", ($StartTime + $AddMins));
                $slot = $t . ' - ' . $u;

                $dataArr[] = array("instructor_id" => $time->ins_id, "available_time" => $slot);
                $StartTime += $AddMins;
            }
        }
    }

    // 3) Retrieve max capacity of selected session type
    $session = $wpdb->get_row("SELECT * FROM " . DB_PACKAGE_SESSIONS . " WHERE id = " . $session_id);
    $max_capacity = (int) $session->max_capacity;
    $final_timing = array();

    // 4) Duplicate existing timings array * max_capacity
    for ($i = 0; $i < $max_capacity; $i++) {
        $final_timing = array_merge($final_timing, $dataArr);
    }

    // 5) Retrieve existing appointments
    $query = "SELECT * FROM " . DB_APPOINTMENTS . " as appts  JOIN " . DB_APPOINTMENT_INSTRUCTORS . "
    as ins ON ins.appt_id = appts.id  WHERE ins.instructor_id IS NOT NULL AND appts.is_cancelled = '0' AND appts.appointment_date = '$date'";
    $current_appointments = $wpdb->get_results($query, ARRAY_A);
    foreach ($current_appointments as $value) {

        // 6) Omit booked timings, while retaining other instructors availability
        $key = array_search($value['instructor_id'], array_column($final_timing, 'instructor_id'));
        if ($key !== false) {
            if ($value['appointment_time'] == $final_timing[$key]['available_time']) {
                unset($final_timing[$key]);
            }
        }
    }

    // Retrive only matched instructors IDs
    $filteredArr = array_filter($final_timing, function ($value) use ($appointment_time) {
        return $value['available_time'] == $appointment_time;
    });

    // Fetch matched instructors IDs as single array
    $available_instructors_id = array_column($filteredArr, 'instructor_id');

    // Add the ids of appt_ids_one
    $fetch_parent_appts = $wpdb->get_results("SELECT ins.instructor_id FROM " . DB_APPOINTMENTS . " as appts JOIN " . DB_APPOINTMENT_INSTRUCTORS . "
    as ins ON ins.appt_id = appts.id WHERE appts.id IN (" . $appt_ids_one . ") AND ins.instructor_id IS NOT NULL", ARRAY_A);
    if (count($fetch_parent_appts > 0)) {
        foreach ($fetch_parent_appts as $single) {
            $available_instructors_id[] = $single['instructor_id'];
        }
    }
    $available_instructors_id = array_unique($available_instructors_id);

    $instructors = $wpdb->get_results("SELECT * FROM " . DB_USERS . " WHERE ID IN (" . implode(',', $available_instructors_id) . ")");

    ob_start(); ?>

        <hr>
        <div class="row">
            <div class="col-md-6 col-md-offset-3">
                <div class="form-group">
                    <label for="">Choose an Available Instructor for the Merged Session</label>
                    <select multiple="multiple" onchange="getMergeMessage(this)" name="assign_instructor[]" id="assign_instructor" class="form-control" required>

                        <?php foreach ($instructors as $instructor) { ?>
                            <option value="<?php echo $instructor->ID; ?>"> <?php echo $instructor->display_name; ?> </option>
                        <?php } ?>
                    </select>
                </div>
            </div>
        </div>

    <?php $renderedHtml = ob_get_clean();

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

add_action('wp_ajax_merge_sessions', 'merge_sessions');
function merge_sessions()
{

    global $wpdb;

    parse_str($_POST['form_data'], $form_data); //This will convert the string to array
    $sel_first_session = explode('|', $form_data['sel_first_session']);
    array_pop($sel_first_session);
    $sel_second_session = explode('|', $form_data['sel_second_session']);
    array_pop($sel_second_session);

    $assign_instructor = $form_data['assign_instructor'];

    // var_dump($_POST);
    // exit();

    // Parent Session with appointment IDs
    foreach ($sel_first_session as $single) {
        $appointment = $wpdb->get_row("SELECT DISTINCT * FROM " . DB_USERS . " JOIN " . DB_APPOINTMENTS . " ON " . DB_APPOINTMENTS . ".customer_id=" . DB_USERS . ".ID  JOIN " . DB_APPOINTMENT_INSTRUCTORS . "
        as ins ON ins.appt_id = " . DB_APPOINTMENTS . ".id  WHERE " . DB_APPOINTMENTS . ".id = '$single'", ARRAY_A);

        $finalApptDate = $appointment['appointment_date'];
        $finalApptTime = $appointment['appointment_time'];
        $instructor_id = $appointment['instructor_id'];

        $final_location = $appointment['location_id'];
        $wpdb->query("DELETE FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE `appt_id` = '$single'");
        // if ($instructor_id != $assign_instructor) {
        $wpdb->update(DB_APPOINTMENTS, array('session_id' => 1), array('id' => $single));
        // $args = array(
        //     "appt_id" => $single,
        //     "instructor_id" => $assign_instructor,
        // );
        $wpdb->update(DB_APPOINTMENTS, array('instructor_id' => null), array("id" => $single));
        foreach ($assign_instructor as $ins) {
            if (count($assign_instructor) == 1) {
                $wpdb->update(DB_APPOINTMENTS, array('instructor_id' => $ins), array("id" => $single));
            }
            $args = array(
                "appt_id" => $single,
                "instructor_id" => $ins,
                "approval_notification_status" => 1,
            );
            $wpdb->insert(DB_APPOINTMENT_INSTRUCTORS, $args);
        }


        // Mail to Customer and Instructor regarding change
        $instructor = get_user_by('ID', $assign_instructor);
        $email = $instructor->user_email;
        $instructor_name = $instructor->display_name;

        $customer_name = $appointment['display_name'];
        $appointment_date = $appointment['appointment_date'];
        $appointment_time = $appointment['appointment_time'];

        //Instructor Email
        // $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 4", ARRAY_A);
        // $inst_msg = $email_instructor['body'];
        // $inst_subject = $email_instructor['subject'];
        // $inst_email = $instructor->user_email;

        // $location = $wpdb->get_row("SELECT * FROM ".DB_COACHING_LOCATIONS." WHERE id = ".$appointment['location_id']);
        // $location_name = $location->name;

        // preg_match_all('/{(.*?)}/', $inst_msg, $matches);
        // $split_time = explode(' - ',$appointment_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])) {
        //     $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
        // }
        // if (in_array("appointment_date", $matches[1])) {
        //     $inst_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($appointment_date)), $inst_msg);
        // }
        // if (in_array("appointment_time", $matches[1])) {
        //     $inst_msg = str_replace('{appointment_time}', $current_app_time, $inst_msg);
        // }
        // if (in_array("instructor_name", $matches[1])) {
        //     $inst_msg = str_replace('{instructor_name}', $instructor_name, $inst_msg);
        // }
        // if (in_array("location_name", $matches[1])) {
        //     $inst_msg = str_replace('{location_name}', $location_name, $inst_msg);
        // }

        // $headers[] = 'Content-Type: text/html; charset=UTF-8';
        // $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
        // if($email_instructor['notify_via_email'] == 1){
        //     wp_mail($inst_email, $inst_subject, $inst_msg, $headers);
        // }

        // if($email_instructor['notify_via_sms'] == 1){
        //     $inst_msg_sms=$inst_msg;
        //     $inst_msg_sms = str_replace('<br>',"\n",$inst_msg_sms);
        //     $inst_msg_sms = str_replace('&nbsp'," ",$inst_msg_sms);
        //     preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
        //     $phone = get_user_meta( $assign_instructor, 'billing_billing_phone');
        //     if(count($phone)>0){
        //         foreach($sms_matches[0] as $match){
        //             $inst_msg_sms = str_replace($match,'',$inst_msg_sms);
        //         }
        //         //Twilio message
        //         $args = array(
        //             'number_to'=> fetchCountryMobileCode($assign_instructor) . $phone[0],
        //             'message' =>$inst_msg_sms
        //         );
        //         twl_send_sms( $args );
        //     }
        // }

        // Customer Email
        // $email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 5", ARRAY_A);
        // $cust_msg = $email_user['body'];
        // $cust_email = $appointment['user_email'];
        // $cust_subject = $email_user['subject'];

        // preg_match_all('/{(.*?)}/', $cust_msg, $matches);
        // //time split up
        // $split_time = explode(' - ',$appointment_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}', $customer_name, $cust_msg);
        // }
        // if (in_array("appointment_date", $matches[1])) {
        //     $cust_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($appointment_date)), $cust_msg);
        // }
        // if (in_array("appointment_time", $matches[1])) {
        //     $cust_msg = str_replace('{appointment_time}', $current_app_time, $cust_msg);
        // }
        // if (in_array("instructor_name", $matches[1])) {
        //     $cust_msg = str_replace('{instructor_name}', $instructor_name, $cust_msg);
        // }
        // if (in_array("location_name", $matches[1])) {
        //     $cust_msg = str_replace('{location_name}', $location_name, $cust_msg);
        // }

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

        // 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($appointment['customer_id'], 'billing_billing_phone');
        //     if(count($phone)>0){
        //         foreach($sms_matches[0] as $match){
        //             $cust_msg_sms = str_replace($match,'',$cust_msg_sms);
        //         }
        //         //Twilio message
        //         $args = array(
        //             'number_to'=> fetchCountryMobileCode($appointment['customer_id']) . $phone[0],
        //             'message' => $cust_msg_sms
        //         );
        //         twl_send_sms( $args );
        //     }
        // }
        // }
    }

    // Sessions with appointment IDs to be merged
    foreach ($sel_second_session as $single) {
        $appointment = $wpdb->get_row("SELECT DISTINCT * FROM " . DB_USERS . " JOIN " . DB_APPOINTMENTS . " ON " . DB_APPOINTMENTS . ".customer_id=" . DB_USERS . ".ID  JOIN " . DB_APPOINTMENT_INSTRUCTORS . "
        as ins ON ins.appt_id = " . DB_APPOINTMENTS . ".id  WHERE " . DB_APPOINTMENTS . ".id = '$single'", ARRAY_A);
        $appointment_date = $appointment['appointment_date'];
        $appointment_time = $appointment['appointment_time'];
        $instructor_id = $appointment['instructor_id'];
        $location_id = $appointment['location_id'];
        $customer_id = $appointment['customer_id'];

        if ($appointment_date != $finalApptDate || $appointment_time != $finalApptTime || $location_id != $final_location) {
            $wpdb->update(DB_APPOINTMENTS, array('appointment_date' => $finalApptDate, "appointment_time" => $finalApptTime, 'location_id' => $final_location, 'session_id' => 1), array('id' => $single));

            // Mail to Customer regarding change
            $unixTimestamp = strtotime($appointment_date);
            $dayOfWeek = date("l", $unixTimestamp);
            $weekday = strtolower($dayOfWeek);
            // $currDateTime = ucfirst($weekday) . ', ' . date("l, F d Y", strtotime($date)) . ' : ' . $appointment['appointment_time'];
            $currDateTime = ucfirst($weekday) . " " . $appointment['appointment_date'];

            // $query = "SELECT DISTINCT * FROM " . DB_USERS . " JOIN " . DB_APPOINTMENTS . " ON " . DB_APPOINTMENTS . ".customer_id=" . DB_USERS . ".ID GROUP BY " . DB_APPOINTMENTS . ".id";
            $query = "SELECT  * FROM " . DB_USERS . " JOIN " . DB_APPOINTMENTS . " ON " . DB_APPOINTMENTS . ".customer_id=" . DB_USERS . ".ID WHERE " . DB_APPOINTMENTS . ".ID=" . $single . " GROUP BY " . DB_APPOINTMENTS . ".id";
            $rowData = $wpdb->get_row($query, ARRAY_A);

            // Email the user
            $email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 17", ARRAY_A);
            $cust_msg = $email_user['body'];
            $cust_subject = $email_user['subject'];
            $cust_mailID = $email_user['subject'];
            $email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 49", ARRAY_A);
            $admin_msg = $email_admin['body'];
            $admin_subject = $email_admin['subject'];
            $token = my_simple_crypt(time());

            $verification_url = site_url('wp-admin/admin-ajax.php?status=1&action=ftoken&token=' . $token);
            $rejected_url = site_url('wp-admin/admin-ajax.php?status=2&action=ftoken&token=' . $token);
            $args = array(
                "appointment_id" => $single,
                "suggested_slot" => $finalApptTime,
                "token" => $token,
            );
            $wpdb->insert(DB_APPOINTMENT_MODIFY, $args);
            preg_match_all('/{(.*?)}/', $cust_msg, $matches);

            if (in_array("customer_name", $matches[1])) {
                $cust_msg = str_replace('{customer_name}', $appointment['display_name'], $cust_msg);
                $admin_msg = str_replace('{customer_name}', $appointment['display_name'], $admin_msg);
            }
            if (in_array("current_appt_date_time", $matches[1])) {
                $cust_msg = str_replace('{current_appt_date_time}', $currDateTime, $cust_msg);
                $admin_msg = str_replace('{current_appt_date_time}', $currDateTime, $admin_msg);
            }
            if (in_array("new_timeslot", $matches[1])) {
                $split_time = explode(' - ', $finalApptTime);
                $current_app_time = date('g:i A', strtotime($split_time[0])) . " - " . date('g:i A', strtotime($split_time[1]));
                $cust_msg = str_replace('{new_timeslot}', $current_app_time, $cust_msg);
                $admin_msg = str_replace('{new_timeslot}', $current_app_time, $admin_msg);
            }
            if (in_array("verification_url", $matches[1])) {
                $cust_msg = str_replace('{verification_url}', '<a target="_blank" href="' . $verification_url . '"> Click </a><br>', $cust_msg);
                $admin_msg = str_replace('{verification_url}', '<a target="_blank" href="' . $verification_url . '"> Click </a><br>', $admin_msg);
                // $cust_msg = str_replace('{verification_url}', $verification_url, $cust_msg);
                // $admin_msg = str_replace('{verification_url}', $verification_url, $admin_msg);
            }

            if (in_array("rejected_url", $matches[1])) {
                $cust_msg = str_replace('{rejected_url}', '<a target="_blank" href="' . $rejected_url . '"> Click </a><br>', $cust_msg);
                $admin_msg = str_replace('{rejected_url}', '<a target="_blank" href="' . $rejected_url . '"> Click </a><br>', $admin_msg);
                // $cust_msg = str_replace('{rejected_url}', $rejected_url, $cust_msg);
                // $admin_msg = str_replace('{rejected_url}', $rejected_url, $admin_msg);
            }
            if (in_array("child_name", $matches[1])) {
                $cust_msg = str_replace('{child_name}', $rowData['child_id_name'], $cust_msg);
                $admin_msg = str_replace('{child_name}', $rowData['child_id_name'], $admin_msg);
            }
            if (in_array("appointment_time", $matches[1])) {
                $cust_msg = str_replace('{appointment_time}', $appointment_time, $cust_msg);
                $admin_msg = str_replace('{appointment_time}', $appointment_time, $admin_msg);
            }
            $locationid = $appointment['location_id'];
            $loc = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id =" . $locationid, ARRAY_A);

            if (in_array("location", $matches[1])) {
                $cust_msg = str_replace('{location}', $loc['name'], $cust_msg);
                $admin_msg = str_replace('{location}', $loc['name'], $admin_msg);
            }

            $headers[] = 'Content-Type: text/html; charset=UTF-8';
            $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
            if ($email_user['notify_via_email'] == 1) {
                wp_mail($rowData['user_email'], $cust_subject, $cust_msg, $headers);
            }
            $argsadmin = array(
                'role' => 'administrator',
                'orderby' => 'user_nicename',
                'order' => 'ASC',
            );
            $administrator = get_users($argsadmin);
            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() );

                            }
                        }
                    }
                }
            }

            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($rowData['customer_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($rowData['customer_id']) . $phone[0],
                    //     'message' => $cust_msg_sms
                    // );
                    // twl_send_sms($args);
                    $phones = [];
                    if (!in_array($phone[0], $phones)) {

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

                        }
                    }
                }
            }
        }

        // if ($instructor_id != $assign_instructor) {
        // $wpdb->update(DB_APPOINTMENTS, array('instructor_id' => $assign_instructor), array('id' => $single));
        $wpdb->query("DELETE FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE `appt_id` = '$single'");
        $wpdb->update(DB_APPOINTMENTS, array('instructor_id' => null), array("id" => $single));
        $wpdb->update(DB_APPOINTMENTS, array('instructor_id' => null), array("id" => $single));
        foreach ($assign_instructor as $ins) {
            if (count($assign_instructor) == 1) {
                $wpdb->update(DB_APPOINTMENTS, array('instructor_id' => $ins), array("id" => $single));
            }
            $args = array(
                "appt_id" => $single,
                "instructor_id" => $ins,
                "approval_notification_status" => 1,
            );
            $wpdb->insert(DB_APPOINTMENT_INSTRUCTORS, $args);
        }

        // Mail to Customer and Instructor regarding change
        $instructor = get_user_by('ID', $assign_instructor);
        $email = $instructor->user_email;
        $instructor_name = $instructor->display_name;

        $customer_name = $appointment['display_name'];
        $appointment_date = $appointment['appointment_date'];
        $appointment_time = $appointment['appointment_time'];

        // //Instructor Email
        // $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 4", ARRAY_A);
        // $inst_msg = $email_instructor['body'];
        // $inst_subject = $email_instructor['subject'];
        // $inst_email = $instructor->user_email;

        // $location = $wpdb->get_row("SELECT * FROM ".DB_COACHING_LOCATIONS." WHERE id = ".$appointment['location_id']);
        // $location_name = $location->name;

        // preg_match_all('/{(.*?)}/', $inst_msg, $matches);
        // $split_time = explode(' - ',$appointment_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])) {
        //     $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
        // }
        // if (in_array("appointment_date", $matches[1])) {
        //     $inst_msg = str_replace('{appointment_date}', date('l, F d Y ', strtotime($appointment_date)), $inst_msg);
        // }
        // if (in_array("appointment_time", $matches[1])) {
        //     $inst_msg = str_replace('{appointment_time}', $current_app_time, $inst_msg);
        // }
        // if (in_array("instructor_name", $matches[1])) {
        //     $inst_msg = str_replace('{instructor_name}', $instructor_name, $inst_msg);
        // }
        // if (in_array("location_name", $matches[1])) {
        //     $inst_msg = str_replace('{location_name}', $location_name, $inst_msg);
        // }

        // $headers[] = 'Content-Type: text/html; charset=UTF-8';
        // $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
        // if($email_instructor['notify_via_email'] == 1){
        //     wp_mail($inst_email, $inst_subject, $inst_msg, $headers);
        // }

        // if($email_instructor['notify_via_sms'] == 1){
        //     $inst_msg_sms=$inst_msg;
        //     $inst_msg_sms = str_replace('<br>',"\n",$inst_msg_sms);
        //     $inst_msg_sms = str_replace('&nbsp'," ",$inst_msg_sms);
        //     preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
        //     $phone = get_user_meta( $assign_instructor, 'billing_billing_phone');
        //     if(count($phone)>0){
        //         foreach($sms_matches[0] as $match){
        //             $inst_msg_sms = str_replace($match,'',$inst_msg_sms);
        //         }
        //         //Twilio message
        //         $args = array(
        //             'number_to'=> fetchCountryMobileCode($assign_instructor) . $phone[0],
        //             'message' =>$inst_msg_sms
        //         );
        //         twl_send_sms( $args );
        //     }
        // }

        // // Customer Email
        // $email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 5", ARRAY_A);
        // $cust_msg = $email_user['body'];
        // $cust_email = $appointment['user_email'];
        // $cust_subject = $email_user['subject'];

        // preg_match_all('/{(.*?)}/', $cust_msg, $matches);
        // //time split up
        // $split_time = explode(' - ',$appointment_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}', $customer_name, $cust_msg);
        // }
        // if (in_array("appointment_date", $matches[1])) {
        //     $cust_msg = str_replace('{appointment_date}',date('l, F d Y ', strtotime($appointment_date)), $cust_msg);
        // }
        // if (in_array("appointment_time", $matches[1])) {
        //     $cust_msg = str_replace('{appointment_time}', $current_app_time, $cust_msg);
        // }
        // if (in_array("instructor_name", $matches[1])) {
        //     $cust_msg = str_replace('{instructor_name}', $instructor_name, $cust_msg);
        // }
        // if (in_array("location_name", $matches[1])) {
        //     $cust_msg = str_replace('{location_name}', $location_name, $cust_msg);
        // }

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

        // 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($appointment['customer_id'], 'billing_billing_phone');
        //     if(count($phone)>0){
        //         foreach($sms_matches[0] as $match){
        //         $cust_msg_sms = str_replace($match,'',$cust_msg_sms);
        //         }
        //         //Twilio message
        //         $args = array(
        //             'number_to'=> fetchCountryMobileCode($appointment['customer_id']) . $phone[0],
        //             'message' =>$cust_msg_sms
        //         );
        //         twl_send_sms( $args );
        //     }
        // }
        // }
    }

    echo json_encode(['status' => true, 'message' => 'Two Sessions has been successfully merged into one']);
    die();
}

add_action('wp_ajax_nopriv_send_mailto_customer', 'send_mailto_customer');
add_action('wp_ajax_send_mailto_customer', 'send_mailto_customer');
function send_mailto_customer()
{

    global $wpdb;

    // delete_option('scheduled_date');
    // die();
    if (get_option('scheduled_date') != date('Y-m-d')) {
        error_log(date("l jS \of F Y h:i:s A") . "--Success Send--send_mailto_customer");
    } else {
        error_log(date("l jS \of F Y h:i:s A") . "--Already Sent--send_mailto_customer");
        echo json_encode(['status' => false, 'message' => "Schedule Already Sent"]);
        // die();
    }

    set_scheduled_values('cron');

    update_option('scheduled_date', date('Y-m-d'));

    $customer = $wpdb->get_results("SELECT * FROM " . DB_USERS);

    $customer = get_users(['role__in' => ['customer', 'siab_instructor']]);
    $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 39", ARRAY_A);
    $inst_msg = $email_instructor['body'];
    $inst_subject = $email_instructor['subject'];

    ob_start();
    ?>
        <h4 style="margin-top: 20px;font-size:20px!important;" class="heading-style-secondary"> Available Locations this week </h4>
        <style type="text/css">
            .tool {
                position: relative;
                display: inline-block;
            }

            .tool .tooltiptext {
                visibility: hidden;
                width: 400px;
                background-color: #f8f8f8;
                color: black;
                text-align: center;
                border-radius: 6px;
                padding: 5px 0;

                /* Position the tooltip */
                position: absolute;
                z-index: 1;
                bottom: 100%;
                left: 50%;
                margin-left: -125px;
                font-size: 17px;
                text-transform: none;
            }

            .tool:hover .tooltiptext {
                visibility: visible;
            }

            .btn {
                border: none;
                color: white;
                padding: 4px 8px;
                text-align: center;
                text-decoration: none;
                display: inline-block;
                font-size: 12px;
                transition-duration: 0.4s;
                cursor: pointer;
            }

            .min-width-td {

                min-width: 100px;
            }

            .my-packages-table th {
                line-height: 14px;
                font-size: 11px;
                font-weight: 500;
                padding: 14px 12px;
            }

            .my-packages-table td {
                border: none;
                border-bottom: 4px solid #fff;
                border-top: 5px solid #fff;
                font-weight: 500;
                font-size: 12px;
                line-height: 16px;
                padding: 20px 10px;
            }

            .my-packages-table td:first-child {
                padding-left: 12px;
            }

            .child-details-btns {
                border: 1px solid #eee;
                align-items: center;
                min-height: 65px;
                display: flex;
            }


            .heading-style-secondary {
                font-size: 28px !important;
                color: #000000;
                text-align: left;
                font-weight: 700;
                font-style: normal;
                letter-spacing: 0;
                text-transform: uppercase;
                margin: 0 0 15px 0;
                background: none;
            }

            .booking-cover {
                margin-top: 50px;
            }

            .book-an-appointment {
                background-color: #e8e8e8 !important;
                padding: 30px;
            }

            .book-an-appointment label {
                color: #333;
                opacity: 1;
                font-size: 14px;
                margin: 0 0 5px 0;
                font-family: roboto;
                font-weight: 500;
            }

            .book-an-appointment .select2-container {
                width: 100% !important;
            }


            .book-an-appointment .date_sel,
            .book-an-appointment textarea {
                height: 45px !important;
                border: 1px solid #d7d6d6 !important;
                outline: none !important;
                border-radius: 0 !important;
                box-shadow: none;
                padding: 0 15px !important;
                font-family: Roboto !important;
            }

            .book-an-appointment textarea {
                height: 100px !important;
                padding: 10px 20px !important;
                font-family: Roboto !important;
            }


            .book-an-appointment .select2-container--default .select2-selection--single .select2-selection__rendered {
                line-height: 40px !important;

            }

            .book-an-appointment .select2-container--default .select2-selection--single {
                height: 42px !important;
                font-family: roboto;
            }

            .book-an-appointment .select2-container--default .select2-selection--single .select2-selection__arrow {
                height: 40px !important;
            }

            .form-group {
                position: relative;
            }

            .custom-parsley>.parsley-errors-list {
                position: absolute;
                top: 70px;
                right: 0;
            }

            .parsley-required {
                color: #fd5692;
                font-size: 13px;
                margin-top: 2px;
            }

            .book-an-appointment .outerGroup {
                border-top: 2px solid #d2d2d2;
                padding: 25px 0;
            }


            .book-an-appointment .outerGroup:first-child {
                border-top: 0;
                padding: 0 0 25px 0 !important;
            }

            .close-row {
                width: 100%;
                float: left;
                margin: -10px 0 -15px 0;
            }
        </style>
        <table class="my-packages-tables shop_table shop_table_responsive " style="width: 100%;background: #ff9933;">
            <thead>
                <th class="min-width-td" style=" line-height: 14px;
				    "> Date </th>
                <th> Location </th>

            </thead>

            <tbody>

                <?php
                $timestamp = strtotime('sunday last week');
                $timestamps = strtotime('saturday this week');
                $test = "";
                // if(date('w') == 6 && strtotime(date('H:i')) > strtotime('12:00')){
                if (date('w') == 0 || date('w') == 6) {
                    $monday = strtotime("next monday");

                    // $monday = date('w', $monday)==date('w') ? $monday+7*86400 : $monday;
                } else {
                    $monday = strtotime("last monday");
                    $monday = date('w', $monday) == date('w') ? $monday + 7 * 86400 : $monday;
                }

                $sunday = strtotime(date("Y-m-d", $monday) . "  days");
                $this_week_sd = date("Y-m-d", $monday);
                $this_week_ed = date("Y-m-d", $sunday);

                $dt = new DateTime();
                if (date('w') == 0 || date('w') == 6) {
                    $dt->modify('next monday');
                }

                $dates = [];
                for ($d = 1; $d <= 7; $d++) {
                    $dt->setISODate($dt->format('o'), $dt->format('W'), $d);
                    $dates[$dt->format('D')] = $dt->format('m-d-Y');
                ?>
                    <tr>
                        <td style="background-color: #e8e8e8 !important;
					border: none;
					border-bottom: 4px solid #fff;
					border-top: 5px solid #fff;
					font-weight: 500;
					font-size: 12px;
					line-height: 16px;
					padding: 20px 10px;">
                            <?php echo $dt->format('l, F d Y'); ?>
                        </td>

                        <td style="background-color: #e8e8e8 !important;
					border: none;
					border-bottom: 4px solid #fff;
					border-top: 5px solid #fff;
					font-weight: 500;
					font-size: 12px;
					line-height: 16px;
					padding: 20px 10px;">
                            <?php
                            global $wpdb;

                            $date = $dt->format('Y-m-d');

                            $unixTimestamp = strtotime($date);

                            $dayOfWeek = date("l", $unixTimestamp);
                            $weekday = strtolower($dayOfWeek);
                            $weekdayTxt = strtolower($dayOfWeek);

                            // $locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE is_deleted = 0", ARRAY_A);
                            $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 status = 0 AND is_deleted = 0", ARRAY_A);
                            } else {
                                $locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE status = 0 AND is_deleted = 0", ARRAY_A);
                            }
                            $permittedLocs = array();
                            $flag = 0;

                            if (count($locations) > 0) {
                                echo "<ul style='list-style: disc;'>";
                                foreach ($locations as $loc) {
                                    $working_hours = json_decode($loc['working_hours'], true);
                                    if ($working_hours[$weekday]['open'] && $working_hours[$weekday]['close']) {
                                        echo "<li style='padding-left: 0px;font-size: 13px;'>" . $loc['name'] . " - " . date('g:i A', strtotime($working_hours[$weekday]['open'])) . " to " . date('g:i A', strtotime($working_hours[$weekday]['close'])) . "</li>";
                                        // $test .= " ".$loc['name']." - ".$weekday."-".date('g:i A',strtotime($working_hours[$weekday]['open']))." to ".date('g:i A',strtotime($working_hours[$weekday]['close']))."\n";
                                        // $test .= " ".$weekday."\n".$loc['name']." - ".date('g:i A',strtotime($working_hours[$weekday]['open']))." to ".date('g:i A',strtotime($working_hours[$weekday]['close']))."\n";
                                        $test .= " " . "\n" . ucfirst($weekdayTxt) . "\n" . $loc['name'] . " - " . date('g:i A', strtotime($working_hours[$weekday]['open'])) . " to " . date('g:i A', strtotime($working_hours[$weekday]['close'])) . "\n";
                                        $weekdayTxt = "";
                                        $flag = 1;
                                    }
                                }
                                echo "</ul>";
                            }
                            if ($flag == 0) {
                                echo "No Locations Available";
                            }
                            ?>
                        </td>
                    </tr>
                <?php
                }

                ?>

            </tbody>

        </table>
        <?php
        $table_html = ob_get_clean();
        $phones = [];
        $subscribers = [];
        foreach ($customer as $value) {
            $headers[] = 'Content-Type: text/html; charset=UTF-8';
            $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
            $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 39", ARRAY_A);
            $inst_msg = $email_instructor['body'];
            $inst_subject = $email_instructor['subject'];
            preg_match_all('/{(.*?)}/', $inst_msg, $matches);

            //         $inst_msg_sms = $inst_msgs;
            $inst_msg_sms = $inst_msg;
            $customer_name = $value->display_name;
            if (in_array("customer_name", $matches[1])) {
                //             $inst_msgs = str_replace('{customer_name}', $customer_name, $inst_msg);
                $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
            }

            if (in_array("schedule_table", $matches[1])) {
                // $inst_msgs = str_replace('{schedule_table}', $table_html, $inst_msg);
                $inst_msg = str_replace('{schedule_table}', $table_html, $inst_msg);
                $inst_msg_sms = str_replace('{schedule_table}', $test, $inst_msg_sms);
                // $inst_msg_sms = str_replace('{schedule_table}', '', $test);
                // $inst_msg = str_replace('{schedule_table}', '', $inst_msg_sms);
            }

            $inst_email = $value->user_email;

            try {
                //code...
                wp_mail($inst_email, $inst_subject, $inst_msg, $headers);
            } catch (Exception $th) {
                //throw $th;
            }

            if ($email_instructor['notify_via_sms'] == 1) {
                // $admin_msg_sms = $inst_msg_sms;

                $inst_msg_sms = str_replace('{customer_name}', " ", $inst_msg_sms);
                $inst_msg_sms = str_replace('<br>', "\n", $inst_msg_sms);
                $inst_msg_sms = str_replace('&nbsp', " ", $inst_msg_sms);
                preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
                foreach ($sms_matches[0] as $match) {

                    if ($match == "</p>") {
                        $inst_msg_sms = str_replace($match, "\n", $inst_msg_sms);
                    } else {
                        $inst_msg_sms = str_replace($match, '', $inst_msg_sms);
                    }
                }
                //Twilio message
                // $phone = get_user_meta($value->ID, $key = 'billing_phone');
                $phone = get_user_meta($value->ID, 'billing_phone');

                if (count($phone) > 0) {
                    if (!in_array(trim($phone[0]), $phones)) {
                        $number = fetchCountryMobileCode($value->ID) . $phone[0];
                        $json_data = json_encode(['binding_type' => "sms", 'address' => $number]);
                        array_push($subscribers, $json_data);
                        array_push($phones, trim($phone[0]));
                    }
                }
            }
        }

        // $json_data = json_encode(['binding_type' => "sms", 'address' => "+919809144184"]);
        //                 array_push($subscribers,$json_data);

        $sid = TWILIO_ID;
        $token = TWILIO_AUTH_TOKEN;
        $notify_sid = TWILIO_NOTIFY_SID;
        $client = new Client($sid, $token);
        $twilio_number = TWILIO_NUMBER;

        // $json_data = json_encode(['binding_type' => "sms", 'address' => +918289899343]);
        // array_push($subscribers,$json_data);
        // echo "<pre>";
        // print_r($subscribers);
        $start_time = microtime(true);
        if (count($subscribers) > 0) {
            try {

                $request_data = [
                    "toBinding" => $subscribers,
                    'body' => $inst_msg_sms,
                ];
                // Create a notification
                $notification = $client
                    ->notify->services($notify_sid)
                    ->notifications->create($request_data);
                error_log(date("l jS \of F Y h:i:s A") . "--Success Send--send_mailto_customer");
            } catch (Exception $e) {
                error_log(date("l jS \of F Y h:i:s A") . "--Fail Send--send_mailto_customer");
                // die( $e->getCode() . ' : ' . $e->getMessage() );

            }
        }

        echo json_encode(['status' => true, 'message' => "Sent Successfully"]);
        die();
    }
    add_action('wp_ajax_nopriv_send_mailto_customer_week', 'send_mailto_customer_week');
    add_action('wp_ajax_send_mailto_customer_week', 'send_mailto_customer_week');
    function send_mailto_customer_week()
    {
        global $wpdb;
        $selected_date = $_POST['startdate'];
       $txtDate = $_POST['txtDate'];
        $schedulerTime = $_POST['schedulerTime'];
        //echo json_encode(['status' => false, 'message' => $selected_date]);
    // echo $date;
        if($txtDate !=""){
    
            try {
                $wpdb->query("DELETE FROM " . DB_SCHEDULER . " WHERE `weekstartdate` = '$selected_date'");
                $args = array(
                    'shceduled_date' => $txtDate,
                    'scheduled_time' => strtotime($schedulerTime),
                    'weekstartdate' => $selected_date,
                );
        
                $sqlInsert = $wpdb->insert(DB_SCHEDULER, $args);
                // echo $wpdb->last_query;
                // die();
                echo json_encode(['status' => true, 'message' => "Schedule Created Successfully"]);
                die();
            } catch (Exception $th) {
                echo json_encode(['status' => false, 'message' => "Schedule Already Created for this week"]);
                die();
            }
            
        }
        shootinschoolschedule($selected_date);
        shootinschoolscheduleinstructor($selected_date);
        bwcSchedule($selected_date);
    }

    function shootinschoolschedule($selected_date)
    {


        global $wpdb;
        // $selected_date = $_POST['startdate'];
        // delete_option('scheduled_date');
        // die();
        // if (get_option('scheduled_date') != $date) {
        //     error_log(date("l jS \of F Y h:i:s A") . "--Success Send--send_mailto_customer");
        // } else {
        //     error_log(date("l jS \of F Y h:i:s A") . "--Already Sent--send_mailto_customer");
        //     echo json_encode(['status' => false, 'message' => "Schedule Already Sent"]);
        //     // die();
        // }

        // set_scheduled_values('cron');

        update_option('scheduled_date', $selected_date);

        // $customer = $wpdb->get_results("SELECT * FROM " . DB_USERS);
        $query = "
        SELECT u.*
        FROM {$wpdb->users} u
        INNER JOIN {$wpdb->usermeta} um ON u.ID = um.user_id
        INNER JOIN {$wpdb->usermeta} um2 ON u.ID = um2.user_id
        WHERE um.meta_key = 'isbwc'
        AND um.meta_value = '0'
        AND um2.meta_key = '{$wpdb->prefix}capabilities'
        AND um2.meta_value LIKE '%\"customer\"%'";

        $customer = $wpdb->get_results($query);

        // $customer = get_users(['role__in' => ['customer', 'siab_instructor']]);
        // $customer = get_users(['role__in' => ['customer']]);
        $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 39", ARRAY_A);
        $inst_msg = $email_instructor['body'];
        $inst_subject = $email_instructor['subject'];

        ob_start();
        ?>
        <h4 style="margin-top: 20px;font-size:20px!important;" class="heading-style-secondary"> Available Locations this week </h4>
        <style type="text/css">
            .tool {
                position: relative;
                display: inline-block;
            }

            .tool .tooltiptext {
                visibility: hidden;
                width: 400px;
                background-color: #f8f8f8;
                color: black;
                text-align: center;
                border-radius: 6px;
                padding: 5px 0;

                /* Position the tooltip */
                position: absolute;
                z-index: 1;
                bottom: 100%;
                left: 50%;
                margin-left: -125px;
                font-size: 17px;
                text-transform: none;
            }

            .tool:hover .tooltiptext {
                visibility: visible;
            }

            .btn {
                border: none;
                color: white;
                padding: 4px 8px;
                text-align: center;
                text-decoration: none;
                display: inline-block;
                font-size: 12px;
                transition-duration: 0.4s;
                cursor: pointer;
            }

            .min-width-td {

                min-width: 100px;
            }

            .my-packages-table th {
                line-height: 14px;
                font-size: 11px;
                font-weight: 500;
                padding: 14px 12px;
            }

            .my-packages-table td {
                border: none;
                border-bottom: 4px solid #fff;
                border-top: 5px solid #fff;
                font-weight: 500;
                font-size: 12px;
                line-height: 16px;
                padding: 20px 10px;
            }

            .my-packages-table td:first-child {
                padding-left: 12px;
            }

            .child-details-btns {
                border: 1px solid #eee;
                align-items: center;
                min-height: 65px;
                display: flex;
            }


            .heading-style-secondary {
                font-size: 28px !important;
                color: #000000;
                text-align: left;
                font-weight: 700;
                font-style: normal;
                letter-spacing: 0;
                text-transform: uppercase;
                margin: 0 0 15px 0;
                background: none;
            }

            .booking-cover {
                margin-top: 50px;
            }

            .book-an-appointment {
                background-color: #e8e8e8 !important;
                padding: 30px;
            }

            .book-an-appointment label {
                color: #333;
                opacity: 1;
                font-size: 14px;
                margin: 0 0 5px 0;
                font-family: roboto;
                font-weight: 500;
            }

            .book-an-appointment .select2-container {
                width: 100% !important;
            }


            .book-an-appointment .date_sel,
            .book-an-appointment textarea {
                height: 45px !important;
                border: 1px solid #d7d6d6 !important;
                outline: none !important;
                border-radius: 0 !important;
                box-shadow: none;
                padding: 0 15px !important;
                font-family: Roboto !important;
            }

            .book-an-appointment textarea {
                height: 100px !important;
                padding: 10px 20px !important;
                font-family: Roboto !important;
            }


            .book-an-appointment .select2-container--default .select2-selection--single .select2-selection__rendered {
                line-height: 40px !important;

            }

            .book-an-appointment .select2-container--default .select2-selection--single {
                height: 42px !important;
                font-family: roboto;
            }

            .book-an-appointment .select2-container--default .select2-selection--single .select2-selection__arrow {
                height: 40px !important;
            }

            .form-group {
                position: relative;
            }

            .custom-parsley>.parsley-errors-list {
                position: absolute;
                top: 70px;
                right: 0;
            }

            .parsley-required {
                color: #fd5692;
                font-size: 13px;
                margin-top: 2px;
            }

            .book-an-appointment .outerGroup {
                border-top: 2px solid #d2d2d2;
                padding: 25px 0;
            }


            .book-an-appointment .outerGroup:first-child {
                border-top: 0;
                padding: 0 0 25px 0 !important;
            }

            .close-row {
                width: 100%;
                float: left;
                margin: -10px 0 -15px 0;
            }
        </style>
        <table class="my-packages-tables shop_table shop_table_responsive " style="width: 100%;background: #ff9933;">
            <thead>
                <th class="min-width-td" style=" line-height: 14px;
				    "> Date </th>
                <th> Location </th>

            </thead>

            <tbody>

                <?php
                $timestamp = strtotime('sunday last week');
                $timestamps = strtotime('saturday this week');
                $test = "";
                // if(date('w') == 6 && strtotime(date('H:i')) > strtotime('12:00')){
                if (date('w') == 0 || date('w') == 6) {
                    // $monday = strtotime("next monday");
                    $monday = strtotime("next Monday", strtotime($selected_date));

                    // $monday = date('w', $monday)==date('w') ? $monday+7*86400 : $monday;
                } else {
                    // $monday = strtotime("last monday");
                    $monday = strtotime("last Monday", strtotime($selected_date));
                    $monday = date('w', $monday) == date('w') ? $monday + 7 * 86400 : $monday;
                }

                $sunday = strtotime(date("Y-m-d", $monday) . "  days");
                $this_week_sd = date("Y-m-d", $monday);
                $this_week_ed = date("Y-m-d", $sunday);

                $dt = new DateTime($selected_date);
                if (date('w') == 0 || date('w') == 6) {
                    $dt->modify('next monday');
                }

                $dates = [];
                for ($d = 1; $d <= 7; $d++) {
                    $dt->setISODate($dt->format('o'), $dt->format('W'), $d);
                    $dates[$dt->format('D')] = $dt->format('m-d-Y');
                ?>
                    <tr>
                        <td style="background-color: #e8e8e8 !important;
					border: none;
					border-bottom: 4px solid #fff;
					border-top: 5px solid #fff;
					font-weight: 500;
					font-size: 12px;
					line-height: 16px;
					padding: 20px 10px;">
                            <?php echo $dt->format('l, F d Y'); ?>
                        </td>

                        <td style="background-color: #e8e8e8 !important;
					border: none;
					border-bottom: 4px solid #fff;
					border-top: 5px solid #fff;
					font-weight: 500;
					font-size: 12px;
					line-height: 16px;
					padding: 20px 10px;">
                            <?php
                            global $wpdb;

                            $date = $dt->format('Y-m-d');

                            $unixTimestamp = strtotime($date);

                            $dayOfWeek = date("l", $unixTimestamp);
                            $weekday = strtolower($dayOfWeek);
                            $weekdayTxt = strtolower($dayOfWeek);



                            // $locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE is_deleted = 0", ARRAY_A);
                            // $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 status = 0 AND is_deleted = 0", ARRAY_A);
                            //     $locations = $wpdb->get_results("SELECT cl.id, cl.name, cl.address, cl.phone, cl.description, cl.status, cl.package, wh.working_hours FROM " . DB_COACHING_LOCATIONS . " cl JOIN " . DB_WORKING_HOURS . " wh ON cl.id = wh.location_id WHERE cl.status = 0 AND cl.is_deleted = 0 AND wh.start_date = '$selected_date'", ARRAY_A);
                            //     echo $wpdb->last_query;
                            //     die();
                            // } else {
                                $locations = $wpdb->get_results("SELECT cl.id, cl.name, cl.address, cl.phone, cl.description, cl.status, cl.package, cl.customlabelShoot, wh.working_hours FROM " . DB_COACHING_LOCATIONS . " cl JOIN " . DB_WORKING_HOURS . " wh ON cl.id = wh.location_id WHERE cl.status = 0 AND cl.is_deleted = 0 AND (cl.platform = 1 OR cl.platform = 3) AND wh.start_date =  '$selected_date'", ARRAY_A);
                               
                                // $locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE status = 0 AND is_deleted = 0", ARRAY_A);
                            // }
                            
                            $permittedLocs = array();
                            $flag = 0;
                            // echo "<pre>";
                            // print_r($locations);
                            // echo $wpdb->last_query;
                            // echo "Location count=====".count($locations);

                            if (count($locations) > 0) {
                                echo "<ul style='list-style: disc;'>";
                                foreach ($locations as $loc) {
                                    $working_hours = json_decode($loc['working_hours'], true);
                                    if ($working_hours[$weekday]['open'] && $working_hours[$weekday]['close']) {
                                        echo "<li style='padding-left: 0px;font-size: 13px;'>" . $loc['name'] . "(" . $loc['customlabelShoot'] . ") - " . date('g:i A', strtotime($working_hours[$weekday]['open'])) . " to " . date('g:i A', strtotime($working_hours[$weekday]['close'])) . "</li>";
                                        // $test .= " ".$loc['name']." - ".$weekday."-".date('g:i A',strtotime($working_hours[$weekday]['open']))." to ".date('g:i A',strtotime($working_hours[$weekday]['close']))."\n";
                                        // $test .= " ".$weekday."\n".$loc['name']." - ".date('g:i A',strtotime($working_hours[$weekday]['open']))." to ".date('g:i A',strtotime($working_hours[$weekday]['close']))."\n";
                                        $test .= " " . "\n" . ucfirst($weekdayTxt) . "\n" . $loc['name'] . "(" . $loc['customlabelShoot'] . ") - " . date('g:i A', strtotime($working_hours[$weekday]['open'])) . " to " . date('g:i A', strtotime($working_hours[$weekday]['close'])) . "\n";
                                        $weekdayTxt = "";
                                        $flag = 1;
                                    }
                                }
                                echo "</ul>";
                            }
                            if ($flag == 0) {
                                // die();
                                echo "No Locations Available";
                            }
                            ?>
                        </td>
                    </tr>
                <?php
                }

                ?>

            </tbody>

        </table>
        <?php

        $table_html = ob_get_clean();
        $phones = [];
        $subscribers = [];
        foreach ($customer as $value) {
            $headers[] = 'Content-Type: text/html; charset=UTF-8';
            $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
            $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 39", ARRAY_A);
            $inst_msg = $email_instructor['body'];
            $inst_subject = $email_instructor['subject'];
            preg_match_all('/{(.*?)}/', $inst_msg, $matches);

            //         $inst_msg_sms = $inst_msgs;
            $inst_msg_sms = $inst_msg;
            $customer_name = $value->display_name;
            if (in_array("customer_name", $matches[1])) {
                //             $inst_msgs = str_replace('{customer_name}', $customer_name, $inst_msg);
                $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
            }

            if (in_array("schedule_table", $matches[1])) {
                // $inst_msgs = str_replace('{schedule_table}', $table_html, $inst_msg);
                $inst_msg = str_replace('{schedule_table}', $table_html, $inst_msg);
                $inst_msg_sms = str_replace('{schedule_table}', $test, $inst_msg_sms);
                // $inst_msg_sms = str_replace('{schedule_table}', '', $test);
                // $inst_msg = str_replace('{schedule_table}', '', $inst_msg_sms);
            }

            $inst_email = $value->user_email;

            try {
                //code...
                wp_mail($inst_email, $inst_subject, $inst_msg, $headers);
                // die();
            } catch (Exception $th) {
                //throw $th;
            }

            if ($email_instructor['notify_via_sms'] == 1) {
                // $admin_msg_sms = $inst_msg_sms;

                $inst_msg_sms = str_replace('{customer_name}', " ", $inst_msg_sms);
                $inst_msg_sms = str_replace('<br>', "\n", $inst_msg_sms);
                $inst_msg_sms = str_replace('&nbsp', " ", $inst_msg_sms);
                preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
                foreach ($sms_matches[0] as $match) {

                    if ($match == "</p>") {
                        $inst_msg_sms = str_replace($match, "\n", $inst_msg_sms);
                    } else {
                        $inst_msg_sms = str_replace($match, '', $inst_msg_sms);
                    }
                }
                //Twilio message
                // $phone = get_user_meta($value->ID, $key = 'billing_phone');
                $phone = get_user_meta($value->ID, 'billing_phone');

                if (count($phone) > 0) {
                    if (!in_array(trim($phone[0]), $phones)) {
                        $number = fetchCountryMobileCode($value->ID) . $phone[0];
                        $json_data = json_encode(['binding_type' => "sms", 'address' => $number]);
                        array_push($subscribers, $json_data);
                        array_push($phones, trim($phone[0]));
                    }
                }
            }
        }

        // $json_data = json_encode(['binding_type' => "sms", 'address' => "+919809144184"]);
        //                 array_push($subscribers,$json_data);

        $sid = TWILIO_ID;
        $token = TWILIO_AUTH_TOKEN;
        $notify_sid = TWILIO_NOTIFY_SID;
        $client = new Client($sid, $token);
        $twilio_number = TWILIO_NUMBER;

        // $json_data = json_encode(['binding_type' => "sms", 'address' => +918289899343]);
        // array_push($subscribers,$json_data);
        // echo "<pre>";
        // print_r($subscribers);
        $start_time = microtime(true);
        if (count($subscribers) > 0) {
            try {

                $request_data = [
                    "toBinding" => $subscribers,
                    'body' => $inst_msg_sms,
                ];
                // Create a notification
                $notification = $client
                    ->notify->services($notify_sid)
                    ->notifications->create($request_data);
                error_log(date("l jS \of F Y h:i:s A") . "--Success Send--send_mailto_customer");
            } catch (Exception $e) {
                error_log(date("l jS \of F Y h:i:s A") . "--Fail Send--send_mailto_customer");
                // die( $e->getCode() . ' : ' . $e->getMessage() );

            }
        }

        echo json_encode(['status' => true, 'message' => "Sent Successfully"]);
      
    }

    function shootinschoolscheduleinstructor($selected_date)
    {


        global $wpdb;
        // $selected_date = $_POST['startdate'];
        // delete_option('scheduled_date');
        // die();
        // if (get_option('scheduled_date') != $date) {
        //     error_log(date("l jS \of F Y h:i:s A") . "--Success Send--send_mailto_customer");
        // } else {
        //     error_log(date("l jS \of F Y h:i:s A") . "--Already Sent--send_mailto_customer");
        //     echo json_encode(['status' => false, 'message' => "Schedule Already Sent"]);
        //     // die();
        // }

        // set_scheduled_values('cron');

        update_option('scheduled_date', $selected_date);

        $customer = $wpdb->get_results("SELECT * FROM " . DB_USERS);
        // $query = "
        // SELECT u.* 
        // FROM {$wpdb->users} u
        // INNER JOIN {$wpdb->usermeta} um ON u.ID = um.user_id
        // WHERE um.meta_key = 'isbwc'
        // AND um.meta_value = '0'";

        // $customer = $wpdb->get_results($query);

        $customer = get_users(['role__in' => ['siab_instructor']]);
        // $customer = get_users(['role__in' => ['customer']]);
        $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 39", ARRAY_A);
        $inst_msg = $email_instructor['body'];
        $inst_subject = $email_instructor['subject'];

        ob_start();
        ?>
        <h4 style="margin-top: 20px;font-size:20px!important;" class="heading-style-secondary"> Available Locations this week </h4>
        <style type="text/css">
            .tool {
                position: relative;
                display: inline-block;
            }

            .tool .tooltiptext {
                visibility: hidden;
                width: 400px;
                background-color: #f8f8f8;
                color: black;
                text-align: center;
                border-radius: 6px;
                padding: 5px 0;

                /* Position the tooltip */
                position: absolute;
                z-index: 1;
                bottom: 100%;
                left: 50%;
                margin-left: -125px;
                font-size: 17px;
                text-transform: none;
            }

            .tool:hover .tooltiptext {
                visibility: visible;
            }

            .btn {
                border: none;
                color: white;
                padding: 4px 8px;
                text-align: center;
                text-decoration: none;
                display: inline-block;
                font-size: 12px;
                transition-duration: 0.4s;
                cursor: pointer;
            }

            .min-width-td {

                min-width: 100px;
            }

            .my-packages-table th {
                line-height: 14px;
                font-size: 11px;
                font-weight: 500;
                padding: 14px 12px;
            }

            .my-packages-table td {
                border: none;
                border-bottom: 4px solid #fff;
                border-top: 5px solid #fff;
                font-weight: 500;
                font-size: 12px;
                line-height: 16px;
                padding: 20px 10px;
            }

            .my-packages-table td:first-child {
                padding-left: 12px;
            }

            .child-details-btns {
                border: 1px solid #eee;
                align-items: center;
                min-height: 65px;
                display: flex;
            }


            .heading-style-secondary {
                font-size: 28px !important;
                color: #000000;
                text-align: left;
                font-weight: 700;
                font-style: normal;
                letter-spacing: 0;
                text-transform: uppercase;
                margin: 0 0 15px 0;
                background: none;
            }

            .booking-cover {
                margin-top: 50px;
            }

            .book-an-appointment {
                background-color: #e8e8e8 !important;
                padding: 30px;
            }

            .book-an-appointment label {
                color: #333;
                opacity: 1;
                font-size: 14px;
                margin: 0 0 5px 0;
                font-family: roboto;
                font-weight: 500;
            }

            .book-an-appointment .select2-container {
                width: 100% !important;
            }


            .book-an-appointment .date_sel,
            .book-an-appointment textarea {
                height: 45px !important;
                border: 1px solid #d7d6d6 !important;
                outline: none !important;
                border-radius: 0 !important;
                box-shadow: none;
                padding: 0 15px !important;
                font-family: Roboto !important;
            }

            .book-an-appointment textarea {
                height: 100px !important;
                padding: 10px 20px !important;
                font-family: Roboto !important;
            }


            .book-an-appointment .select2-container--default .select2-selection--single .select2-selection__rendered {
                line-height: 40px !important;

            }

            .book-an-appointment .select2-container--default .select2-selection--single {
                height: 42px !important;
                font-family: roboto;
            }

            .book-an-appointment .select2-container--default .select2-selection--single .select2-selection__arrow {
                height: 40px !important;
            }

            .form-group {
                position: relative;
            }

            .custom-parsley>.parsley-errors-list {
                position: absolute;
                top: 70px;
                right: 0;
            }

            .parsley-required {
                color: #fd5692;
                font-size: 13px;
                margin-top: 2px;
            }

            .book-an-appointment .outerGroup {
                border-top: 2px solid #d2d2d2;
                padding: 25px 0;
            }


            .book-an-appointment .outerGroup:first-child {
                border-top: 0;
                padding: 0 0 25px 0 !important;
            }

            .close-row {
                width: 100%;
                float: left;
                margin: -10px 0 -15px 0;
            }
        </style>
        <table class="my-packages-tables shop_table shop_table_responsive " style="width: 100%;background: #ff9933;">
            <thead>
                <th class="min-width-td" style=" line-height: 14px;
				    "> Date </th>
                <th> Location </th>

            </thead>

            <tbody>

                <?php
                $timestamp = strtotime('sunday last week');
                $timestamps = strtotime('saturday this week');
                $test = "";
                // if(date('w') == 6 && strtotime(date('H:i')) > strtotime('12:00')){
                if (date('w') == 0 || date('w') == 6) {
                    // $monday = strtotime("next monday");
                    $monday = strtotime("next Monday", strtotime($selected_date));

                    // $monday = date('w', $monday)==date('w') ? $monday+7*86400 : $monday;
                } else {
                    // $monday = strtotime("last monday");
                    $monday = strtotime("last Monday", strtotime($selected_date));
                    $monday = date('w', $monday) == date('w') ? $monday + 7 * 86400 : $monday;
                }

                $sunday = strtotime(date("Y-m-d", $monday) . "  days");
                $this_week_sd = date("Y-m-d", $monday);
                $this_week_ed = date("Y-m-d", $sunday);

                $dt = new DateTime($selected_date);
                if (date('w') == 0 || date('w') == 6) {
                    $dt->modify('next monday');
                }

                $dates = [];
                for ($d = 1; $d <= 7; $d++) {
                    $dt->setISODate($dt->format('o'), $dt->format('W'), $d);
                    $dates[$dt->format('D')] = $dt->format('m-d-Y');
                ?>
                    <tr>
                        <td style="background-color: #e8e8e8 !important;
					border: none;
					border-bottom: 4px solid #fff;
					border-top: 5px solid #fff;
					font-weight: 500;
					font-size: 12px;
					line-height: 16px;
					padding: 20px 10px;">
                            <?php echo $dt->format('l, F d Y'); ?>
                        </td>

                        <td style="background-color: #e8e8e8 !important;
					border: none;
					border-bottom: 4px solid #fff;
					border-top: 5px solid #fff;
					font-weight: 500;
					font-size: 12px;
					line-height: 16px;
					padding: 20px 10px;">
                            <?php
                            global $wpdb;

                            $date = $dt->format('Y-m-d');

                            $unixTimestamp = strtotime($date);

                            $dayOfWeek = date("l", $unixTimestamp);
                            $weekday = strtolower($dayOfWeek);
                            $weekdayTxt = strtolower($dayOfWeek);



                            // $locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE is_deleted = 0", ARRAY_A);
                            // $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 status = 0 AND is_deleted = 0", ARRAY_A);
                            //     $locations = $wpdb->get_results("SELECT cl.id, cl.name, cl.address, cl.phone, cl.description, cl.status, cl.package, wh.working_hours FROM " . DB_COACHING_LOCATIONS . " cl JOIN " . DB_WORKING_HOURS . " wh ON cl.id = wh.location_id WHERE cl.status = 0 AND cl.is_deleted = 0 AND wh.start_date = '$selected_date'", ARRAY_A);
                            //     echo $wpdb->last_query;
                            //     die();
                            // } else {
                                $locations = $wpdb->get_results("SELECT cl.id, cl.name, cl.address, cl.phone, cl.description, cl.status, cl.package, wh.working_hours FROM " . DB_COACHING_LOCATIONS . " cl JOIN " . DB_WORKING_HOURS . " wh ON cl.id = wh.location_id WHERE cl.status = 0 AND cl.is_deleted = 0 AND wh.start_date = '$selected_date'", ARRAY_A); 
                                // $locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE status = 0 AND is_deleted = 0", ARRAY_A);
                            // }
                            
                            $permittedLocs = array();
                            $flag = 0;
                            // echo "<pre>";
                            // print_r($locations);
                            // echo $wpdb->last_query;
                            // echo "Location count=====".count($locations);

                            if (count($locations) > 0) {
                                echo "<ul style='list-style: disc;'>";
                                foreach ($locations as $loc) {
                                    $working_hours = json_decode($loc['working_hours'], true);
                                    if ($working_hours[$weekday]['open'] && $working_hours[$weekday]['close']) {
                                        echo "<li style='padding-left: 0px;font-size: 13px;'>" . $loc['name']. " - " . date('g:i A', strtotime($working_hours[$weekday]['open'])) . " to " . date('g:i A', strtotime($working_hours[$weekday]['close'])) . "</li>";
                                        // $test .= " ".$loc['name']." - ".$weekday."-".date('g:i A',strtotime($working_hours[$weekday]['open']))." to ".date('g:i A',strtotime($working_hours[$weekday]['close']))."\n";
                                        // $test .= " ".$weekday."\n".$loc['name']." - ".date('g:i A',strtotime($working_hours[$weekday]['open']))." to ".date('g:i A',strtotime($working_hours[$weekday]['close']))."\n";
                                        $test .= " " . "\n" . ucfirst($weekdayTxt) . "\n" . $loc['name'] . " - " . date('g:i A', strtotime($working_hours[$weekday]['open'])) . " to " . date('g:i A', strtotime($working_hours[$weekday]['close'])) . "\n";
                                        $weekdayTxt = "";
                                        $flag = 1;
                                    }
                                }
                                echo "</ul>";
                            }
                            if ($flag == 0) {
                                // die();
                                echo "No Locations Available";
                            }
                            ?>
                        </td>
                    </tr>
                <?php
                }

                ?>

            </tbody>

        </table>
        <?php

        $table_html = ob_get_clean();
        $phones = [];
        $subscribers = [];
        foreach ($customer as $value) {
            $headers[] = 'Content-Type: text/html; charset=UTF-8';
            $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
            $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 39", ARRAY_A);
            $inst_msg = $email_instructor['body'];
            $inst_subject = $email_instructor['subject'];
            preg_match_all('/{(.*?)}/', $inst_msg, $matches);

            //         $inst_msg_sms = $inst_msgs;
            $inst_msg_sms = $inst_msg;
            $customer_name = $value->display_name;
            if (in_array("customer_name", $matches[1])) {
                //             $inst_msgs = str_replace('{customer_name}', $customer_name, $inst_msg);
                $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
            }

            if (in_array("schedule_table", $matches[1])) {
                // $inst_msgs = str_replace('{schedule_table}', $table_html, $inst_msg);
                $inst_msg = str_replace('{schedule_table}', $table_html, $inst_msg);
                $inst_msg_sms = str_replace('{schedule_table}', $test, $inst_msg_sms);
                // $inst_msg_sms = str_replace('{schedule_table}', '', $test);
                // $inst_msg = str_replace('{schedule_table}', '', $inst_msg_sms);
            }

            $inst_email = $value->user_email;

            try {
                //code...
                wp_mail($inst_email, $inst_subject, $inst_msg, $headers);
                // die();
            } catch (Exception $th) {
                //throw $th;
            }

            if ($email_instructor['notify_via_sms'] == 1) {
                // $admin_msg_sms = $inst_msg_sms;

                $inst_msg_sms = str_replace('{customer_name}', " ", $inst_msg_sms);
                $inst_msg_sms = str_replace('<br>', "\n", $inst_msg_sms);
                $inst_msg_sms = str_replace('&nbsp', " ", $inst_msg_sms);
                preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
                foreach ($sms_matches[0] as $match) {

                    if ($match == "</p>") {
                        $inst_msg_sms = str_replace($match, "\n", $inst_msg_sms);
                    } else {
                        $inst_msg_sms = str_replace($match, '', $inst_msg_sms);
                    }
                }
                //Twilio message
                // $phone = get_user_meta($value->ID, $key = 'billing_phone');
                $phone = get_user_meta($value->ID, 'billing_phone');

                if (count($phone) > 0) {
                    if (!in_array(trim($phone[0]), $phones)) {
                        $number = fetchCountryMobileCode($value->ID) . $phone[0];
                        $json_data = json_encode(['binding_type' => "sms", 'address' => $number]);
                        array_push($subscribers, $json_data);
                        array_push($phones, trim($phone[0]));
                    }
                }
            }
        }

        // $json_data = json_encode(['binding_type' => "sms", 'address' => "+919809144184"]);
        //                 array_push($subscribers,$json_data);

        $sid = TWILIO_ID;
        $token = TWILIO_AUTH_TOKEN;
        $notify_sid = TWILIO_NOTIFY_SID;
        $client = new Client($sid, $token);
        $twilio_number = TWILIO_NUMBER;

        // $json_data = json_encode(['binding_type' => "sms", 'address' => +918289899343]);
        // array_push($subscribers,$json_data);
        // echo "<pre>";
        // print_r($subscribers);
        $start_time = microtime(true);
        if (count($subscribers) > 0) {
            try {

                $request_data = [
                    "toBinding" => $subscribers,
                    'body' => $inst_msg_sms,
                ];
                // Create a notification
                $notification = $client
                    ->notify->services($notify_sid)
                    ->notifications->create($request_data);
                error_log(date("l jS \of F Y h:i:s A") . "--Success Send--send_mailto_customer");
            } catch (Exception $e) {
                error_log(date("l jS \of F Y h:i:s A") . "--Fail Send--send_mailto_customer");
                // die( $e->getCode() . ' : ' . $e->getMessage() );

            }
        }

        echo json_encode(['status' => true, 'message' => "Sent Successfully"]);
       
    }

    function bwcSchedule($selected_date)
    {



        global $wpdb;
        // $selected_date = $_POST['startdate'];
        // delete_option('scheduled_date');
        // die();
        // if (get_option('scheduled_date') != $date) {
        //     error_log(date("l jS \of F Y h:i:s A") . "--Success Send--send_mailto_customer");
        // } else {
        //     error_log(date("l jS \of F Y h:i:s A") . "--Already Sent--send_mailto_customer");
        //     echo json_encode(['status' => false, 'message' => "Schedule Already Sent"]);
        //     // die();
        // }

        // set_scheduled_values('cron');

        update_option('scheduled_date', $selected_date);


        $query = "
       SELECT u.*
    FROM {$wpdb->users} u
    INNER JOIN {$wpdb->usermeta} um ON u.ID = um.user_id
    INNER JOIN {$wpdb->usermeta} um2 ON u.ID = um2.user_id
    WHERE um.meta_key = 'isbwc'
    AND um.meta_value = '1'
    AND um2.meta_key = '{$wpdb->prefix}capabilities'
    AND um2.meta_value LIKE '%\"customer\"%'";

        $customer = $wpdb->get_results($query);

        // $customer = get_users(['role__in' => ['customer', 'siab_instructor']]);
        // $customer = get_users(['role__in' => ['customer']]);

        // $customer = $wpdb->get_results("SELECT * FROM " . DB_USERS);

        // $customer = get_users(['role__in' => ['customer', 'siab_instructor']]);
        $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 39", ARRAY_A);
        $inst_msg = $email_instructor['body'];
        $inst_subject = $email_instructor['subject'];

        ob_start();
        ?>
        <h4 style="margin-top: 20px;font-size:20px!important;" class="heading-style-secondary"> Available Locations this week </h4>
        <style type="text/css">
            .tool {
                position: relative;
                display: inline-block;
            }

            .tool .tooltiptext {
                visibility: hidden;
                width: 400px;
                background-color: #f8f8f8;
                color: black;
                text-align: center;
                border-radius: 6px;
                padding: 5px 0;

                /* Position the tooltip */
                position: absolute;
                z-index: 1;
                bottom: 100%;
                left: 50%;
                margin-left: -125px;
                font-size: 17px;
                text-transform: none;
            }

            .tool:hover .tooltiptext {
                visibility: visible;
            }

            .btn {
                border: none;
                color: white;
                padding: 4px 8px;
                text-align: center;
                text-decoration: none;
                display: inline-block;
                font-size: 12px;
                transition-duration: 0.4s;
                cursor: pointer;
            }

            .min-width-td {

                min-width: 100px;
            }

            .my-packages-table th {
                line-height: 14px;
                font-size: 11px;
                font-weight: 500;
                padding: 14px 12px;
            }

            .my-packages-table td {
                border: none;
                border-bottom: 4px solid #fff;
                border-top: 5px solid #fff;
                font-weight: 500;
                font-size: 12px;
                line-height: 16px;
                padding: 20px 10px;
            }

            .my-packages-table td:first-child {
                padding-left: 12px;
            }

            .child-details-btns {
                border: 1px solid #eee;
                align-items: center;
                min-height: 65px;
                display: flex;
            }


            .heading-style-secondary {
                font-size: 28px !important;
                color: #000000;
                text-align: left;
                font-weight: 700;
                font-style: normal;
                letter-spacing: 0;
                text-transform: uppercase;
                margin: 0 0 15px 0;
                background: none;
            }

            .booking-cover {
                margin-top: 50px;
            }

            .book-an-appointment {
                background-color: #e8e8e8 !important;
                padding: 30px;
            }

            .book-an-appointment label {
                color: #333;
                opacity: 1;
                font-size: 14px;
                margin: 0 0 5px 0;
                font-family: roboto;
                font-weight: 500;
            }

            .book-an-appointment .select2-container {
                width: 100% !important;
            }


            .book-an-appointment .date_sel,
            .book-an-appointment textarea {
                height: 45px !important;
                border: 1px solid #d7d6d6 !important;
                outline: none !important;
                border-radius: 0 !important;
                box-shadow: none;
                padding: 0 15px !important;
                font-family: Roboto !important;
            }

            .book-an-appointment textarea {
                height: 100px !important;
                padding: 10px 20px !important;
                font-family: Roboto !important;
            }


            .book-an-appointment .select2-container--default .select2-selection--single .select2-selection__rendered {
                line-height: 40px !important;

            }

            .book-an-appointment .select2-container--default .select2-selection--single {
                height: 42px !important;
                font-family: roboto;
            }

            .book-an-appointment .select2-container--default .select2-selection--single .select2-selection__arrow {
                height: 40px !important;
            }

            .form-group {
                position: relative;
            }

            .custom-parsley>.parsley-errors-list {
                position: absolute;
                top: 70px;
                right: 0;
            }

            .parsley-required {
                color: #fd5692;
                font-size: 13px;
                margin-top: 2px;
            }

            .book-an-appointment .outerGroup {
                border-top: 2px solid #d2d2d2;
                padding: 25px 0;
            }


            .book-an-appointment .outerGroup:first-child {
                border-top: 0;
                padding: 0 0 25px 0 !important;
            }

            .close-row {
                width: 100%;
                float: left;
                margin: -10px 0 -15px 0;
            }
        </style>
        <table class="my-packages-tables shop_table shop_table_responsive " style="width: 100%;background: #ff9933;">
            <thead>
                <th class="min-width-td" style=" line-height: 14px;
				    "> Date </th>
                <th> Location </th>

            </thead>

            <tbody>

                <?php
                $timestamp = strtotime('sunday last week');
                $timestamps = strtotime('saturday this week');
                $test = "";
                // if(date('w') == 6 && strtotime(date('H:i')) > strtotime('12:00')){
                if (date('w') == 0 || date('w') == 6) {
                    // $monday = strtotime("next monday");
                    $monday = strtotime("next Monday", strtotime($selected_date));

                    // $monday = date('w', $monday)==date('w') ? $monday+7*86400 : $monday;
                } else {
                    // $monday = strtotime("last monday");
                    $monday = strtotime("last Monday", strtotime($selected_date));
                    $monday = date('w', $monday) == date('w') ? $monday + 7 * 86400 : $monday;
                }

                $sunday = strtotime(date("Y-m-d", $monday) . "  days");
                $this_week_sd = date("Y-m-d", $monday);
                $this_week_ed = date("Y-m-d", $sunday);

                $dt = new DateTime($selected_date);
                if (date('w') == 0 || date('w') == 6) {
                    $dt->modify('next monday');
                }

                $dates = [];
                for ($d = 1; $d <= 7; $d++) {
                    $dt->setISODate($dt->format('o'), $dt->format('W'), $d);
                    $dates[$dt->format('D')] = $dt->format('m-d-Y');
                ?>
                    <tr>
                        <td style="background-color: #e8e8e8 !important;
					border: none;
					border-bottom: 4px solid #fff;
					border-top: 5px solid #fff;
					font-weight: 500;
					font-size: 12px;
					line-height: 16px;
					padding: 20px 10px;">
                            <?php echo $dt->format('l, F d Y'); ?>
                        </td>

                        <td style="background-color: #e8e8e8 !important;
					border: none;
					border-bottom: 4px solid #fff;
					border-top: 5px solid #fff;
					font-weight: 500;
					font-size: 12px;
					line-height: 16px;
					padding: 20px 10px;">
                            <?php
                            global $wpdb;

                            $date = $dt->format('Y-m-d');

                            $unixTimestamp = strtotime($date);

                            $dayOfWeek = date("l", $unixTimestamp);
                            $weekday = strtolower($dayOfWeek);
                            $weekdayTxt = strtolower($dayOfWeek);



                            // $locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE is_deleted = 0", ARRAY_A);
                            // $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 status = 0 AND is_deleted = 0", ARRAY_A);
                            //     // $locations = $wpdb->get_results("SELECT cl.id, cl.name, cl.address, cl.phone, cl.description, cl.status, cl.package, wh.working_hours FROM " . DB_COACHING_LOCATIONS . " cl JOIN " . DB_WORKING_HOURS . " wh ON cl.id = wh.location_id WHERE cl.status = 0 AND cl.is_deleted = 0  AND wh.start_date = '$selected_date'", ARRAY_A);
                            // } else {
                                $locations = $wpdb->get_results("SELECT cl.id, cl.name, cl.address, cl.phone, cl.description, cl.status, cl.package,cl.customlabelBwc, wh.working_hours FROM " . DB_COACHING_LOCATIONS . " cl JOIN " . DB_WORKING_HOURS . " wh ON cl.id = wh.location_id WHERE cl.status = 0 AND cl.is_deleted = 0 AND (cl.platform = 2 OR cl.platform = 3) AND wh.start_date =  '$selected_date'", ARRAY_A);

                                // $locations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE status = 0 AND is_deleted = 0", ARRAY_A);
                            // }

                            $permittedLocs = array();
                            $flag = 0;
                            // echo "<pre>";
                            // print_r($locations);
                            // echo $wpdb->last_query;
                            // echo "Location count=====".count($locations);

                            if (count($locations) > 0) {
                                echo "<ul style='list-style: disc;'>";
                                foreach ($locations as $loc) {
                                    $working_hours = json_decode($loc['working_hours'], true);
                                    if ($working_hours[$weekday]['open'] && $working_hours[$weekday]['close']) {
                                        echo "<li style='padding-left: 0px;font-size: 13px;'>" . $loc['name'] . "(" . $loc['customlabelBwc'] . ") - " . date('g:i A', strtotime($working_hours[$weekday]['open'])) . " to " . date('g:i A', strtotime($working_hours[$weekday]['close'])) . "</li>";
                                        // $test .= " ".$loc['name']." - ".$weekday."-".date('g:i A',strtotime($working_hours[$weekday]['open']))." to ".date('g:i A',strtotime($working_hours[$weekday]['close']))."\n";
                                        // $test .= " ".$weekday."\n".$loc['name']." - ".date('g:i A',strtotime($working_hours[$weekday]['open']))." to ".date('g:i A',strtotime($working_hours[$weekday]['close']))."\n";
                                        $test .= " " . "\n" . ucfirst($weekdayTxt) . "\n" . $loc['name'] . "(" . $loc['customlabelBwc'] . ") - " . date('g:i A', strtotime($working_hours[$weekday]['open'])) . " to " . date('g:i A', strtotime($working_hours[$weekday]['close'])) . "\n";
                                        $weekdayTxt = "";
                                        $flag = 1;
                                    }
                                }
                                echo "</ul>";
                            }
                            if ($flag == 0) {
                                // die();
                                echo "No Locations Available";
                            }
                            ?>
                        </td>
                    </tr>
                <?php
                }

                ?>

            </tbody>

        </table>
        <?php

        $table_html = ob_get_clean();
        $phones = [];
        $subscribers = [];
        foreach ($customer as $value) {
            $headers[] = 'Content-Type: text/html; charset=UTF-8';
            $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
            $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 39", ARRAY_A);
            $inst_msg = $email_instructor['body'];
            $inst_subject = $email_instructor['subject'];
            preg_match_all('/{(.*?)}/', $inst_msg, $matches);

            //         $inst_msg_sms = $inst_msgs;
            $inst_msg_sms = $inst_msg;
            $customer_name = $value->display_name;
            if (in_array("customer_name", $matches[1])) {
                //             $inst_msgs = str_replace('{customer_name}', $customer_name, $inst_msg);
                $inst_msg = str_replace('{customer_name}', $customer_name, $inst_msg);
            }

            if (in_array("schedule_table", $matches[1])) {
                // $inst_msgs = str_replace('{schedule_table}', $table_html, $inst_msg);
                $inst_msg = str_replace('{schedule_table}', $table_html, $inst_msg);
                $inst_msg_sms = str_replace('{schedule_table}', $test, $inst_msg_sms);
                // $inst_msg_sms = str_replace('{schedule_table}', '', $test);
                // $inst_msg = str_replace('{schedule_table}', '', $inst_msg_sms);
            }

            $inst_email = $value->user_email;

            try {
                //code...
                wp_mail($inst_email, $inst_subject, $inst_msg, $headers);
                // die();
            } catch (Exception $th) {
                //throw $th;
            }

            if ($email_instructor['notify_via_sms'] == 1) {
                // $admin_msg_sms = $inst_msg_sms;

                $inst_msg_sms = str_replace('{customer_name}', " ", $inst_msg_sms);
                $inst_msg_sms = str_replace('<br>', "\n", $inst_msg_sms);
                $inst_msg_sms = str_replace('&nbsp', " ", $inst_msg_sms);
                preg_match_all('/<(.*?)>/', $inst_msg_sms, $sms_matches);
                foreach ($sms_matches[0] as $match) {

                    if ($match == "</p>") {
                        $inst_msg_sms = str_replace($match, "\n", $inst_msg_sms);
                    } else {
                        $inst_msg_sms = str_replace($match, '', $inst_msg_sms);
                    }
                }
                //Twilio message
                // $phone = get_user_meta($value->ID, $key = 'billing_phone');
                $phone = get_user_meta($value->ID, 'billing_phone');

                if (count($phone) > 0) {
                    if (!in_array(trim($phone[0]), $phones)) {
                        $number = fetchCountryMobileCode($value->ID) . $phone[0];
                        $json_data = json_encode(['binding_type' => "sms", 'address' => $number]);
                        array_push($subscribers, $json_data);
                        array_push($phones, trim($phone[0]));
                    }
                }
            }
        }

        // $json_data = json_encode(['binding_type' => "sms", 'address' => "+919809144184"]);
        //                 array_push($subscribers,$json_data);

        $sid = TWILIO_ID;
        $token = TWILIO_AUTH_TOKEN;
        $notify_sid = TWILIO_NOTIFY_SID;
        $client = new Client($sid, $token);
        $twilio_number = TWILIO_NUMBER;

        // $json_data = json_encode(['binding_type' => "sms", 'address' => +918289899343]);
        // array_push($subscribers,$json_data);
        // echo "<pre>";
        // print_r($subscribers);
        $start_time = microtime(true);
        if (count($subscribers) > 0) {
            try {

                $request_data = [
                    "toBinding" => $subscribers,
                    'body' => $inst_msg_sms,
                ];
                // Create a notification
                $notification = $client
                    ->notify->services($notify_sid)
                    ->notifications->create($request_data);
                error_log(date("l jS \of F Y h:i:s A") . "--Success Send--send_mailto_customer");
            } catch (Exception $e) {
                error_log(date("l jS \of F Y h:i:s A") . "--Fail Send--send_mailto_customer");
                // die( $e->getCode() . ' : ' . $e->getMessage() );

            }
        }

        echo json_encode(['status' => true, 'message' => "Sent Successfully"]);
        die();
    }
    add_action('wp_ajax_trigger_manual_capture', 'trigger_manual_capture');
    function trigger_manual_capture()
    {

        global $wpdb;

        $pur_rec_id = $_POST['pur_rec_id'];
        $stripe_error = "";

        require_once YITH_WCSTRIPE_DIR . 'includes/class-yith-stripe-api.php';
        require_once YITH_WCSTRIPE_DIR . 'includes/class-yith-stripe-gateway.php';

        $fetch_yith_gateway = new YITH_WCStripe_Gateway();
        $fetch_yith_gateway->init_stripe_sdk();
        // $fetch_if_test_or_live = $fetch_yith_gateway->env;

        $query = "SELECT *, pur_rec.id as pur_rec_id, pur.id as pur_id FROM " . DB_WC_GF_CUSTOMER_PURCHASES_RECURRING . " AS pur_rec JOIN " . DB_WC_GF_CUSTOMER_PURCHASES . " as pur ON pur.id = pur_rec.customer_purchase_id WHERE pur_rec.id = " . $pur_rec_id;
        $data = $wpdb->get_row($query, ARRAY_A);

        // error_log("*** data ****");
        // error_log( print_r($data, TRUE) );

        if ($data['prev_stripe_capture_status'] == 1) {
            echo json_encode(['status' => false, 'message' => 'This payment has already been authorized and captured']);
            die();
        }

        // // N.B : For testing purposes ONLY
        // if($fetch_if_test_or_live == 'live'){
        //     echo "You are running on LIVE Stripe Instance";
        //     return;
        // }
        // // N.B : For testing purposes ONLY

        try {

            $response = YITH_Stripe_API::get_charge($data['prev_stripe_transaction_id']);
            $response->capture();
        } catch (Stripe_CardError $e) {
            $stripe_error = $e->getMessage();
        } catch (Stripe_InvalidRequestError $e) {
            // Invalid parameters were supplied to Stripe's API
            $stripe_error = $e->getMessage();
        } catch (Stripe_AuthenticationError $e) {
            // Authentication with Stripe's API failed
            $stripe_error = $e->getMessage();
        } catch (Stripe_ApiConnectionError $e) {
            // Network communication with Stripe failed
            $stripe_error = $e->getMessage();
        } catch (Stripe_Error $e) {
            // Display a very generic error to the user, and maybe send
            // yourself an email
            $stripe_error = $e->getMessage();
        } catch (Exception $e) {
            // Something else happened, completely unrelated to Stripe
            $stripe_error = $e->getMessage();
        }

        if (!$stripe_error) {
            if ($response['status'] && $response['captured']) {
                if ($wpdb->update(DB_WC_GF_CUSTOMER_PURCHASES_RECURRING, array('prev_stripe_capture_status' => 1), array('id' => $data['pur_rec_id']))) {
                    $expiry = date("Y-m-d", strtotime($data['expiry'] . " +1 month"));
                    $wpdb->update(DB_WC_GF_CUSTOMER_PURCHASES, array('expiry' => $expiry), array('id' => $data['pur_id']));

                    $user_id = $data['customer_id'];
                    $user = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE ID = $user_id");
                    $email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 28", ARRAY_A);
                    $email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 29", ARRAY_A);
                    $cust_subject = $email_user['subject'];
                    $admin_subject = $email_admin['subject'];
                    //Twilio message

                    // ADMIN
                    $admin_msg = $email_admin['body'];
                    $headers = [];
                    preg_match_all('/{(.*?)}/', $admin_msg, $matches);

                    if (in_array("customer_name", $matches[1])) {
                        $admin_msg = str_replace('{customer_name}', $user->display_name, $admin_msg);
                    }
                    if (in_array("order_id", $matches[1])) {
                        $admin_msg = str_replace('{order_id}', $data['order_id'], $admin_msg);
                    }
                    if (in_array("charge", $matches[1])) {
                        $admin_msg = str_replace('{charge}', $data['next_payment_charging_amount'], $admin_msg);
                    }

                    $pack_id = $data['customer_purchase_id'];
                    $package = $wpdb->get_row("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE id =" . $pack_id);
                    if (in_array("package", $matches[1])) {
                        $admin_msg = str_replace('{package}', $package->package_hidden_name, $admin_msg);
                    }

                    $us_id = $package['customer_id'];

                    $childrens = $wpdb->get_results("SELECT * FROM " . DB_CHILD_DETAILS . " WHERE user_id =" . $us_id);

                    $children = '';
                    foreach ($childrens as $key => $value) {
                        # code...
                        $children .= $value->first_name . " " . $value->last_name . ",";
                    }

                    if (in_array("child_name", $matches[1])) {
                        $admin_msg = str_replace('{child_name}', $children, $admin_msg);
                    }
                    $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) {
                            wp_mail($user->user_email, $admin_subject, $admin_msg, $headers);
                        }
                        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)) {
                                    // wp_mail($inst_email, "test Message from phone--".$phone[0], $inst_msg, $headers);
                                    // $args = array(
                                    //     'number_to' => fetchCountryMobileCode($value->ID) . $phone[0],
                                    //     'message' => $inst_msg_sms
                                    // );
                                    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(['status' => true, 'message' => 'Payment has been captured successfully']);
                    die();
                }
            }
        } else {
            echo json_encode(['status' => false, 'message' => $stripe_error]);
            die();
        }
    }
    add_action('wp_ajax_nopriv_appointmentModifyUpdateAdmin', 'appointmentModifyUpdateAdmin');
    add_action('wp_ajax_appointmentModifyUpdateAdmin', 'appointmentModifyUpdateAdmin');
    function appointmentModifyUpdateAdmin()
    {
        global $wpdb;
        $appointment_id = $_POST['appointment_id'];
        $veriStatus = $_POST['status'];
        $appointment_modify = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENT_MODIFY . " WHERE appointment_id = '$appointment_id' order by id desc limit 1 ", ARRAY_A);

        if ($appointment_modify) {
            if ($veriStatus == 1) {
                $wpdb->update(DB_APPOINTMENTS, array('cust_appointment_time' => $appointment_modify['suggested_slot']), array('id' => $appointment_modify['appointment_id']));
                $wpdb->update(DB_APPOINTMENT_MODIFY, array('status' => 1), array('appointment_id' => $appointment_modify['appointment_id']));


                /* Admin */
                $email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 50", ARRAY_A);
                $admin_msg = $email_admin['body'];
                $admin_email = get_option('admin_email');
                $admin_subject = $email_admin['subject'];
                $fetch_appointments = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id=" . $appointment_modify['appointment_id'], ARRAY_A);
                $user = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE id=" . $fetch_appointments['customer_id'], ARRAY_A);
                preg_match_all('/{(.*?)}/', $admin_msg, $matches);
                //customer appointment time
                $split_time = explode(' - ', $fetch_appointments['cust_appointment_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($fetch_appointments['appointment_date'])), $admin_msg);
                }

                if (in_array("appointment_time", $matches[1])) {
                    $admin_msg = str_replace('{appointment_time}', $current_app_time, $admin_msg);
                }

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

                if (in_array("status", $matches[1])) {
                    $admin_msg = str_replace('{status}', 'Accepted', $admin_msg);
                }
                if (in_array("child_name", $matches[1])) {
                    $admin_msg = str_replace('{child_name}',  $fetch_appointments['child_id_name'], $admin_msg);
                }
                $locationid = $fetch_appointments['location_id'];
                $loc  = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id =" . $locationid, ARRAY_A);
                if (in_array("location", $matches[1])) {
                    $admin_msg = str_replace('{location}',  $loc['name'], $admin_msg);
                }

                // $admin_msg = wpautop($content);
                $headers[] = 'Content-Type: text/html; charset=UTF-8';
                $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
                $headers[] = 'Cc: shootinschool@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);
                    }
                    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() );

                                }
                            }
                        }
                    }
                }

                // send email to customer
                $user = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE id=" . $fetch_appointments['customer_id'], ARRAY_A);

                $email_customer = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 51", ARRAY_A);
                $customer_msg = $email_customer['body'];
                $customer_subject = $email_customer['subject'];

                // get location detals
                $location = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id = " . $fetch_appointments['location_id']);
                $location_name = $location->name;

                $result = $wpdb->get_row("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id =" . $fetch_appointments['customer_id'], ARRAY_A);
                $credit = $result['credits'];

                preg_match_all('/{(.*?)}/', $customer_msg, $matches);

                if (in_array("customer_name", $matches[1])) {
                    $customer_msg = str_replace('{customer_name}', $user['display_name'], $customer_msg);
                }

                if (in_array("player_name", $matches[1])) {
                    $customer_msg = str_replace('{player_name}', $fetch_appointments['child_id_name'], $customer_msg);
                }

                if (in_array("appointment_location", $matches[1])) {
                    $customer_msg = str_replace('{appointment_location}', $location_name, $customer_msg);
                }

                if (in_array("appointment_time", $matches[1])) {
                    $customer_msg = str_replace('{appointment_time}', $current_app_time, $customer_msg);
                }

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

                if (in_array("remaining_sessions", $matches[1])) {
                    $customer_msg = str_replace('{remaining_sessions}', $credit, $customer_msg);
                }

                if ($email_customer['notify_via_email'] == 1) {
                    wp_mail($user['user_email'], $customer_subject, $customer_msg, $headers);
                }
                if ($email_customer['notify_via_sms'] == 1) {
                    $admin_msg_sms = $customer_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($user['id'], $key = 'billing_phone');
                    if (count($phone) > 0) {
                        // $args = array(
                        // 	'number_to' => fetchCountryMobileCode($user['id']) . $phone[0],
                        // 	'message' => $admin_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" => $admin_msg_sms, "from" => $twilio_number]
                                );
                                array_push($phones, $phone[0]);
                            } catch (Exception $e) {
                                // die( $e->getCode() . ' : ' . $e->getMessage() );

                            }
                        }
                    }
                }
                // send email to customer ends

                echo json_encode(['status' => true, 'message' => 'Appointment Time Changed Accepted Successfuly']);
                die();
            } else {
                $wpdb->update(DB_APPOINTMENT_MODIFY, array('status' => 2), array('appointment_id' => $appointment_modify['appointment_id']));
                $wpdb->update(DB_APPOINTMENTS, array('appointment_time' => NULL), array('id' => $appointment_modify['appointment_id']));
                $apptID = $appointment_modify['appointment_id'];
                $wpdb->query("DELETE FROM " . DB_APPOINTMENT_INSTRUCTORS . " WHERE `appt_id` = '$apptID'");
                // send email to customer
                $fetch_appointments = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id=" . $appointment_modify['appointment_id'], ARRAY_A);

                $user = $wpdb->get_row("SELECT * FROM " . DB_USERS . " WHERE id=" . $fetch_appointments['customer_id'], ARRAY_A);
                $split_time = explode(' - ', $fetch_appointments['cust_appointment_time']);
                $current_app_time = date('g:i A', strtotime($split_time[0])) . " - " . date('g:i A', strtotime($split_time[1]));

                $email_customer = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 38", ARRAY_A);
                $customer_msg = $email_customer['body'];
                $customer_subject = $email_customer['subject'];
                $headers[] = 'Content-Type: text/html; charset=UTF-8';
                $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';

                // get location detals
                $location = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id = " . $fetch_appointments['location_id']);
                $location_name = $location->name;

                $result = $wpdb->get_row("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE customer_id =" . $fetch_appointments['customer_id'], ARRAY_A);
                $credit = $result['credits'];

                preg_match_all('/{(.*?)}/', $customer_msg, $matches);

                if (in_array("customer_name", $matches[1])) {
                    $customer_msg = str_replace('{customer_name}', $user['display_name'], $customer_msg);
                }

                if (in_array("appointment_location", $matches[1])) {
                    $customer_msg = str_replace('{appointment_location}', $location_name, $customer_msg);
                }

                if (in_array("appointment_time", $matches[1])) {
                    $customer_msg = str_replace('{appointment_time}', $current_app_time, $customer_msg);
                }

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

                if (in_array("player_name", $matches[1])) {
                    $customer_msg = str_replace('{player_name}', $fetch_appointments['child_id_name'], $customer_msg);
                }

                if (in_array("remaining_sessions", $matches[1])) {
                    $customer_msg = str_replace('{remaining_sessions}', $credit, $customer_msg);
                }

                if ($email_customer['notify_via_email'] == 1) {
                    wp_mail($user['user_email'], $customer_subject, $customer_msg, $headers);
                }
                if ($email_customer['notify_via_sms'] == 1) {
                    $admin_msg_sms = $customer_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($user['id'], $key = 'billing_phone');
                    if (count($phone) > 0) {
                        // $args = array(
                        // 	'number_to' => fetchCountryMobileCode($user['id']) . $phone[0],
                        // 	'message' => $admin_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" => $admin_msg_sms, "from" => $twilio_number]
                                );
                                array_push($phones, $phone[0]);
                            } catch (Exception $e) {
                                // die( $e->getCode() . ' : ' . $e->getMessage() );

                            }
                        }
                    }
                }
                // send email to customer ends
                echo json_encode(['status' => true, 'message' => 'Appointment Time Changed Rejected Successfuly']);
                die();
            }
        }
    }

    // admin manage appointments page
    function make_an_appointment()
    {
        global $wpdb;
        $query = "SELECT DISTINCT * FROM " . DB_USERS . " as us JOIN " . DB_WC_GF_CUSTOMER_PURCHASES . " as ps ON ps.customer_id = us.ID GROUP BY us.ID";
        $users = $wpdb->get_results($query, ARRAY_A);

        $now = new DateTime("now", new DateTimeZone(DEFAULT_TIMEZONE));
        $current_date = strtotime($now->format('Y-m-d'));

        ?>
        <div class="wrap">
            <div class="alert alert-info" role="alert" style="border: 1px solid green;border-radius: 5px;">
                <h3> Make an Appointment1 </h3>
            </div>
            <div class="row">
                <div class="col-md-7">
                    <h4>Choose a Customer</h4>
                    <select name="sel_customer" id="sel_customer" onchange="admin_appointment()">
                        <option value=""> -- Choose a Customer -- </option>
                        <?php foreach ($users as $user) {

                        ?>
                            <option value="<?php echo $user['ID']; ?>" <?php echo $cus_id == $user['ID'] ? 'selected' : ''; ?>>
                                <?php
                                $isBwc = get_user_meta($user['ID'], 'isBwc', true);
                                if ($isBwc == 1) {
                                    echo "<b>(BWC)</b> - ";
                                } else {
                                    echo "<b>(SHOOTIN SCHOOL)</b> - ";
                                }

                                echo $user['display_name']; ?> : <?php echo $user['user_email']; ?>
                            </option>
                        <?php } ?>
                    </select>
                </div>
                <br />
            </div>

            <div class="css_loader">Loading&#8230;</div>
            <div class="shop_table shop_table_responsive" id="admin_booking_show" style="display: none;">
                <div class="alert alert-info" role="alert">
                    <h3> Book an Appointment </h3>
                    <div class="outer-d">
                        <form id="createAppointment">
                            <div id="cloneApptDiv">
                                <!-- Append Clone Here -->
                            </div>
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <button type="button" class="button view" onclick="saveAppointment()">Book Appointment</button>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <button type="button" class="button view" onclick="cloneAppointment_backend()">+ Add another</button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal" id="cancelWarningModal" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Cancel Appointment Confirmation</h4>
                    </div>
                    <div class="modal-body" id="appendSavedCardsDiv">
                        <!-- Append Here -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" id="proceedBtn" data-appt_pur_ids="" class="btn btn-primary" onclick="cancelMyAppointment();">Yes, Proceed</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">No</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal" id="booking_error_modal" role="dialog">
            <div class="modal-dialog">
                <!-- Modal content-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">Appointment Booking Error</h4>
                    </div>
                    <div class="modal-body" id="booking_error_modalBody">
                        <!-- Append Here -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Dismiss</button>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal" id="addChildDetailsModal" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title"> Update Team Children Details</h4>
                    </div>
                    <div class="modal-body" id="appendChildDetailsDiv">
                        <!-- Append Here -->
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" onclick="addChildDetails();">Update</button>
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </div>
        </div>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.js"></script>

        <style>
            #sel_package {
                position: relative;
                display: inline-block;
                vertical-align: middle;
                font-size: 13px;
                zoom: 1;
                *display: inline;
                -webkit-user-select: none;
                -moz-user-select: none;
                user-select: none;
            }

            /* @group Base */
            .chosen-container {
                position: relative;
                display: inline-block;
                vertical-align: middle;
                font-size: 13px;
                zoom: 1;
                *display: inline;
                -webkit-user-select: none;
                -moz-user-select: none;
                user-select: none;
            }

            .chosen-container * {
                -webkit-box-sizing: border-box;
                -moz-box-sizing: border-box;
                box-sizing: border-box;
            }

            .chosen-container .chosen-drop {
                position: absolute;
                top: 100%;
                left: -9999px;
                z-index: 1010;
                width: 100%;
                border: 1px solid #aaa;
                border-top: 0;
                background: #fff;
                box-shadow: 0 4px 5px rgba(0, 0, 0, 0.15);
            }

            .chosen-container.chosen-with-drop .chosen-drop {
                left: 0;
            }

            .chosen-container a {
                cursor: pointer;
            }

            .chosen-container .search-choice .group-name,
            .chosen-container .chosen-single .group-name {
                margin-right: 4px;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                font-weight: normal;
                color: #999999;
            }

            .chosen-container .search-choice .group-name:after,
            .chosen-container .chosen-single .group-name:after {
                content: ":";
                padding-left: 2px;
                vertical-align: top;
            }

            /* @end */
            /* @group Single Chosen */
            .chosen-container-single .chosen-single {
                position: relative;
                display: block;
                overflow: hidden;
                padding: 0 0 0 8px;
                height: 25px;
                border: 1px solid #aaa;
                background-color: #fff;
                color: #444;
                text-decoration: none;
                white-space: nowrap;
                line-height: 24px;
            }

            .chosen-container-single .chosen-default {
                color: #999;
            }

            .chosen-container-single .chosen-single span {
                display: block;
                overflow: hidden;
                margin-right: 26px;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

            .chosen-container-single .chosen-single-with-deselect span {
                margin-right: 38px;
            }

            .chosen-container-single .chosen-single abbr {
                position: absolute;
                top: 6px;
                right: 26px;
                display: block;
                width: 12px;
                height: 12px;
                background: url('chosen-sprite.png') -42px 1px no-repeat;
                font-size: 1px;
            }

            .chosen-container-single .chosen-single abbr:hover {
                background-position: -42px -10px;
            }

            .chosen-container-single.chosen-disabled .chosen-single abbr:hover {
                background-position: -42px -10px;
            }

            .chosen-container-single .chosen-single div {
                position: absolute;
                top: 0;
                right: 0;
                display: block;
                width: 18px;
                height: 100%;
            }

            .chosen-container-single .chosen-single div b {
                display: block;
                width: 100%;
                height: 100%;
                background: url('chosen-sprite.png') no-repeat 0px 2px;
            }

            .chosen-container-single .chosen-search {
                position: relative;
                z-index: 1010;
                margin: 0;
                padding: 3px 4px;
                white-space: nowrap;
            }

            .chosen-container-single .chosen-search input[type="text"] {
                margin: 1px 0;
                padding: 4px 20px 4px 5px;
                width: 100%;
                height: auto;
                outline: 0;
                border: 1px solid #aaa;
                background: white url('chosen-sprite.png') no-repeat 100% -20px;
                background: url('chosen-sprite.png') no-repeat 100% -20px;
                font-size: 1em;
                font-family: sans-serif;
                line-height: normal;
                border-radius: 0;
            }

            .chosen-container-single .chosen-drop {
                margin-top: -1px;
                border-radius: 0 0 4px 4px;
                background-clip: padding-box;
            }

            .chosen-container-single.chosen-container-single-nosearch .chosen-search {
                position: absolute;
                left: -9999px;
            }

            /* @end */
            /* @group Results */
            .chosen-container .chosen-results {
                color: #444;
                position: relative;
                overflow-x: hidden;
                overflow-y: auto;
                margin: 0 4px 4px 0;
                padding: 0 0 0 4px;
                max-height: 240px;
                -webkit-overflow-scrolling: touch;
            }

            .chosen-container .chosen-results li {
                display: none;
                margin: 0;
                padding: 5px 6px;
                list-style: none;
                line-height: 15px;
                word-wrap: break-word;
                -webkit-touch-callout: none;
            }

            .chosen-container .chosen-results li.active-result {
                display: list-item;
                cursor: pointer;
            }

            .chosen-container .chosen-results li.disabled-result {
                display: list-item;
                color: #ccc;
                cursor: default;
            }

            .chosen-container .chosen-results li.highlighted {
                background-color: #3875d7;
                background-image: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(20%, #3875d7), color-stop(90%, #2a62bc));
                background-image: -webkit-linear-gradient(#3875d7 20%, #2a62bc 90%);
                background-image: -moz-linear-gradient(#3875d7 20%, #2a62bc 90%);
                background-image: -o-linear-gradient(#3875d7 20%, #2a62bc 90%);
                background-image: linear-gradient(#3875d7 20%, #2a62bc 90%);
                color: #fff;
            }

            .chosen-container .chosen-results li.no-results {
                color: #777;
                display: list-item;
                background: #f4f4f4;
            }

            .chosen-container .chosen-results li.group-result {
                display: list-item;
                font-weight: bold;
                cursor: default;
            }

            .chosen-container .chosen-results li.group-option {
                padding-left: 15px;
            }

            .chosen-container .chosen-results li em {
                font-style: normal;
                text-decoration: underline;
            }


            #ui-datepicker-div {
                display: none;
                background-color: #fff !important;
            }

            .ui-state-disabled span {
                opacity: 0.5 !important;
            }

            .tool {
                position: relative;
                display: inline-block;
            }

            .tool .tooltiptext {
                visibility: hidden;
                width: 400px;
                background-color: #f8f8f8;
                color: black;
                text-align: center;
                border-radius: 6px;
                padding: 5px 0;

                /* Position the tooltip */
                position: absolute;
                z-index: 1;
                bottom: 100%;
                left: 50%;
                margin-left: -125px;
                font-size: 17px;
                text-transform: none;
            }

            .tool:hover .tooltiptext {
                visibility: visible;
            }

            /* @end */
            /* @group Retina compatibility */
            @media only screen and (-webkit-min-device-pixel-ratio: 1.5),
            only screen and (min-resolution: 144dpi),
            only screen and (min-resolution: 1.5dppx) {

                .chosen-rtl .chosen-search input[type="text"],
                .chosen-container-single .chosen-single abbr,
                .chosen-container-single .chosen-single div b,
                .chosen-container-single .chosen-search input[type="text"],
                .chosen-container-multi .chosen-choices .search-choice .search-choice-close,
                .chosen-container .chosen-results-scroll-down span,
                .chosen-container .chosen-results-scroll-up span {
                    background-image: url('chosen-sprite@2x.png') !important;
                    background-size: 52px 37px !important;
                    background-repeat: no-repeat !important;
                }
            }

            /* @end */
        </style>
        <script>
            jQuery(document).ready(function() {
                jQuery("#sel_customer").chosen({
                    search_contains: true
                });
                jQuery('.tooltip').hide();
            });
        </script>
    <?php } ?>
    <?php

    add_action('wp_ajax_nopriv_markasbwc', 'markasbwc');
    add_action('wp_ajax_markasbwc', 'markasbwc');
    function markasbwc()
    {
        $user_id = $_REQUEST['cid'];
        $new_isBwc_value = 1;
        // Update the isBwc user meta field
        update_user_meta($user_id, 'isBwc', $new_isBwc_value);
        echo json_encode(['status' => true, 'message' => 'Updated Successfully']);
        die();
    }

    add_action('wp_ajax_nopriv_unmarkasbwc', 'unmarkasbwc');
    add_action('wp_ajax_unmarkasbwc', 'unmarkasbwc');
    function unmarkasbwc()
    {
        $user_id = $_REQUEST['cid'];
        $new_isBwc_value = 0;
        // Update the isBwc user meta field
        update_user_meta($user_id, 'isBwc', $new_isBwc_value);
        echo json_encode(['status' => true, 'message' => 'Updated Successfully']);
        die();
    }

    add_action('wp_ajax_nopriv_markasselfregister', 'markasselfregister');
    add_action('wp_ajax_markasselfregister', 'markasselfregister');
    function markasselfregister()
    {
        $user_id = $_REQUEST['cid'];
        $new_selfregister_value = 1;  
        // Update the isBwc user meta field
        update_user_meta($user_id, 'isselfregister', $new_selfregister_value);
        echo json_encode(['status' => true, 'message' => 'Updated Successfully']);
        die(); 
    
    }
    
    add_action('wp_ajax_nopriv_unmarkasselfregister', 'unmarkasselfregister');
    add_action('wp_ajax_unmarkasselfregister', 'unmarkasselfregister');
    function unmarkasselfregister()
    {
        $user_id = $_REQUEST['cid'];
        $new_selfregister_value = 0;  
        // Update the isBwc user meta field
        update_user_meta($user_id, 'isselfregister', $new_selfregister_value);
        echo json_encode(['status' => true, 'message' => 'Updated Successfully']);
        die(); 
    
    }