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

	filter_var_array($_POST, FILTER_SANITIZE_STRING);

	global $wpdb;
	$user_id = get_current_user_id();

	$value = explode('|', $_POST['appt_pur_ids']);

	$appointment_id = $value[0];
	$appointment = $wpdb->get_row("SELECT * FROM " . DB_APPOINTMENTS . " WHERE id =" . $appointment_id, ARRAY_A);
	$purchase_id = $value[1];

	$statusFlag = FALSE;
	$charged = false;
	if (isset($_POST['savedCard_id'])) {

		$encrypted_savedCard_id = $_POST['savedCard_id'];
		$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');
		require_once(YITH_WCSTRIPE_DIR . 'includes/class-yith-stripe-gateway-advanced.php');
	
		$fetch_yith_gateway = new YITH_WCStripe_Gateway_Advanced();
		$fetch_yith_gateway->init_stripe_sdk();
	
		//$fetch_if_test_or_live = $fetch_yith_gateway->env;
		require_once(plugin_dir_path(__FILE__).'/stripe-sdk/vendor/autoload.php');
	
	 
		
		$stripe = new \Stripe\StripeClient(STRIPE_API_KEY);

      
        $customer = YITH_WCStripe()->get_customer()->get_usermeta_info($user_id);
		$source = '';
        try {
            $stripe_customer = $stripe->customers->retrieve(
                $customer['id'],
                []
            );

            if($stripe_customer->invoice_settings->default_payment_method != ''){
                $source = $stripe_customer->invoice_settings->default_payment_method;
            }else{
                $source = $stripe_customer->default_source;
            }
        }catch(Exception $e){
            
        }

		 
        $txn = '000000000';
		$stripe_error = '';
        if($source != ''){
			try {
				
	
				$initial_response = $stripe->paymentIntents->create([
					'amount' => 20 * 100,
					'currency' => 'usd',
					'customer' => $customer['id'],
					'payment_method_types' => ['card'],
				]);
	
				$response =$stripe->paymentIntents->confirm(
					$initial_response->id,
					['payment_method' => $source]
				);
	
				$txn = $response->charges->data[0]->id;
				$stripe_error = "";
			} 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) {
				$args = array(
					'appointment_id' => $appointment_id,
					'user_id' => $user_id,
					'stripe_charge_id' => $response->id,
					'charge_amount' => '$20',
					'charge_status' => 'Charge Success',
					'remarks' => 'Charged for cancelling appointment after Cut-Off time'
				);
	
				$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 ($statusFlag) {

		
		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_id = $data['instructor_id'];
		$wpdb->update(DB_APPOINTMENTS, array('is_cancelled' => 1, 'instructor_id' => NULL, 'assigned_instructor' => $instructor_id), array('id' => $appointment_id));
		if ($charged) {
			$email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 14", ARRAY_A);
			$email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 15", ARRAY_A);
			$email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 10", ARRAY_A);
		} else {
			$email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 8", ARRAY_A);
			$email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 9", ARRAY_A);
			$email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 10", ARRAY_A);
		}
		$customer_name = $data['display_name'];
		$appointment_date = $data['appointment_date'];
		$appointment_time = $data['appointment_time'];
		$instructor = get_user_by('ID', $data['instructor_id']);
		$instructor_name = $instructor->display_name;
		$locationid = $data['location_id'];
		$loc = $wpdb->get_row("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE id =" . $locationid, ARRAY_A);


		/* Admin */
		$admin_msg = $email_admin['body'];
		$admin_email = get_option('admin_email');
		$admin_subject = $email_admin['subject'];

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

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

		}else{
		$inst_split = explode(' - ', $data['cust_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])) {
			$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}', $app_time, $admin_msg);
		}
		if ($data['instructor_id'] && in_array("instructor_name", $matches[1])) {
			$admin_msg = str_replace('{instructor_name}', $instructor_name, $admin_msg);
		} else {
			$admin_msg = str_replace('{instructor_name}', '-', $admin_msg);
		}
		if (in_array("appointment_id", $matches[1])) {
			$admin_msg = str_replace('{appointment_id}', $appointment_id, $admin_msg);
		}
		if ($charged && in_array("charge", $matches[1])) {
			$admin_msg = str_replace('{charge}', '$20', $admin_msg);
		}
		if (in_array("child_name", $matches[1])) {
			$admin_msg = str_replace('{child_name}', $data['child_id_name'], $admin_msg);
		}

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

		$headers[] = 'Content-Type: text/html; charset=UTF-8';
		$headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
		$args1 = array(
			'role__in' => ['administrator','siab_sub_admin'],
			'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() );
							
						}
					
					}
				}
			}
		}


		/* Customer */
		$cust_email = $data['user_email'];
		$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}', $app_time, $cust_msg);
		}
		if ($data['instructor_id'] && in_array("instructor_name", $matches[1])) {
			$cust_msg = str_replace('{instructor_name}', $instructor_name, $cust_msg);
		} else {
			$cust_msg = str_replace('{instructor_name}', '-', $cust_msg);
		}
		if (in_array("appointment_id", $matches[1])) {
			$cust_msg = str_replace('{appointment_id}', $appointment_id, $cust_msg);
		}
		if (in_array("charge", $matches[1])) {
			if ($charged) {
				$cust_msg = str_replace('{charge}', '$20', $cust_msg);
			} else {
				$cust_msg = str_replace('{charge}', '0', $cust_msg);
			}
		}
		if (in_array("child_name", $matches[1])) {
			$cust_msg = str_replace('{child_name}', $data['child_id_name'], $cust_msg);
		}

		if (in_array("location", $matches[1])) {
			$cust_msg = str_replace('{location}', $loc['name'], $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'], $key = 'billing_billing_phone');
			if (count($phone) > 0) {
				foreach ($sms_matches[0] as $match) {

					if ($match == "</p>") {
						$cust_msg_sms = str_replace($match, "\n", $cust_msg_sms);
					} else {
						$cust_msg_sms = str_replace($match, '', $cust_msg_sms);
					}
				}
				//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)) {
						
						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 is assigned
		if ($data['instructor_id']) {

			$inst_email = $instructor->user_email;
			$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("instructor_name", $matches[1])) {
				$inst_msg = str_replace('{instructor_name}', $instructor_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("session", $matches[1])){
				$inst_msg = str_replace('{session}',$result['package_hidden_name'],$inst_msg);
			}

			if (in_array("appointment_id", $matches[1])) {
				$inst_msg = str_replace('{appointment_id}', $appointment_id, $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($instructor->id, $key = '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
					// );
					// 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' => 'Your Appointment has been cancelled successfully.']);
	} else {
		echo json_encode(['status' => false, 'message' => 'Your Appointment cancellation failed']);
	}
	die();
}
add_action('wp_ajax_cancel_my_appointment', 'cancel_my_appointment');


// Show cancellation charge alert modal with list of already saved Cards
add_action('wp_ajax_render_cancel_warning_modal', 'render_cancel_warning_modal');
function render_cancel_warning_modal() {

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

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

        

$sp = explode(" - ",$appointment['appointment_time']);
if(count($sp)>0){
$starttimestamp = strtotime($current_time);
$endtimestamp = strtotime($sp[0]);
	$difference = abs($endtimestamp - $starttimestamp)/3600;
}else{
$difference = 10;
}
	

	if(strtotime($appointment_date) == strtotime($current_date) && $difference<6){ // Bookings not cancellable for today
		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();

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

 			if(empty($customer['cards'])){
                try{
                    $api = new YITH_Stripe_API(STRIPE_API_KEY);
					//$api = new YITH_Stripe_API('sk_test_Qf9JajukBCaNmVubuYsDix5u');
                    $customer = $api->get_customer($customer);
                    
                }catch (Exception $e) {
                    // Something else happened, completely unrelated to Stripe
                    $stripe_error = $e->getMessage();
                  }
            }

		if ( ! empty( $customer['cards'] ) ) {
			$cards = array();
			foreach ( $customer['cards'] as $the ) {
				// $card            = new stdClass();
				$card['id']        = $the->id;
				$card['brand']     = $the->brand;
				// $card['slug']      = array_values( array_keys( $this->cards, $card['brand'] ) );
				$card['last4']     = $the->last4;
				// $card['exp_month'] = str_pad( $the->exp_month, 2, '0', STR_PAD_LEFT );
				// $card['exp_year']  = str_pad( substr( $the->exp_year, - 2 ), 2, '0', STR_PAD_LEFT );
				$cards[] = $card;
			}
		}

		ob_start(); ?>

		<?php if(count($cards) > 0){ ?>
			<p>
				<strong>Warning : </strong>You will be charged <strong>$20.00</strong> as cancellation charges. <br/>Are you sure want to cancel your Appointment ?
			</p>
			<div class="row">
				<div class="col-md-12">
				    <div class="form-group">
				        <select class="form-control" id="savedCard_id">
				            <option value=""> -- Choose from Saved Cards -- </option>
				            <?php foreach ($cards as $single) { ?>
				                <option value="<?php echo my_simple_crypt( $single['id'], 'e' ); ?>">
				                	<?php echo $single['brand']; ?>
				                	<?php echo " - XXXX-XXXX-XXXX-" .$single['last4']; ?>
				                </option>
				            <?php } ?>
				        </select>
				    </div>
				</div>
			</div>
		<?php }

	} else{ //Bookings cancellable

		ob_start(); ?>

		<input type="hidden" id="is_chargable" value="9zayp">
		<p>
			Are you sure you wish to cancel your Appointment ?
		</p>

	<?php }

	$renderedHtml = ob_get_clean();

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


// Add/View Team Child Details
add_action('wp_ajax_render_add_child_details_modal', 'render_add_child_details_modal');
function render_add_child_details_modal() {

	global $wpdb;
	$appointment_id = $_POST['appointment_id'];
	$appointment = $wpdb->get_row("SELECT * FROM " .DB_APPOINTMENTS." appt LEFT JOIN " . DB_WC_GF_CUSTOMER_PURCHASES . " pur ON appt.purchase_credits_id = pur.id WHERE appt.id =" . $appointment_id, ARRAY_A);

	// Get the Form fields
	$form = RGFormsModel::get_form_meta($appointment['gf_form_id']);
	$grade_options = RGFormsModel::get_field( $form, 5 );
	$grade_optionsArr = array_column($grade_options->choices, 'text');

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

	$entry = GFAPI::get_entry( $appointment['gform_entry_id'] );
	$kidsCount = rgar( $entry, '14' );

	$team_child_details = $appointment['team_child_details'];
	$team_child_detailsArr = array();
	if($team_child_details){ // View Form
		$hasData = TRUE;
		$team_child_detailsArr = json_decode($team_child_details, TRUE);
	}

	ob_start(); ?>

	<?php if(count($team_child_detailsArr) > 0){
		$target = 'update'; ?>

		<div class="css_loader">Loading&#8230;</div>
		<form id="team_child_detailsForm">
			<input type="hidden" name="appt_id" value="<?php echo $appointment_id; ?>">

			<?php foreach($team_child_detailsArr as $key => $child) { ?>

				<strong> Child Detail #<?php echo $key+1;?> </strong>

				<div class="row">
			    	<div class="col-md-6">
					    <div class="form-group">
					        <input type="text" name="fname[]" class="form-control" placeholder="Enter First Name" value="<?php echo $child['fname'];?>" disabled>
					    </div>
					</div>
					<div class="col-md-6">
					    <div class="form-group">
					        <input type="text" name="lname[]" class="form-control" placeholder="Enter Last Name" value="<?php echo $child['lname'];?>" disabled>
					    </div>
					</div>
				</div>
				<div class="row">
			    	<div class="col-md-6">
					    <div class="form-group">
					        <input type="email" name="email[]" class="form-control" placeholder="Enter Email" value="<?php echo $child['email'];?>" disabled>
					    </div>
					</div>
					<div class="col-md-6">
					    <div class="form-group">
					        <input type="text" name="phone[]" class="form-control" placeholder="Enter PhoneNumber" value="<?php echo $child['phone'];?>" disabled>
					    </div>
					</div>
				</div>

				<!-- <div class="row">
			    	<div class="col-md-6">
					    <div class="form-group">
					    	<select class="form-control sel_grade" name="sel_grade[]" disabled>
					    	    <option value=""> -- Choose Grade -- </option>
					    	    <?php foreach ($grade_optionsArr as $grade) { ?>
					    	        <option value="<?php echo $grade; ?>" <?php echo $child['sel_grade'] == $grade ? 'selected' : '';?> >
					    	        	<?php echo $grade; ?>
					    	        </option>
					    	    <?php } ?>
					    	</select>
					    </div>
					</div>
					<div class="col-md-6">
						<div class="form-group">
							<select class="form-control sel_jersey" name="sel_jersey[]" disabled>
							    <option value=""> -- Choose Jersey Size -- </option>
							    <?php foreach ($jersey_size_optionsArr as $jersey) { ?>
							        <option value="<?php echo $jersey; ?>" <?php echo $child['sel_jersey'] == $jersey ? 'selected' : '';?> >
							        	<?php echo $jersey; ?>
							        </option>
							    <?php } ?>
							</select>
						</div>
					</div>
				</div> -->

			<?php } ?>

		</form>

	<?php } else{
		$target = 'save'; ?>

		<div class="css_loader">Loading&#8230;</div>
		<form id="team_child_detailsForm">
			<input type="hidden" name="appt_id" value="<?php echo $appointment_id; ?>">

			<?php for($i=0; $i<$kidsCount; $i++){ ?>

				<strong> Child Detail #<?php echo $i+1;?> </strong>

				<div class="row">
			    	<div class="col-md-6">
					    <div class="form-group">
					        <input type="text" name="fname[]" class="form-control" placeholder="Enter First Name" required>
					    </div>
					</div>
					<div class="col-md-6">
					    <div class="form-group">
					        <input type="text" name="lname[]" class="form-control" placeholder="Enter Last Name" required>
					    </div>
					</div>
				</div>
                <div class="row">
			    	<div class="col-md-6">
					    <div class="form-group">
					        <input type="email" name="email[]" class="form-control" placeholder="Enter Email" required>
					    </div>
					</div>
					<div class="col-md-6">
					    <div class="form-group">
					        <input type="text" name="phone[]" class="form-control" placeholder="Enter PhoneNumber" required>
					    </div>
					</div>
				</div>
				<!-- <div class="row">
			    	<div class="col-md-6">
					    <div class="form-group">
					    	<select class="form-control sel_grade" name="sel_grade[]" required>
					    	    <option value=""> -- Choose Grade -- </option>
					    	    <?php foreach ($grade_optionsArr as $grade) { ?>
					    	        <option value="<?php echo $grade; ?>">
					    	        	<?php echo $grade; ?>
					    	        </option>
					    	    <?php } ?>
					    	</select>
					    </div>
					</div>
					<div class="col-md-6">
						<div class="form-group">
							<select class="form-control sel_jersey" name="sel_jersey[]" required>
							    <option value=""> -- Choose Jersey Size -- </option>
							    <?php foreach ($jersey_size_optionsArr as $jersey) { ?>
							        <option value="<?php echo $jersey; ?>">
							        	<?php echo $jersey; ?>
							        </option>
							    <?php } ?>
							</select>
						</div>
					</div>
				</div> -->

			<?php } ?>

		</form>

	<?php }

	$renderedHtml = ob_get_clean();

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

// Save Team Child Details
add_action('wp_ajax_save_team_child_details', 'save_team_child_details');
function save_team_child_details() {

	global $wpdb;
	parse_str($_POST['form_data'], $form_data);

	$appt_id = $form_data['appt_id'];

	$mainArr = array();
	foreach ($form_data['fname'] as $key => $fname) {
		$tempArr = array();
		$tempArr['fname'] = $fname;
		$tempArr['lname'] = $form_data['lname'][$key];
		$tempArr['email'] = $form_data['email'][$key];
		$tempArr['phone'] = $form_data['phone'][$key];

		// $tempArr['sel_grade'] = $form_data['sel_grade'][$key];
		// $tempArr['sel_jersey'] = $form_data['sel_jersey'][$key];

		$mainArr[] = $tempArr;
	}

	$args = array(
		"team_child_details" => json_encode($mainArr),
	);

	$wpdb->update(DB_APPOINTMENTS, $args, ['id' => $appt_id]);

	echo json_encode(['status' => true, 'message' => 'Team children details have been successfully updated']);
	die();
}
// -----------------------------------------

add_action('wp_ajax_nopriv_Subscription_Pause', 'Subscription_Pause');
add_action('wp_ajax_Subscription_Pause', 'Subscription_Pause');
function Subscription_Pause() {
	global $wpdb;
	$customer_purchase_id = $_POST['customer_purchase_id'];


	$wpdb->update( DB_WC_GF_CUSTOMER_PURCHASES_RECURRING, array('recurring_status'=> 1), array('customer_purchase_id' => $customer_purchase_id) );

	$wpdb->update(DB_WC_GF_CUSTOMER_PURCHASES, array('billable' => 0), array('id'=> $customer_purchase_id));


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


		// 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("renew_date", $matches[1])){
			$admin_msg = str_replace('{renew_date}',date('l, F d Y ', strtotime($renew_date)),$admin_msg);
		}
if (in_array("package", $matches[1])) {
			$admin_msg = str_replace('{package}', $data['package_hidden_name'],$admin_msg);
		}

		$us_id = $data['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("children", $matches[1])) {
			$admin_msg = str_replace('{children}', $children,$admin_msg);
		}

		if(in_array("pause_date", $matches[1])){
			$admin_msg = str_replace('{pause_date}',date('l, F d Y ', strtotime(date('Y-m-d'))),$admin_msg);
		}
		if (in_array("resume_date", $matches[1])) {
			$admin_msg = str_replace('{resume_date}', 'Unavailable',$admin_msg);
		}


		$date2=date_create($data['expiry']);
		$date1=date_create($data['created_at']);
		$diff=date_diff($date1,$date2);

		$consumed_month = $diff->m;

		$months_left = 4-$consumed_month;

		if($months_left<0){
			$months_left = 0;
		}
		if (in_array("months_remaining", $matches[1])) {
			$admin_msg = str_replace('{months_remaining}', $months_left,$admin_msg);
		}

		$date1=date_create(date('Y-m-d'));
		$date2=date_create(date('Y-m-t'));
		$diff=date_diff($date1,$date2);

		$days_left = $diff->d;

		if (in_array("days_left", $matches[1])) {
			$admin_msg = str_replace('{days_left}', $days_left,$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){

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

			}
	    	}
		}

		// CUSTOMER //
		$user = $wpdb->get_row("SELECT * FROM ".DB_USERS." WHERE ID = $user_id");
		$email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 30", ARRAY_A);
		$cust_subject = $email_user['subject'];
		$cust_msg = $email_user['body'];
		$headers = [];
		preg_match_all('/{(.*?)}/', $cust_msg, $matches);
		if(in_array("customer_name", $matches[1])){
			$cust_msg = str_replace('{customer_name}',$user->display_name,$cust_msg);
		}
		if (in_array("order_id", $matches[1])) {
			$cust_msg = str_replace('{order_id}', $data['order_id'],$cust_msg);
		}
		
			if (in_array("package", $matches[1])) {
			$admin_msg = str_replace('{package}', $data['package_hidden_name'],$admin_msg);
		}

		$us_id = $user->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("children", $matches[1])) {
			$cust_msg = str_replace('{children}', $children,$cust_msg);
		}

		if(in_array("pause_date", $matches[1])){
			$cust_msg = str_replace('{pause_date}',date('l, F d Y ', strtotime(date('Y-m-d'))),$cust_msg);
		}
		if (in_array("resume_date", $matches[1])) {
			$cust_msg = str_replace('{resume_date}', 'Unavailable',$cust_msg);
		}


		$date2=date_create($data['expiry']);
		$date1=date_create($data['created_at']);
		$diff=date_diff($date1,$date2);

		$consumed_month = $diff->m;

		$months_left = 4-$consumed_month;

		if($months_left<0){
			$months_left = 0;
		}
		if (in_array("months_remaining", $matches[1])) {
			$cust_msg = str_replace('{months_remaining}', $months_left,$cust_msg);
		}

		$date1=date_create(date('Y-m-d'));
		$date2=date_create(date('Y-m-t'));
		$diff=date_diff($date1,$date2);

		$days_left = $diff->d;

		if (in_array("days_left", $matches[1])) {
			$cust_msg = str_replace('{days_left}', $days_left,$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( $user->user_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);
			$admin_msg_sms = str_replace('&nbsp'," ",$admin_msg_sms);
			preg_match_all('/<(.*?)>/', $cust_msg_sms, $sms_matches);
			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
			// $user_id= get_current_user_id();
			$user_id= $us_id;
			$phone=get_user_meta( $user_id,'billing_billing_phone');
			if(count($phone)>0){
				// $args = array(
				// 	'number_to'=> fetchCountryMobileCode($user_id) . $phone[0],
				// 	'message' => $cust_msg_sms
				// );
				// twl_send_sms( $args );
				$phones = [];
				if (!in_array($phone[0], $phones)) {
						
					try{
						$number = fetchCountryMobileCode($user_id) . $phone[0];
						// twl_send_sms($args);
						$sid = TWILIO_ID;
						$token = TWILIO_AUTH_TOKEN;
						// In production, these should be environment variables. E.g.:
						// $auth_token = $_ENV["TWILIO_AUTH_TOKEN"]
						
						// A Twilio number you own with SMS capabilities
						$twilio_number = TWILIO_NUMBER;
						$twilio = new Client($sid, $token);
					
						$message = $twilio->messages->create($number,
											   ["body" => $cust_msg_sms, "from" => $twilio_number] );
						array_push($phones,$phone[0]);
					}catch (Exception $e) {
							// die( $e->getCode() . ' : ' . $e->getMessage() );
						
					}
				
				}
			}
		}
   echo json_encode(['status' => true, 'message' => 'Your Subscription has been Pauseed successfully.']);
   die();

}
add_action('wp_ajax_nopriv_Subscription_Resume', 'Subscription_Resume');
add_action('wp_ajax_Subscription_Resume', 'Subscription_Resume');
function Subscription_Resume() {

	global $wpdb;
	$customer_purchase_id = $_POST['customer_purchase_id'];


	$wpdb->update( DB_WC_GF_CUSTOMER_PURCHASES_RECURRING, array('recurring_status'=> 0), array('customer_purchase_id' => $customer_purchase_id) );

	$wpdb->update(DB_WC_GF_CUSTOMER_PURCHASES, array('billable' => 1), array('id'=> $customer_purchase_id));

	$data = $wpdb->get_row("SELECT * FROM ".DB_WC_GF_CUSTOMER_PURCHASES." WHERE id =" . $customer_purchase_id, ARRAY_A);
	$renew_date = $data['expiry'];
	$user_id = $data['customer_id'];
	$user = $wpdb->get_row("SELECT * FROM ".DB_USERS." WHERE ID = $user_id");
	$email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 33", ARRAY_A);
	$admin_subject = $email_admin['subject'];
	//Twilio message
	// error_log("*******:".$user_id);


		// 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("renew_date", $matches[1])){
			$admin_msg = str_replace('{renew_date}',date('l, F d Y ', strtotime($renew_date)),$admin_msg);
		}

		if (in_array("package", $matches[1])) {
			$admin_msg = str_replace('{package}', $data['package_hidden_name'],$admin_msg);
		}

		$us_id = $data['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("children", $matches[1])) {
			$admin_msg = str_replace('{children}', $children,$admin_msg);
		}

		if(in_array("pause_date", $matches[1])){
			$admin_msg = str_replace('{pause_date}','Unavailable',$admin_msg);
		}
		if (in_array("resume_date", $matches[1])) {
			$admin_msg = str_replace('{resume_date}', date('l, F d Y ', strtotime(date('Y-m-d'))),$admin_msg);
		}


		$date2=date_create($data['expiry']);
		$date1=date_create($data['created_at']);
		$diff=date_diff($date1,$date2);

		$consumed_month = $diff->m;

		$months_left = 4-$consumed_month;

		if($months_left<0){
			$months_left = 0;
		}
		if (in_array("months_remaining", $matches[1])) {
			$admin_msg = str_replace('{months_remaining}', $months_left,$admin_msg);
		}

		$date1=date_create(date('Y-m-d'));
		$date2=date_create(date('Y-m-t'));
		$diff=date_diff($date1,$date2);

		$days_left = $diff->d;

		if (in_array("days_left", $matches[1])) {
			$admin_msg = str_replace('{days_left}', $days_left,$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){
				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() );
						
					}
				
				}

			}
		}	}

		// CUSTOMER //

		$user = $wpdb->get_row("SELECT * FROM ".DB_USERS." WHERE ID = $user_id");


		$email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 32", ARRAY_A);
		$cust_subject = $email_user['subject'];
		$cust_msg = $email_user['body'];
		$headers = [];
		preg_match_all('/{(.*?)}/', $cust_msg, $matches);
		if(in_array("customer_name", $matches[1])){
			$cust_msg = str_replace('{customer_name}',$user->display_name,$cust_msg);
		}
		if (in_array("order_id", $matches[1])) {
			$cust_msg = str_replace('{order_id}', $data['order_id'],$cust_msg);
		}
		if(in_array("renew_date", $matches[1])){
			$cust_msg = str_replace('{renew_date}',date('l, F d Y ', strtotime($renew_date)),$cust_msg);
		}

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

		$us_id = $data['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("children", $matches[1])) {
			$cust_msg = str_replace('{children}', $children,$cust_msg);
		}

		if(in_array("pause_date", $matches[1])){
			$cust_msg = str_replace('{pause_date}','Unavailable',$cust_msg);
		}
		if (in_array("resume_date", $matches[1])) {
			$cust_msg = str_replace('{resume_date}', date('l, F d Y ', strtotime(date('Y-m-d'))),$cust_msg);
		}


		$date2=date_create($data['expiry']);
		$date1=date_create($data['created_at']);
		$diff=date_diff($date1,$date2);

		$consumed_month = $diff->m;

		$months_left = 4-$consumed_month;

		if($months_left<0){
			$months_left = 0;
		}
		if (in_array("months_remaining", $matches[1])) {
			$cust_msg = str_replace('{months_remaining}', $months_left,$cust_msg);
		}

		$date1=date_create(date('Y-m-d'));
		$date2=date_create(date('Y-m-t'));
		$diff=date_diff($date1,$date2);

		$days_left = $diff->d;

		if (in_array("days_left", $matches[1])) {
			$cust_msg = str_replace('{days_left}', $days_left,$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( $user->user_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);
			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
			// $user_id= get_current_user_id();
			$user_id= $us_id;
			$phone=get_user_meta( $user_id,'billing_billing_phone');
			if(count($phone)>0){
				// $args = array(
				// 	'number_to'=> fetchCountryMobileCode($user_id) . $phone[0],
				// 	'message' => $cust_msg_sms
				// );
				// twl_send_sms( $args );
				$phones = [];
				if (!in_array($phone[0], $phones)) {
						
					try{
						$number = fetchCountryMobileCode($user_id) . $phone[0];
						// twl_send_sms($args);
						$sid = TWILIO_ID;
						$token = TWILIO_AUTH_TOKEN;
						// In production, these should be environment variables. E.g.:
						// $auth_token = $_ENV["TWILIO_AUTH_TOKEN"]
						
						// A Twilio number you own with SMS capabilities
						$twilio_number = TWILIO_NUMBER;
						$twilio = new Client($sid, $token);
					
						$message = $twilio->messages->create($number,
											   ["body" => $cust_msg_sms, "from" => $twilio_number] );
						array_push($phones,$phone[0]);
					}catch (Exception $e) {
							// die( $e->getCode() . ' : ' . $e->getMessage() );
						
					}
				
				}
			}
		}
 echo json_encode(['status' => true, 'message' => 'Your Subscription has been Resumed successfully.']);
   die();

}
add_action('wp_ajax_nopriv_Subscription_cancel', 'Subscription_cancel');
add_action('wp_ajax_Subscription_cancel', 'Subscription_cancel');
function Subscription_cancel() {

	global $wpdb;
	$customer_purchase_id = $_POST['customer_purchase_id'];

	$wpdb->delete( DB_WC_GF_CUSTOMER_PURCHASES_RECURRING, array( 'customer_purchase_id' => $customer_purchase_id ) );

	$appt =  $wpdb->get_row("SELECT * FROM " . DB_WC_GF_CUSTOMER_PURCHASES . " WHERE id =". $customer_purchase_id);

	if($appt->package_hidden_name == 'unlimited'){
		$wpdb->update( DB_WC_GF_CUSTOMER_PURCHASES, array( 'billable' => 0,'is_cancelled' => 1,'customer_cancelled'=> $_POST['is_customer'] ) , array( 'id' => $customer_purchase_id ) );
	}else{
		$wpdb->update( DB_WC_GF_CUSTOMER_PURCHASES, array( 'billable' => 0,'is_cancelled' => 1,'customer_cancelled'=> $_POST['is_customer'] ) , array( 'id' => $customer_purchase_id ) );
	}

	
	$data = $wpdb->get_row("SELECT * FROM ".DB_WC_GF_CUSTOMER_PURCHASES." WHERE id =" . $customer_purchase_id, ARRAY_A);
	$user_id = $data['customer_id'];
	$user = $wpdb->get_row("SELECT * FROM ".DB_USERS." WHERE ID = $user_id");
	$email_admin = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 35", ARRAY_A);

	$admin_subject = $email_admin['subject'];
	//Twilio message
	// error_log("*******:".$user_id);


		// 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("expiry_date", $matches[1])){
			$admin_msg = str_replace('{expiry_date}',date('l, F d Y ', strtotime($data['expiry'])),$admin_msg);
		}


		if (in_array("package", $matches[1])) {
			$admin_msg = str_replace('{package}', $data['package_hidden_name'],$admin_msg);
		}

		$us_id = $data['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("children", $matches[1])) {
			$admin_msg = str_replace('{children}', $children,$admin_msg);
		}

		if(in_array("unsub_date", $matches[1])){
			$admin_msg = str_replace('{unsub_date}',date('l, F d Y ', strtotime(date('Y-m-d'))),$admin_msg);
		}
		if (in_array("resume_date", $matches[1])) {
			$admin_msg = str_replace('{final_date}', date('l, F d Y ', strtotime(date('Y-m-t'))),$admin_msg);
		}



		$headers[] = 'Content-Type: text/html; charset=UTF-8';
		$headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
		$args1 = array(
			'role__in' => ['administrator','siab_sub_admin'],
			'orderby' => 'user_nicename',
			'order' => 'ASC'
		);
		$administrator = get_users($args1);
		foreach ($administrator as $user) {
				$admin_id=$user->ID;
			if($email_admin['notify_via_email']==1){
				try {
					//code...
					wp_mail( $user->user_email, $admin_subject,$admin_msg ,$headers);
	
				} catch (Exception $th) {
					//throw $th;
				}


			}
			if($email_admin['notify_via_sms']==1){
			$admin_msg_sms=$admin_msg ;
			$admin_msg_sms = str_replace('<br>',"\n",$admin_msg_sms);
			$admin_msg_sms = str_replace('&nbsp'," ",$admin_msg_sms);
			preg_match_all('/<(.*?)>/', $admin_msg_sms, $sms_matches);
			foreach($sms_matches[0] as $match){
				
			if($match == "</p>"){
			$admin_msg_sms = str_replace($match, "\n", $admin_msg_sms);
			}else{
			$admin_msg_sms = str_replace($match, '', $admin_msg_sms);
			}
			}
			//Twilio message
			$phone=get_user_meta( $admin_id, $key = 'billing_phone');
			if(count($phone)>0){
				// $args = array(
				// 	'number_to'=> fetchCountryMobileCode($admin_id) . $phone[0],
				// 	'message' => $admin_msg_sms
				// );
				// twl_send_sms( $args );
				$phones = [];
				if (!in_array($phone[0], $phones)) {
						
					try{
						$number = fetchCountryMobileCode($admin_id) . $phone[0];
						// twl_send_sms($args);
						$sid = TWILIO_ID;
						$token = TWILIO_AUTH_TOKEN;
						// In production, these should be environment variables. E.g.:
						// $auth_token = $_ENV["TWILIO_AUTH_TOKEN"]
						
						// A Twilio number you own with SMS capabilities
						$twilio_number = TWILIO_NUMBER;
						$twilio = new Client($sid, $token);
					
						$message = $twilio->messages->create($number,
											   ["body" => $admin_msg_sms, "from" => $twilio_number] );
						array_push($phones,$phone[0]);
					}catch (Exception $e) {
							// die( $e->getCode() . ' : ' . $e->getMessage() );
						
					}
				
				}

			}
		}
	}
		// CUSTOMER //

		$user = $wpdb->get_row("SELECT * FROM ".DB_USERS." WHERE ID = $user_id");


		$email_user = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 34", ARRAY_A);
		$cust_subject = $email_user['subject'];
		$cust_msg = $email_user['body'];
		$headers = [];
		preg_match_all('/{(.*?)}/', $cust_msg, $matches);
		if(in_array("customer_name", $matches[1])){
			$cust_msg = str_replace('{customer_name}',$user->display_name,$cust_msg);
		}
		if (in_array("order_id", $matches[1])) {
			$cust_msg = str_replace('{order_id}', $data['order_id'],$cust_msg);
		}
		if(in_array("expiry_date", $matches[1])){
			$cust_msg = str_replace('{expiry_date}',date('l, F d Y ', strtotime($data['expiry'])),$cust_msg);
		}
		if (in_array("package", $matches[1])) {
			$cust_msg = str_replace('{package}', $data['package_hidden_name'],$cust_msg);
		}

		$us_id = $data['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("children", $matches[1])) {
			$cust_msg = str_replace('{children}', $children,$cust_msg);
		}

		if(in_array("unsub_date", $matches[1])){
			$cust_msg = str_replace('{unsub_date}',date('l, F d Y ', strtotime(date('Y-m-d'))),$cust_msg);
		}
		if (in_array("resume_date", $matches[1])) {
			$cust_msg = str_replace('{final_date}', date('l, F d Y ', strtotime(date('Y-m-t'))),$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( $user->user_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);
			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
			// $user_id= get_current_user_id();
			// $user_id= $us_id;
			$phone=get_user_meta( $user_id,'billing_billing_phone');
			if(count($phone)>0){
				// $args = array(
				// 	'number_to'=> fetchCountryMobileCode($user_id) . $phone[0],
				// 	'message' => $cust_msg_sms
				// );
				// twl_send_sms( $args );
				$phones = [];
				if (!in_array($phone[0], $phones)) {
						
					try{
						$number = fetchCountryMobileCode($user_id) . $phone[0];
						// twl_send_sms($args);
						$sid = TWILIO_ID;
						$token = TWILIO_AUTH_TOKEN;
						// In production, these should be environment variables. E.g.:
						// $auth_token = $_ENV["TWILIO_AUTH_TOKEN"]
						
						// A Twilio number you own with SMS capabilities
						$twilio_number = TWILIO_NUMBER;
						$twilio = new Client($sid, $token);
					
						$message = $twilio->messages->create($number,
											   ["body" => $cust_msg_sms, "from" => $twilio_number] );
						array_push($phones,$phone[0]);
					}catch (Exception $e) {
							// die( $e->getCode() . ' : ' . $e->getMessage() );
						
					}
				
				}
			}
		}
   echo json_encode(['status' => true, 'message' => 'Your Subscription has been Canceled successfully.']);
   die();

}

// View Children Details
add_action('wp_ajax_nopriv_render_view_child_details_modal', 'render_view_child_details_modal');
add_action('wp_ajax_render_view_child_details_modal', 'render_view_child_details_modal');
function render_view_child_details_modal() {
	global $wpdb;
	$i = 1;
	$user_id = get_current_user_id();
	$allChilds = $wpdb->get_results("SELECT * FROM  " . DB_CHILD_DETAILS . " WHERE user_id = '$user_id'");
	ob_start(); ?>
	<table>
		<thead>
			<th> Sl No </th>
			<th> Child Name </th>
			<th> Grade</th>
			<th> Jersey Size </th>
		</thead>
		<tbody>
			<?php foreach ($allChilds as $allChild) : ?>
				<tr class="order">
					<td><?=$i++ ?></td>
					<td><?=$allChild->first_name.' '.$allChild->last_name?></td>
					<td><?=$allChild->grade?></td>
					<td><?=$allChild->jersey_size?></td>
				</tr>
			<?php endforeach; ?>
		</tbody>
	</table>
	<?php
	$renderedHtml = ob_get_clean();
	echo json_encode(['status' => true, 'renderedHtml' => $renderedHtml]);
	die();
}