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/bwcsports-site/wp-content/themes/salient/functions.php
<?php

date_default_timezone_set('Asia/Kolkata' );
$apiurl =  BWC_API_LOGIN_ENDPOINT;
$siteurl =  WP_HOME;
//  session_start();
// echo $_SESSION['uid'];
/**
 * Salient functions and definitions.
 *
 * @package Salient
 * @since 1.0
 */


/**
 * Define Constants.
 */
require_once 'vendor/autoload.php';

use GuzzleHttp\Client;
// require_once '/guzzle-7.8/guzzle-7.8/src/Client.php';


$splash_inc_path = get_template_directory() . '/includes';
// Gravity Form IDs start
if (!defined('GF_INDIVIDUAL_FORM_ID'))
  define('GF_INDIVIDUAL_FORM_ID', 15);

// if (!defined('GF_PERSONAL_FORM_ID'))
// 	define('GF_PERSONAL_FORM_ID', 13);

if (!defined('GF_GROUP_FORM_ID'))
  define('GF_GROUP_FORM_ID', 13);

// if (!defined('GF_GROUP_FORM_ID'))
// define('GF_GROUP_FORM_ID', 44);

if (!defined('GF_UNLIMITED_FORM_ID'))
  define('GF_UNLIMITED_FORM_ID', 16);

/* PRODUCTION */

// if (!defined('GF_CHILD_DETAILS_FORM_ID'))
// 	 define('GF_CHILD_DETAILS_FORM_ID', 46);
// if (!defined('GF_TEAM_FORM_ID'))
//   define('GF_TEAM_FORM_ID', 47);

/* Gravity Form IDs end */

/* STAGING */

if (!defined('GF_CHILD_DETAILS_FORM_ID'))
  define('GF_CHILD_DETAILS_FORM_ID', 29);
if (!defined('GF_TEAM_FORM_ID'))
  define('GF_TEAM_FORM_ID', 28);

require_once($splash_inc_path . '/setup.php');
require_once($splash_inc_path . '/custom.php');


function enqueue_jquery()
{
  wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'enqueue_jquery');

//define('BWC_API_LOGIN_ENDPOINT', 'https://shootin-stage.spericorn.com');
function enqueue_custom_script() {
    // Enqueue your custom.js file
    wp_enqueue_script('custom-js', get_stylesheet_directory_uri() . '/assets/custom/js/custom.js', array('jquery'), '2.1.4', true );

    // Pass the constant value to JavaScript
    wp_localize_script('custom-js', 'BWC_API', array(
        'login_endpoint' => BWC_API_LOGIN_ENDPOINT,
    ));
}
add_action('wp_enqueue_scripts', 'enqueue_custom_script');


function custom_footer_script()
{
  // Start or resume the session
  session_start();

  // Output the jQuery code only if $_SESSION['uid'] is set
  if (isset($_SESSION['uid'])) {
?>
    <script>
      jQuery(document).ready(function($) {
        // Change the menu item text to "My Account"
        $('#menu-item-1675').hide();
      });
    </script>
  <?php
  } else {
  ?>
    <script>
      jQuery(document).ready(function($) {
        // Change the menu item text to "My Account"
        $('#menu-item-1674').hide();
      });
    </script>
<?php
  }
}
add_action('wp_footer', 'custom_footer_script');
define('NECTAR_THEME_DIRECTORY', get_template_directory());
define('NECTAR_FRAMEWORK_DIRECTORY', get_template_directory_uri() . '/nectar/');
define('NECTAR_THEME_NAME', 'salient');


if (!function_exists('get_nectar_theme_version')) {
  function nectar_get_theme_version()
  {
    return '11.0.4';
  }
}


/**
 * Load text domain.
 */
add_action('after_setup_theme', 'nectar_lang_setup');

if (!function_exists('nectar_lang_setup')) {
  function nectar_lang_setup()
  {
    load_theme_textdomain('salient', get_template_directory() . '/lang');
  }
}


/**
 * General WordPress.
 */
require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/wp-general.php';


/**
 * Get Salient theme options.
 */

function get_nectar_theme_options()
{

  $legacy_options  = get_option('salient');
  $current_options = get_option('salient_redux');

  if (!empty($current_options)) {
    return $current_options;
  } elseif (!empty($legacy_options)) {
    return $legacy_options;
  } else {
    return $current_options;
  }
}

$nectar_options                    = get_nectar_theme_options();
$nectar_get_template_directory_uri = get_template_directory_uri();



/**
 * Register/Enqueue theme assets.
 */
require_once NECTAR_THEME_DIRECTORY . '/includes/class-nectar-element-assets.php';
require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/enqueue-scripts.php';
require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/enqueue-styles.php';
require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/dynamic-styles.php';


/**
 * Salient Plugin notices.
 */
require_once NECTAR_THEME_DIRECTORY . '/nectar/plugin-notices/salient-plugin-notices.php';


/**
 * Salient welcome page.
 */
require_once NECTAR_THEME_DIRECTORY . '/nectar/welcome/welcome-page.php';


/**
 * Theme hooks & actions.
 */
function nectar_hooks_init()
{

  require_once NECTAR_THEME_DIRECTORY . '/nectar/hooks/hooks.php';
  require_once NECTAR_THEME_DIRECTORY . '/nectar/hooks/actions.php';
}



add_action('after_setup_theme', 'nectar_hooks_init', 10);


/**
 * Post category meta.
 */
require_once NECTAR_THEME_DIRECTORY . '/nectar/meta/category-meta.php';


/**
 * Media and theme image sizes.
 */
require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/media.php';


/**
 * Navigation menus
 */
require_once NECTAR_THEME_DIRECTORY . '/nectar/assets/functions/wp-menu-custom-items/menu-item-custom-fields.php';
require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/nav-menus.php';


/**
 * TGM Plugin inclusion.
 */
require_once NECTAR_THEME_DIRECTORY . '/nectar/tgm-plugin-activation/class-tgm-plugin-activation.php';
require_once NECTAR_THEME_DIRECTORY . '/nectar/tgm-plugin-activation/required_plugins.php';


/**
 * WPBakery functionality.
 */

require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/wpbakery-init.php';

require_once get_template_directory() . '/stripe-php/init.php';

if (!is_page('my-account')) {
  /**
   * Theme skin specific class and assets.
   */
  $nectar_theme_skin    = (!empty($nectar_options['theme-skin'])) ? $nectar_options['theme-skin'] : 'original';
  $nectar_header_format = (!empty($nectar_options['header_format'])) ? $nectar_options['header_format'] : 'default';

  if ('centered-menu-bottom-bar' === $nectar_header_format) {
    $nectar_theme_skin = 'material';
  }

  add_filter('body_class', 'nectar_theme_skin_class');

  function nectar_theme_skin_class($classes)
  {
    global $nectar_theme_skin;
    $classes[] = $nectar_theme_skin;
    return $classes;
  }


  function nectar_theme_skin_css()
  {
    global $nectar_theme_skin;
    wp_enqueue_style('skin-' . $nectar_theme_skin);
  }

  add_action('wp_enqueue_scripts', 'nectar_theme_skin_css');



  /**
   * Search related.
   */
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/search.php';


  /**
   * Register Widget areas.
   */
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/widget-related.php';


  /**
   * Header navigation helpers.
   */
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/header.php';


  /**
   * Blog helpers.
   */
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/blog.php';


  /**
   * Page helpers.
   */
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/page.php';
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/footer.php';

  /**
   * Theme options panel (Redux).
   */
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/redux-salient.php';


  /**
   * WordPress block editor helpers (Gutenberg).
   */
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/gutenberg.php';


  /**
   * Admin assets.
   */
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/admin-enqueue.php';


  /**
   * Pagination Helpers.
   */
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/pagination.php';


  /**
   * Page header.
   */
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/page-header.php';


  /**
   * Third party.
   */
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/wpml.php';
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/woocommerce.php';


  /**
   * v10.5 update assist.
   */
  require_once NECTAR_THEME_DIRECTORY . '/nectar/helpers/update-assist.php';
}
/**
 * Custom logout function.
 *
 * @param string $redirect_url URL to redirect to after logout.
 */
function custom_logout($redirect_url = '')
{
  // Log the user out
  session_start();
  session_unset();
  session_destroy();
  wp_logout();

  // Redirect to the specified URL or the home URL if not provided
  // $redirect_url =$siteurl.'/';//$redirect_url = !empty($redirect_url) ? esc_url($redirect_url) : home_url('/');
  
  $redirect_url = !empty($redirect_url) ? esc_url($redirect_url) : WP_HOME;
  wp_safe_redirect($redirect_url);
  exit;
}

// Hook into the WordPress init action to check for custom logout request
add_action('init', 'check_custom_logout');

/**
 * Check for custom logout request.
 */
function check_custom_logout()
{
  // Check if the custom logout action is triggered
  if (isset($_GET['action']) && $_GET['action'] === 'custom_logout') {

    // Call the custom_logout function with a redirect URL if needed
    $redirect_url = isset($_GET['redirect']) ? $_GET['redirect'] : '';
    custom_logout($redirect_url);
  }
}

function enqueue_toastr_assets() {
    // Enqueue Toastr CSS
    wp_enqueue_style( 'toastr-css', 'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css', array(), '2.1.4', 'all' );

    // Enqueue Toastr JS
    wp_enqueue_script( 'toastr-js', 'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js', array('jquery'), '2.1.4', true );
}

add_action( 'wp_enqueue_scripts', 'enqueue_toastr_assets' );


function custom_menu()
{
  $menu = '<ul id="primary-menu">';
  // echo $_SESSION['uid'];
  if (isset($_SESSION['uid'])) {
    // User is logged in, show "My Account" link
    $menu .= '<li><a href="' . home_url('/my-account/') . '">My Account</a></li>';
  } else {
    // User is not logged in, show "Login" link
    $menu .= '<li><a href="' . wp_login_url() . '">Login</a></li>';
  }

  // Add other menu items as needed
  $menu .= '<li><a href="' . home_url('/') . '">Home</a></li>';
  $menu .= '<li><a href="' . home_url('/about/') . '">About</a></li>';

  $menu .= '</ul>';

  echo $menu;
}

// Register the menu
add_action('init', 'register_custom_menu');

function register_custom_menu()
{
  register_nav_menu('primary-menu', __('Primary Menu'));
}

// add_action('wp_sync_product_cron', 'sync_product_cron');
// function sync_product_cron()
// {

//   $curl = curl_init();

//   curl_setopt_array($curl, array(
//     CURLOPT_URL => 'https://shootinschool.spericorn.com/wp-json/wc/v3/products',
//     CURLOPT_RETURNTRANSFER => true,
//     CURLOPT_ENCODING => '',
//     CURLOPT_MAXREDIRS => 10,
//     CURLOPT_TIMEOUT => 0,
//     CURLOPT_FOLLOWLOCATION => true,
//     CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//     CURLOPT_CUSTOMREQUEST => 'GET',
//     CURLOPT_HTTPHEADER => array(
//       'Authorization: Basic Y2tfNzQ0ZjQ4MTQ2Yzc3Y2FhMmUxNGM4NDQzOGQ1NTEwNjcxYTZiOTQzZDpjc19hOGY3MmI4MjliZWRkZmVlYThhOTgzOGUwOWMxMDExNGJhNDBmZjhm'
//     ),
//   ));

//   $response = curl_exec($curl);

//   curl_close($curl);
//   $response =  json_decode($response);
//   if (!empty($response)) {
//     $desiredCategory = [];
//     foreach ($response as $product) {
//       // echo "<pre>";
//       // print_r($product->categories);


//       foreach ($product->categories as $category) {
//         if ($category->name === 'BWC') {
//           array_push($desiredCategory, $product->id);
//           break;
//         }
//       }
//     }


//     // Your desired category IDs

//     // Prepare an empty array to store IDs not found in the table
//     $notFoundIds = array();

//     // Prepare the SQL query
//     global $wpdb;
//     $tableName = $wpdb->prefix . 'ferdaratedData'; // Assuming 'wp_4s71kwx95x_' is your WordPress table prefix
//     $query = $wpdb->prepare("SELECT shootpid FROM $tableName WHERE shootpid IN (%s)", implode(',', $desiredCategory));

//     // Execute the query
//     $results = $wpdb->get_results($query);

//     // Check if any rows are returned
//     if ($results) {
//       // Iterate through the rows
//       foreach ($results as $result) {
//         // Remove found ID from the desired category array
//         $key = array_search($result->shootpid, $desiredCategory);
//         if ($key !== false) {
//           unset($desiredCategory[$key]);
//         }
//       }
//       // IDs not found in the table
//       $notFoundIds = $desiredCategory;
//     } else {
//       // If no rows are returned, all IDs are not found in the table
//       $notFoundIds = $desiredCategory;
//     }

//     // Output the result
//     // echo "IDs found in the table: " . implode(',', array_diff($desiredCategory, $notFoundIds)) . "<br>";
//     // echo "IDs not found in the table: " . implode(',', $notFoundIds);
//     if (!empty($notFoundIds)) {
//       foreach ($notFoundIds as $id) {
//         $curl = curl_init();

//         curl_setopt_array($curl, array(
//           CURLOPT_URL => "https://shootinschool.spericorn.com/wp-json/wc/v3/products/$id",
//           CURLOPT_RETURNTRANSFER => true,
//           CURLOPT_ENCODING => '',
//           CURLOPT_MAXREDIRS => 10,
//           CURLOPT_TIMEOUT => 0,
//           CURLOPT_FOLLOWLOCATION => true,
//           CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//           CURLOPT_CUSTOMREQUEST => 'GET',
//           CURLOPT_HTTPHEADER => array(
//             'Authorization: Basic Y2tfNzQ0ZjQ4MTQ2Yzc3Y2FhMmUxNGM4NDQzOGQ1NTEwNjcxYTZiOTQzZDpjc19hOGY3MmI4MjliZWRkZmVlYThhOTgzOGUwOWMxMDExNGJhNDBmZjhm'
//           ),
//         ));

//         $response = curl_exec($curl);

//         curl_close($curl);
//         // echo $response;
//         // echo "<pre>";  print_r($response);
//         $data = json_decode($response, true);
//         // echo "<pre>";  print_r($data['images'][0]['id']);
//         // die();
//         // Unset the 'id' key if it exists
//         $pid = $data['id'];
//         unset($data['id']);
//         unset($data['images'][0]['id']);


//         // Iterate through the meta_data array to find the _gravity_form_data and change its id
//         foreach ($data['meta_data'] as &$meta) {
//           if ($meta['key'] == '_gravity_form_data') {
//             if ($meta['value']['id'] == 13) {
//               $meta['value']['id'] = "5"; // Change the ID to 5
//               break; // Exit the loop once we've made our change
//             }
//           }
//         }


//         // Encode back to JSON
//         $newJsonResponse = json_encode($data);

//         // Output the modified JSON
//         // echo $newJsonResponse;

//         $curl = curl_init();

//         curl_setopt_array($curl, array(
//           CURLOPT_URL => 'https://bwc.spericorn.com/wp-json/wc/v3/products',
//           CURLOPT_RETURNTRANSFER => true,
//           CURLOPT_ENCODING => '',
//           CURLOPT_MAXREDIRS => 10,
//           CURLOPT_TIMEOUT => 0,
//           CURLOPT_FOLLOWLOCATION => true,
//           CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//           CURLOPT_CUSTOMREQUEST => 'POST',
//           CURLOPT_POSTFIELDS => $newJsonResponse,
//           CURLOPT_HTTPHEADER => array(
//             'Content-Type: application/json',
//             'Authorization: Basic Y2tfZTM2ZGY4ODFhZTg1MTcwYWFhMDUyN2JlY2RkMzc0NjE0ODZlYWY2Mzpjc181MWE2MjYxMThkYWJlMjhjOTRlYWI4YTZlNTU2NDZmNTYzY2FjMTE3'
//           ),
//         ));

//         $response = curl_exec($curl);

//         curl_close($curl);
//         $Newdata = json_decode($response, true);
//         // echo $response;
//         global $wpdb;
//         $tableName = $wpdb->prefix . 'ferdaratedData'; // Assuming 'wp_4s71kwx95x_' is your WordPress table prefix
//         $wpdb->insert(
//           $tableName,
//           array(
//             'shootpid' => $id,
//             'bwcpid' => $Newdata['id'],
//           )
//         );
//       }
//     }
//   }
// }


add_action('woocommerce_payment_complete', 'my_custom_webhook_after_checkout');

// function my_custom_webhook_after_checkout($order_id)
// {
//   error_log("Function started for Order ID: $order_id");
//   $order = wc_get_order($order_id);
//   if (in_array($order->get_status(), array('completed', 'processing'))) {
//     session_start();
//     $uid = $_SESSION['uid'];
//     $curl = curl_init();

//     // curl_setopt_array($curl, array(
//     //   CURLOPT_URL => WP_HOME.'/wp-json/wc/v3/orders/$order_id',
//     //   CURLOPT_RETURNTRANSFER => true,
//     //   CURLOPT_ENCODING => '',
//     //   CURLOPT_MAXREDIRS => 10,
//     //   CURLOPT_TIMEOUT => 0,
//     //   CURLOPT_FOLLOWLOCATION => true,
//     //   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//     //   CURLOPT_CUSTOMREQUEST => 'GET',
//     //   CURLOPT_HTTPHEADER => array(
//     //     'Authorization: Basic Y2tfMjRkM2Q5YjBjNTNiMDY3MzQ2YTg4NTRiNjU3NGY3MjRjNDQ3NWQ0MDpjc19hNTY1ZmJmNTdjZjhlYjNjYzIwOTViYjdkNGMyNzE4MGE1MzNiNTIw'
//     //   ),
//     // ));

//     curl_setopt_array($curl, array(
//       CURLOPT_URL => WP_HOME."/wp-json/wc/v3/orders/$order_id",
//       CURLOPT_RETURNTRANSFER => true,
//       CURLOPT_ENCODING => '',
//       CURLOPT_MAXREDIRS => 10,
//       CURLOPT_TIMEOUT => 0,
//       CURLOPT_FOLLOWLOCATION => true,
//       CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//       CURLOPT_CUSTOMREQUEST => 'GET',
//       CURLOPT_HTTPHEADER => array(
//         'Authorization: Basic Y2tfZTM2ZGY4ODFhZTg1MTcwYWFhMDUyN2JlY2RkMzc0NjE0ODZlYWY2Mzpjc181MWE2MjYxMThkYWJlMjhjOTRlYWI4YTZlNTU2NDZmNTYzY2FjMTE3'
//       ),
//     ));

//     $response = curl_exec($curl);

//     curl_close($curl);

//     // $response = json_encode($response);
//     // $json = preg_replace('/[[:^print:]]/', '', $response);
//     error_log("****before decode***:".$uid);
//     $response = json_decode($response);
//      error_log("****decode***:".print_r($response, true));
//      die();
//     // error_log("****decode***:".$response);
//     if ($response !== null) {
//       $response->customer_id = $uid;
//       // $response->id = $new_id; #based on the data to be set
//       unset($response->id); #based on the data to be set
//       $all_line_items = $response->line_items;
//       $response->line_items = [];
//       // unset($response->line_items);
//       foreach ($all_line_items as $key => $line_items) {
//         unset($line_items->id);
//         unset($line_items->image);
//         unset($line_items->parent_name);
//         if ($line_items->product_id == 1723) {
//           $line_items->product_id = 9939;
//         }elseif ($line_items->product_id == 1724) {
//           $line_items->product_id = 9940;
//         }elseif ($line_items->product_id == 1725) {
//           $line_items->product_id = 9941;
//         }elseif ($line_items->product_id == 1726) {
//           $line_items->product_id = 9942;
//         }elseif ($line_items->product_id == 1727) {
//           $line_items->product_id = 9943;
//         }elseif ($line_items->product_id == 1728) {
//           $line_items->product_id = 9944;
//         }
//         foreach ($line_items->meta_data as $linekey => $metadata) {
//           unset($metadata->display_value);
//           unset($metadata->value->_gravity_form_linked_entry_id);
//           if ($line_items->product_id == 9939) {
//             $metadata->value->_gravity_form_lead->form_id = 64;
//           }elseif ($line_items->product_id == 9940) {
//             $metadata->value->_gravity_form_lead->form_id = 65;
//           }elseif ($line_items->product_id == 9941) {
//             $metadata->value->_gravity_form_lead->form_id = 66;
//           }elseif ($line_items->product_id == 9942) {
//             $metadata->value->_gravity_form_lead->form_id = 67;
//           }elseif ($line_items->product_id == 9943) {
//             $metadata->value->_gravity_form_lead->form_id = 68;
//           }elseif ($line_items->product_id == 9944) {
//             $metadata->value->_gravity_form_lead->form_id = 69;
//           }
//           $line_items->meta_data[$linekey] = $metadata;
//         }


//         $response->line_items[$key] = $line_items;
//       }

//       $all_fee_lines = $response->fee_lines;
//       $response->fee_lines = [];
//       // unset($response->line_items);
//       foreach ($all_fee_lines as $key => $fee_lines) {
//         unset($fee_lines->id);
//         $response->fee_lines[$key] = $fee_lines;
//       }



//       // error_log("***wwwwwwww****:".json_encode($response));


//       $client = new Client();
//       $headers = [
//         'Content-Type' => 'application/json',
//         'Accept' => '*/*',
//         'Authorization' => 'Basic Y2tfMTFlOTgzMjdiMjg0YTFhNThkNWZiNmRkNTcwZTBiNjczZDJmOGUzNTpjc183NmVlNmIxNDA4NGU4YzI1YWY5MzkyNjk0OTUwNTRjN2NhNGVjNjc2',
//         'Cookie' => 'PHPSESSID=q4g1t78eti2k2j9oipqbh3rpip'
//       ];
//       $body = json_encode($response);

//       $url = BWC_API_LOGIN_ENDPOINT.'/wp-json/wc/v3/orders';
//       $client->postAsync($url, [
//         'headers' => $headers,
//         'body' => $body,
//       ])->then(
//         function ($response) {
//           global $wpdb;
//           $apiurl =  'https://shootin-stage.spericorn.com';//BWC_API_LOGIN_ENDPOINT;
//           $data = json_decode($response->getBody(), true); // Decode response as associative array

//           // Check if the response contains the expected data
//           if (isset($data['id'])) {
//             $orderID = $data['id'];
//             $table_name = "wp_4s71kwx95x_ferdaratedData";

//             $dataToInsert = array(
//               'bwcpid' => 1,
//               'shootpid' => 2,
//               'bwcgfid' => 3,
//               'shootgfid' => $orderID,
//               'test' => 'orderID'
//             );

//             // // Insert data into database
//             // $wpdb->insert($table_name, $dataToInsert);
//             $curl = curl_init();

//             curl_setopt_array($curl, array(
//               CURLOPT_URL => "$apiurl/wp-json/bwc-api/v1/BwcOrderCreate?order_id=$orderID",
//               CURLOPT_RETURNTRANSFER => true,
//               CURLOPT_ENCODING => '',
//               CURLOPT_MAXREDIRS => 10,
//               CURLOPT_TIMEOUT => 0,
//               CURLOPT_FOLLOWLOCATION => true,
//               CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//               CURLOPT_CUSTOMREQUEST => 'GET',

//             ));

//             $response = curl_exec($curl);

//             curl_close($curl);
//           }
//         },
//         function (Exception $e) {
//           // Error callback
//           echo 'Error: ' . $e->getMessage();
//         }
//       )->wait(); // Wait for the promise to resolve



//       // You can access other fields similarly
//     } else {
//       echo "Failed to decode JSON\n";
//     }
//   }
// }

function my_custom_webhook_after_checkout($order_id)
{
    error_log("Function started for Order ID: $order_id");
    $order = wc_get_order($order_id);
    $stripe_customer_id = $order->get_meta('_stripe_customer_id', true); // Fetch Stripe customer ID
    error_log("Stripe Customer ID: $stripe_customer_id");
    // Log the order status
    $order_status = $order->get_status();
    error_log("Order Status: $order_status");

    if (in_array($order_status, array('completed', 'processing'))) {
        session_start();
        $uid = $_SESSION['uid'];
        error_log("User ID from session: $uid");

        $curl = curl_init();

        // Log the API request
        error_log("Initiating CURL request to fetch order data from WC API");

        curl_setopt_array($curl, array(
            CURLOPT_URL => WP_HOME."/wp-json/wc/v3/orders/$order_id",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
              'Authorization: Basic Y2tfMjRkM2Q5YjBjNTNiMDY3MzQ2YTg4NTRiNjU3NGY3MjRjNDQ3NWQ0MDpjc19hNTY1ZmJmNTdjZjhlYjNjYzIwOTViYjdkNGMyNzE4MGE1MzNiNTIw'
            ),
        ));
// 'Authorization: Basic Y2tfZTM2ZGY4ODFhZTg1MTcwYWFhMDUyN2JlY2RkMzc0NjE0ODZlYWY2Mzpjc181MWE2MjYxMThkYWJlMjhjOTRlYWI4YTZlNTU2NDZmNTYzY2FjMTE3'
        $response = curl_exec($curl);
        if ($response === false) {
            error_log("CURL error: " . curl_error($curl));
        }
        curl_close($curl);

        error_log("Received response: $response");

        $response = json_decode($response);
        error_log("Decoded response: " . print_r($response, true));

        if ($response !== null) {

            // $response->order_id = $order_id;
            $response->stripe_customer_id = $stripe_customer_id;
            $response->customer_id = $uid;
            unset($response->id);
            
            // Log the processed line items
            $all_line_items = $response->line_items;
            $response->line_items = [];
            foreach ($all_line_items as $key => $line_items) {
                error_log("Processing line item ID: " . $line_items->product_id);

                unset($line_items->id);
                unset($line_items->image);
                unset($line_items->parent_name);

                // Modify product IDs
                $original_product_id = $line_items->product_id;
                if ($line_items->product_id == 1723) {
                  $line_items->product_id = 9939;
                }elseif ($line_items->product_id == 1724) {
                  $line_items->product_id = 9940;
                }elseif ($line_items->product_id == 1725) {
                  $line_items->product_id = 9941;
                }elseif ($line_items->product_id == 1726) {
                  $line_items->product_id = 9942;
                }elseif ($line_items->product_id == 1727) {
                  $line_items->product_id = 9943;
                }elseif ($line_items->product_id == 1728) {
                  $line_items->product_id = 9944;
                }
                // Continue for all other product IDs...

                error_log("Updated product ID from $original_product_id to " . $line_items->product_id);

                foreach ($line_items->meta_data as $linekey => $metadata) {
                  // Unset unnecessary values
                  unset($metadata->display_value);
                  unset($metadata->value->_gravity_form_linked_entry_id);
                  //if (is_object($metadata->value) && property_exists($metadata->value, '_gravity_form_lead')) {
                      // Ensure _gravity_form_lead is an object before accessing its properties
                      if (is_object($metadata->value->_gravity_form_lead)) {
                          if ($line_items->product_id == 9939) {
                              $metadata->value->_gravity_form_lead->form_id = 64;
                          } elseif ($line_items->product_id == 9940) {
                              $metadata->value->_gravity_form_lead->form_id = 65;
                          } elseif ($line_items->product_id == 9941) {
                              $metadata->value->_gravity_form_lead->form_id = 66;
                          } elseif ($line_items->product_id == 9942) {
                              $metadata->value->_gravity_form_lead->form_id = 67;
                          } elseif ($line_items->product_id == 9943) {
                              $metadata->value->_gravity_form_lead->form_id = 68;
                          } elseif ($line_items->product_id == 9944) {
                              $metadata->value->_gravity_form_lead->form_id = 69;
                          }
                      } else {
                          error_log('Error: _gravity_form_lead is not an object for metadata value.');
                      }
                //   } else {
                //       error_log('Error: metadata->value is not an object or does not have _gravity_form_lead.');
                //   }
              
                  // Reassign the updated metadata back to meta_data array
                  $line_items->meta_data[$linekey] = $metadata;
              }

                $response->line_items[$key] = $line_items;
            }

            // Log the fee lines
            $all_fee_lines = $response->fee_lines;
            $response->fee_lines = [];
            foreach ($all_fee_lines as $key => $fee_lines) {
                unset($fee_lines->id);
                $response->fee_lines[$key] = $fee_lines;
            }

            // Log the modified response
            error_log("Modified response: " . json_encode($response));
            
            // API client for the second request
            $client = new Client();
            $consumerKey = 'ck_67c94f9c38eb9f6b0317afdc5c136c5e8169ba98'; // Your consumer key
            $consumerSecret = 'cs_0db4e1ae741ec1e172b2d9c93c3e2be90380c121'; // Your consumer secret
            $url = BWC_API_LOGIN_ENDPOINT.'/wp-json/wc/v3/orders';

            $auth = base64_encode("$consumerKey:$consumerSecret");
            $headers = [
                'Content-Type' => 'application/json',
                'Accept' => '*/*',
                'Authorization' => 'Basic ' . $auth, // Use dynamically generated Basic Auth
            ];

            // Optional: If you are not sending a request body, set it to an empty array
            // $response = $client->get($url, [
            //     'headers' => $headers
            // ]);

            // // Decode and print the response
            // $responseBody = $response->getBody();
            // $data = json_decode($responseBody, true);
           //error_log("newwwwwww Response: " . print_r($data, true));


            $body = json_encode($response);

            $decoded_response = json_decode($body, true);
            // Append or modify the necessary fields
            $decoded_response['stripe_cus_id'] = isset($response->stripe_customer_id) ? $response->stripe_customer_id : '';
            $decoded_response['order_id'] = isset($response->order_id) ? $response->order_id : '';
            // Re-encode the modified array back into JSON
            $body = json_encode($decoded_response);
            //Basic Y2tfMTFlOTgzMjdiMjg0YTFhNThkNWZiNmRkNTcwZTBiNjczZDJmOGUzNTpjc183NmVlNmIxNDA4NGU4YzI1YWY5MzkyNjk0OTUwNTRjN2NhNGVjNjc2
            // Log the API call to the BWC endpoint
            error_log("Making API request to BWC API: " . BWC_API_LOGIN_ENDPOINT . '/wp-json/wc/v3/orders');
            error_log("Request body: " . $body);

            $url = BWC_API_LOGIN_ENDPOINT.'/wp-json/wc/v3/orders';
           
            // $order_id=$response->order_id;
            $stripe_customer_id = $response->stripe_customer_id;
            $client->postAsync($url, [
                'headers' => $headers,
                'body' => $body,
            ])->then(
                function ($response) {
                    global $wpdb;
                    $apiurl =  BWC_API_LOGIN_ENDPOINT; // BWC API URL
                    $data = json_decode($response->getBody(), true); // Decode response

                    // Log the BWC API response
                    //error_log("Body: " . print_r($body, true));
                    error_log("BWC API response: " . print_r($data, true));
                   
                    $stripeCustomerId = $response->stripe_customer_id;
                    error_log("Stripe Customer ID passed to callback: " . $stripeCustomerId);
                    if (isset($data['id'])) {
                        error_log("Order ID" . $data['id']);
                    } else {
                        error_log("Order ID not found in the response.");
                        
                    }

                    // Check if the response contains the expected data
                    if (isset($data['id'])) {
                        $orderID = $data['id'];
                        $table_name = "wp_4s71kwx95x_ferdaratedData";

                        $dataToInsert = array(
                            'bwcpid' => 1,
                            'shootpid' => 2,
                            'bwcgfid' => 3,
                            'shootgfid' => $orderID,
                            'test' => 'orderID'
                        );

                        // Log the data to insert into the database
                        error_log("Inserting data into database: " . print_r($data, true));

                        
                        foreach ($data['meta_data'] as $meta_item) {
                            if ($meta_item['key'] === '_stripe_customer_id') {
                                $stripe_customer_id = $meta_item['value']; // Assign the value of _stripe_customer_id
                                break; // Exit the loop once we find the value
                            }
                        }
                        // $order_id=$order_id;
                        // Insert data into database (currently commented out)
                        // $wpdb->insert($table_name, $dataToInsert);
                        error_log("stripe_customer_id:  $stripe_customer_id");
                        error_log("bwc_oder_id: $order_id");
                        $curl = curl_init();
                        curl_setopt_array($curl, array(
                            CURLOPT_URL => "$apiurl/wp-json/bwc-api/v1/BwcOrderCreate?order_id=$orderID&stripe_customer_id=$stripe_customer_id&bwc_oder_id=$order_id",
                            CURLOPT_RETURNTRANSFER => true,
                            CURLOPT_ENCODING => '',
                            CURLOPT_MAXREDIRS => 10,
                            CURLOPT_TIMEOUT => 0,
                            CURLOPT_FOLLOWLOCATION => true,
                            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                            CURLOPT_CUSTOMREQUEST => 'GET',
                        ));

                        $response = curl_exec($curl);
                        curl_close($curl);

                        // Log the final curl response
                        error_log("Final BWC API response: $response");
                    }
                },
                function (Exception $e) {
                    // Error callback
                    error_log("Error in API request: " . $e->getMessage());
                }
            )->wait(); // Wait for the promise to resolve
        } else {
            error_log("Failed to decode JSON response");
        }
    }
}
add_action('woocommerce_order_status_completed', 'my_custom_webhook_after_checkout');



// add_action('woocommerce_new_order', 'bwc_new_order');
// function bwc_new_order($order_id)
// {


//   $the_order = wc_get_order($order_id);
//   echo "<pre>";
//   print_r($the_order);
//   die();
//   global $wpdb;

//   $table_name = $wpdb->prefix . 'ferdaratedData';

//   // Prepare the data to be inserted
//   $data = array(
//     'bwcpid' => 1,
//     'shootpid' => 2,
//     'bwcgfid' => 3,
//     'shootgfid' => 5,
//     'test' => 'before order'
//   );

//   // Insert the data into the custom table
//   $wpdb->insert($table_name, $data);
// }

// add_filter('woocommerce_checkout_create_order', 'insert_custom_data_before_order_creation');

// function insert_custom_data_before_order_creation($order) {
//     global $wpdb;

//     $table_name = $wpdb->prefix . 'ferdaratedData';

//     // Prepare the data to be inserted
//     $data = array(
//         'bwcpid' => 1,
//         'shootpid' =>2,
//         'bwcgfid' => 3,
//         'shootgfid' => 5,
//         'test' => 'before order'
//     );

//     // Insert the data into the custom table
//     $wpdb->insert($table_name, $data);
// }



add_action('woocommerce_before_checkout_form', 'custom_intermediate_page');

function custom_intermediate_page()
{
  // Check if it's the checkout page
  if (is_checkout()) {
    session_start();
    if (!isset($_SESSION['uid'])) {
      wp_redirect(get_site_url() . "/login");
    }
    // wp_redirect('https://bwc.spericorn.com/login/'); // Change 'your-custom-page' to the slug of your custom page
    // exit;
  }
}


add_filter('woocommerce_cart_needs_payment', '__return_true');

// Define a function to apply discount
function apply_custom_discount() {
  session_start();
  
  $apiurl =  BWC_API_LOGIN_ENDPOINT;
  $uid = $_SESSION['uid'];
  $curl = curl_init();

            curl_setopt_array($curl, array(
              CURLOPT_URL => "$apiurl/wp-json/bwc-api/v1/BwcCheckSelfDirection?customer_id=$uid",
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => '',
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 0,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => 'GET',

            ));

            $response = curl_exec($curl);

            curl_close($curl);

           
  if($response == "1"){

    
    global $woocommerce;

    // Get the cart subtotal
    $subtotal = $woocommerce->cart->subtotal;

    // Calculate discount percentage (for example, 10%)
    $discount_percentage = 100; // Change this to your desired percentage

    // Calculate discount amount
    $discount_amount = $subtotal * ($discount_percentage / 100);

    // Apply discount
    $woocommerce->cart->add_fee( 'Discount', -$discount_amount );

     
  }
   
}

// Hook into WooCommerce to modify the subtotal display
add_filter('woocommerce_cart_subtotal', 'modify_subtotal_display', 10, 3);

function modify_subtotal_display($cart_subtotal, $compound, $cart) {
    // Check if the subtotal is 15000
    $subtotal = $cart->subtotal;
    if ($subtotal == 150000) {
        $cart_subtotal .= ' <span style="color: #dc1414; font-weight: bold;">(FREE)</span>';
    }

    return $cart_subtotal;
}
// Hook the function to apply the discount
add_action( 'woocommerce_cart_calculate_fees', 'apply_custom_discount' );

function add_custom_text_before_payment() {
  // 	session_start();
    
  $apiurl = BWC_API_LOGIN_ENDPOINT;
  $uid = $_SESSION['uid'];
  $curl = curl_init();

            curl_setopt_array($curl, array(
              CURLOPT_URL => "$apiurl/wp-json/bwc-api/v1/BwcCheckoutSelfDirection?customer_id=$uid",
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => '',
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 0,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => 'GET',

            ));

            $response = curl_exec($curl);

            curl_close($curl);
  if($response == "1"){
    echo '<p style="font-size:18px;color:#e74c3c;margin-bottom: 0px;margin-top: 41px;">If you have self direction, we need your card on file only for <br>no-shows or cancellations.</p>';
   
    }
  }
  add_action('woocommerce_review_order_before_payment', 'add_custom_text_before_payment');


    //-------------------------------------Gravity Form-------------------------------
  //-------------------------------------BWC Fit-------------------------------
  add_filter('gform_pre_render_4', 'populate_player_names');
  add_filter('gform_pre_submission_filter_4', 'populate_player_names');
  add_filter('gform_admin_pre_render_4', 'populate_player_names');
  
  function populate_player_names($form) {
      global $wpdb;
      session_start();
    
       $uid = $_SESSION['uid'];
      // Check if the user is logged in
      if ($_SESSION['uid']) {
  
          // Make API call to fetch child names
          $apiurl = BWC_API_LOGIN_ENDPOINT;
          $curl = curl_init();
  
          curl_setopt_array($curl, array(
              CURLOPT_URL => "$apiurl/wp-json/bwc-api/v1/BwcGetformChild?customer_id=$uid",
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => '',
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 0,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => 'GET',
          ));
  
          $response = curl_exec($curl);
          curl_close($curl);
  
          // Decode the API response
          $childs = json_decode($response);
  
          if (!empty($childs->message)) {
              // Populate the player dropdown with child names
              foreach ($form['fields'] as &$field) {
                  if ($field->inputName === 'players') {
                      $choices = array();
  
                      // Add child names as choices
                      foreach ($childs->message as $child) {
                          $fullName = $child->first_name . " " . $child->last_name;
                          $choices[] = array('text' => esc_html($fullName), 'value' => esc_attr($child->id));
                      }
                      $field->choices = $choices;
                      $field->cssClass = 'gf_select';
                  }
  
                  // Hide first name and last name fields if players exist
                  if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                      $field->visibility = 'hidden';
                  }
              }
          } else {
              // No players found, show first name and last name fields
              foreach ($form['fields'] as &$field) {
                  if ($field->inputName === 'players') {
                      $field->visibility = 'hidden'; // Hide the dropdown
                  }
                  if ($field->inputName === 'input_15') {
                    $field->visibility = 'hidden'; // Hide the specific input field
                }
                  
  
                  if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                      $field->visibility = 'visible'; // Show the textboxes
                  }
              }
  
              // Add a message prompting the user to enter child details
              $message_field = array(
                  'type' => 'html',
                  'content' => "<p style='color: red;'>No child data available. Please enter your child's details below.</p>",
              );
  
              // Insert the message field at the top of the form
              array_unshift($form['fields'], GF_Fields::create($message_field));
          }
      } else {
          // If the user is not logged in, hide the player dropdown and show the textboxes
          foreach ($form['fields'] as &$field) {
              if ($field->inputName === 'players') {
                  $field->visibility = 'hidden'; // Hide the dropdown
              }
  
              if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                  $field->visibility = 'visible'; // Show the textboxes
              }
          }
  
          // Show a message to log in
          $message_field = array(
              'type' => 'html',
              'content' => "<p style='color: red;'>Please log in to select your child from the list, or enter your child's details below to add them.</p>",
          );
  
          // Insert the message field at the top of the form
          array_unshift($form['fields'], GF_Fields::create($message_field));
      }
  
      return $form;
  }
  //-------------------------------------Group Bowling-------------------------------
  add_filter('gform_pre_render_3', 'populate_group_bowling');
  add_filter('gform_pre_submission_filter_3', 'populate_group_bowling');
  add_filter('gform_admin_pre_render_3', 'populate_group_bowling');
  
  function populate_group_bowling($form) {
      global $wpdb;
      session_start();
    
       $uid = $_SESSION['uid'];
      // Check if the user is logged in
      if ($_SESSION['uid']) {
  
          // Make API call to fetch child names
          $apiurl = BWC_API_LOGIN_ENDPOINT;
          $curl = curl_init();
  
          curl_setopt_array($curl, array(
              CURLOPT_URL => "$apiurl/wp-json/bwc-api/v1/BwcGetformChild?customer_id=$uid",
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => '',
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 0,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => 'GET',
          ));
  
          $response = curl_exec($curl);
          curl_close($curl);
  
          // Decode the API response
          $childs = json_decode($response);
  
          if (!empty($childs->message)) {
              // Populate the player dropdown with child names
              foreach ($form['fields'] as &$field) {
                  if ($field->inputName === 'players') {
                      $choices = array();
  
                      // Add child names as choices
                      foreach ($childs->message as $child) {
                          $fullName = $child->first_name . " " . $child->last_name;
                          $choices[] = array('text' => esc_html($fullName), 'value' => esc_attr($child->id));
                      }
                      $field->choices = $choices;
                      $field->cssClass = 'gf_select';
                  }
  
                  // Hide first name and last name fields if players exist
                  if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                      $field->visibility = 'hidden';
                  }
              }
          } else {
              // No players found, show first name and last name fields
              foreach ($form['fields'] as &$field) {
                  if ($field->inputName === 'players') {
                      $field->visibility = 'hidden'; // Hide the dropdown
                  }
  
                  if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                      $field->visibility = 'visible'; // Show the textboxes
                  }
              }
  
              // Add a message prompting the user to enter child details
              $message_field = array(
                  'type' => 'html',
                  'content' => "<p style='color: red;'>No child data available. Please enter your child's details below.</p>",
              );
  
              // Insert the message field at the top of the form
              array_unshift($form['fields'], GF_Fields::create($message_field));
          }
      } else {
          // If the user is not logged in, hide the player dropdown and show the textboxes
          foreach ($form['fields'] as &$field) {
              if ($field->inputName === 'players') {
                  $field->visibility = 'hidden'; // Hide the dropdown
              }
  
              if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                  $field->visibility = 'visible'; // Show the textboxes
              }
          }
  
          // Show a message to log in
          $message_field = array(
              'type' => 'html',
              'content' => "<p style='color: red;'>Please log in to select your child from the list, or enter your child's details below to add them.</p>",
          );
  
          // Insert the message field at the top of the form
          array_unshift($form['fields'], GF_Fields::create($message_field));
      }
  
      return $form;
  }

   //-------------------------------------Group Single Sessions-------------------------------
   add_filter('gform_pre_render_1', 'populate_group_single');
   add_filter('gform_pre_submission_filter_1', 'populate_group_single');
   add_filter('gform_admin_pre_render_1', 'populate_group_single');
   
   function populate_group_single($form) {
       global $wpdb;
       session_start();
     
        $uid = $_SESSION['uid'];
       // Check if the user is logged in
       if ($_SESSION['uid']) {
   
           // Make API call to fetch child names
           $apiurl = BWC_API_LOGIN_ENDPOINT;
           $curl = curl_init();
   
           curl_setopt_array($curl, array(
               CURLOPT_URL => "$apiurl/wp-json/bwc-api/v1/BwcGetformChild?customer_id=$uid",
               CURLOPT_RETURNTRANSFER => true,
               CURLOPT_ENCODING => '',
               CURLOPT_MAXREDIRS => 10,
               CURLOPT_TIMEOUT => 0,
               CURLOPT_FOLLOWLOCATION => true,
               CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
               CURLOPT_CUSTOMREQUEST => 'GET',
           ));
   
           $response = curl_exec($curl);
           curl_close($curl);
   
           // Decode the API response
           $childs = json_decode($response);
   
           if (!empty($childs->message)) {
               // Populate the player dropdown with child names
               foreach ($form['fields'] as &$field) {
                   if ($field->inputName === 'players') {
                       $choices = array();
   
                       // Add child names as choices
                       foreach ($childs->message as $child) {
                           $fullName = $child->first_name . " " . $child->last_name;
                           $choices[] = array('text' => esc_html($fullName), 'value' => esc_attr($child->id));
                       }
                       $field->choices = $choices;
                       $field->cssClass = 'gf_select';
                   }
   
                   // Hide first name and last name fields if players exist
                   if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                       $field->visibility = 'hidden';
                   }
               }
           } else {
               // No players found, show first name and last name fields
               foreach ($form['fields'] as &$field) {
                   if ($field->inputName === 'players') {
                       $field->visibility = 'hidden'; // Hide the dropdown
                   }
   
                   if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                       $field->visibility = 'visible'; // Show the textboxes
                   }
               }
   
               // Add a message prompting the user to enter child details
               $message_field = array(
                   'type' => 'html',
                   'content' => "<p style='color: red;'>No child data available. Please enter your child's details below.</p>",
               );
   
               // Insert the message field at the top of the form
               array_unshift($form['fields'], GF_Fields::create($message_field));
           }
       } else {
           // If the user is not logged in, hide the player dropdown and show the textboxes
           foreach ($form['fields'] as &$field) {
               if ($field->inputName === 'players') {
                   $field->visibility = 'hidden'; // Hide the dropdown
               }
   
               if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                   $field->visibility = 'visible'; // Show the textboxes
               }
           }
   
           // Show a message to log in
           $message_field = array(
               'type' => 'html',
               'content' => "<p style='color: red;'>Please log in to select your child from the list, or enter your child's details below to add them.</p>",
           );
   
           // Insert the message field at the top of the form
           array_unshift($form['fields'], GF_Fields::create($message_field));
       }
   
       return $form;
   }
  
      //-------------------------------------In Gym 1-on-1 Session-------------------------------
      add_filter('gform_pre_render_5', 'populate_gym_session');
      add_filter('gform_pre_submission_filter_5', 'populate_gym_session');
      add_filter('gform_admin_pre_render_5', 'populate_gym_session');
      
      function populate_gym_session($form) {
          global $wpdb;
          session_start();
        
           $uid = $_SESSION['uid'];
          // Check if the user is logged in
          if ($_SESSION['uid']) {
      
              // Make API call to fetch child names
              $apiurl = BWC_API_LOGIN_ENDPOINT;
              $curl = curl_init();
      
              curl_setopt_array($curl, array(
                  CURLOPT_URL => "$apiurl/wp-json/bwc-api/v1/BwcGetformChild?customer_id=$uid",
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_ENCODING => '',
                  CURLOPT_MAXREDIRS => 10,
                  CURLOPT_TIMEOUT => 0,
                  CURLOPT_FOLLOWLOCATION => true,
                  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                  CURLOPT_CUSTOMREQUEST => 'GET',
              ));
      
              $response = curl_exec($curl);
              curl_close($curl);
      
              // Decode the API response
              $childs = json_decode($response);
      
              if (!empty($childs->message)) {
                  // Populate the player dropdown with child names
                  foreach ($form['fields'] as &$field) {
                      if ($field->inputName === 'players') {
                          $choices = array();
      
                          // Add child names as choices
                          foreach ($childs->message as $child) {
                              $fullName = $child->first_name . " " . $child->last_name;
                              $choices[] = array('text' => esc_html($fullName), 'value' => esc_attr($child->id));
                          }
                          $field->choices = $choices;
                          $field->cssClass = 'gf_select';
                      }
      
                      // Hide first name and last name fields if players exist
                      if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                          $field->visibility = 'hidden';
                      }
                  }
              } else {
                  // No players found, show first name and last name fields
                  foreach ($form['fields'] as &$field) {
                      if ($field->inputName === 'players') {
                          $field->visibility = 'hidden'; // Hide the dropdown
                      }
      
                      if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                          $field->visibility = 'visible'; // Show the textboxes
                      }
                  }
      
                  // Add a message prompting the user to enter child details
                  $message_field = array(
                      'type' => 'html',
                      'content' => "<p style='color: red;'>No child data available. Please enter your child's details below.</p>",
                  );
      
                  // Insert the message field at the top of the form
                  array_unshift($form['fields'], GF_Fields::create($message_field));
              }
          } else {
              // If the user is not logged in, hide the player dropdown and show the textboxes
              foreach ($form['fields'] as &$field) {
                  if ($field->inputName === 'players') {
                      $field->visibility = 'hidden'; // Hide the dropdown
                  }
      
                  if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                      $field->visibility = 'visible'; // Show the textboxes
                  }
              }
      
              // Show a message to log in
              $message_field = array(
                  'type' => 'html',
                  'content' => "<p style='color: red;'>Please log in to select your child from the list, or enter your child's details below to add them.</p>",
              );
      
              // Insert the message field at the top of the form
              array_unshift($form['fields'], GF_Fields::create($message_field));
          }
      
          return $form;
      }
      //-------------------------------------Specialty Session-------------------------------
      add_filter('gform_pre_render_6', 'populate_specialty_session');
      add_filter('gform_pre_submission_filter_6', 'populate_specialty_session');
      add_filter('gform_admin_pre_render_6', 'populate_specialty_session');
      
      function populate_specialty_session($form) {
          global $wpdb;
          session_start();
        
           $uid = $_SESSION['uid'];
          // Check if the user is logged in
          if ($_SESSION['uid']) {
      
              // Make API call to fetch child names
              $apiurl = BWC_API_LOGIN_ENDPOINT;
              $curl = curl_init();
      
              curl_setopt_array($curl, array(
                  CURLOPT_URL => "$apiurl/wp-json/bwc-api/v1/BwcGetformChild?customer_id=$uid",
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_ENCODING => '',
                  CURLOPT_MAXREDIRS => 10,
                  CURLOPT_TIMEOUT => 0,
                  CURLOPT_FOLLOWLOCATION => true,
                  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                  CURLOPT_CUSTOMREQUEST => 'GET',
              ));
      
              $response = curl_exec($curl);
              curl_close($curl);
      
              // Decode the API response
              $childs = json_decode($response);
      
              if (!empty($childs->message)) {
                  // Populate the player dropdown with child names
                  foreach ($form['fields'] as &$field) {
                      if ($field->inputName === 'players') {
                          $choices = array();
      
                          // Add child names as choices
                          foreach ($childs->message as $child) {
                              $fullName = $child->first_name . " " . $child->last_name;
                              $choices[] = array('text' => esc_html($fullName), 'value' => esc_attr($child->id));
                          }
                          $field->choices = $choices;
                          $field->cssClass = 'gf_select';
                      }
      
                      // Hide first name and last name fields if players exist
                      if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                          $field->visibility = 'hidden';
                      }
                  }
              } else {
                  // No players found, show first name and last name fields
                  foreach ($form['fields'] as &$field) {
                      if ($field->inputName === 'players') {
                          $field->visibility = 'hidden'; // Hide the dropdown
                      }
      
                      if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                          $field->visibility = 'visible'; // Show the textboxes
                      }
                  }
      
                  // Add a message prompting the user to enter child details
                  $message_field = array(
                      'type' => 'html',
                      'content' => "<p style='color: red;'>No child data available. Please enter your child's details below.</p>",
                  );
      
                  // Insert the message field at the top of the form
                  array_unshift($form['fields'], GF_Fields::create($message_field));
              }
          } else {
              // If the user is not logged in, hide the player dropdown and show the textboxes
              foreach ($form['fields'] as &$field) {
                  if ($field->inputName === 'players') {
                      $field->visibility = 'hidden'; // Hide the dropdown
                  }
      
                  if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                      $field->visibility = 'visible'; // Show the textboxes
                  }
              }
      
              // Show a message to log in
              $message_field = array(
                  'type' => 'html',
                  'content' => "<p style='color: red;'>Please log in to select your child from the list, or enter your child's details below to add them.</p>",
              );
      
              // Insert the message field at the top of the form
              array_unshift($form['fields'], GF_Fields::create($message_field));
          }
      
          return $form;
      }
      //-------------------------------------Group Unlimited-------------------------------
      add_filter('gform_pre_render_2', 'populate_group_unlimited');
      add_filter('gform_pre_submission_filter_2', 'populate_group_unlimited');
      add_filter('gform_admin_pre_render_2', 'populate_group_unlimited');
      
      function populate_group_unlimited($form) {
          global $wpdb;
          session_start();
        
          $uid = $_SESSION['uid'];
          // Check if the user is logged in
          if ($_SESSION['uid']) {
      
              // Make API call to fetch child names
              $apiurl = BWC_API_LOGIN_ENDPOINT;
              $curl = curl_init();
      
              curl_setopt_array($curl, array(
                  CURLOPT_URL => "$apiurl/wp-json/bwc-api/v1/BwcGetUnlimitedChild?customer_id=$uid",
                  CURLOPT_RETURNTRANSFER => true,
                  CURLOPT_ENCODING => '',
                  CURLOPT_MAXREDIRS => 10,
                  CURLOPT_TIMEOUT => 0,
                  CURLOPT_FOLLOWLOCATION => true,
                  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                  CURLOPT_CUSTOMREQUEST => 'GET',
              ));
      
              $response = curl_exec($curl);
              curl_close($curl);
      
              // Decode the API response
              $childs = json_decode($response);
      
              if (!empty($childs->message)) {
                  // Populate the player dropdown with child names
                  foreach ($form['fields'] as &$field) {
                      if ($field->inputName === 'players') {
                          $choices = array();
      
                          // Add child names as choices
                          foreach ($childs->message as $child) {
                              $fullName = $child->first_name . " " . $child->last_name;
                              $choices[] = array('text' => esc_html($fullName), 'value' => esc_attr($child->id));
                          }
                          $field->choices = $choices;
                          $field->cssClass = 'gf_select';
                      }
      
                      // Hide first name and last name fields if players exist
                      if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                          $field->visibility = 'hidden';
                      }
                  }
              } else {
                  // No players found, show first name and last name fields
                  foreach ($form['fields'] as &$field) {
                      if ($field->inputName === 'players') {
                          $field->visibility = 'visible'; // Hide the dropdown
                      }
      
                      if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                          $field->visibility = 'visible'; // Show the textboxes
                      }
                  }
      
                  // Add a message prompting the user to enter child details
                  $message_field = array(
                      'type' => 'html',
                      'content' => "<p style='color: red;'>No child data available. Please enter your child's details below.</p>",
                  );
      
                  // Insert the message field at the top of the form
                  array_unshift($form['fields'], GF_Fields::create($message_field));
              }
          } else {
              // If the user is not logged in, hide the player dropdown and show the textboxes
              foreach ($form['fields'] as &$field) {
                  if ($field->inputName === 'players') {
                      $field->visibility = 'hidden'; // Hide the dropdown
                  }
      
                  if ($field->inputName === 'firstname' || $field->inputName === 'lastname') {
                      $field->visibility = 'visible'; // Show the textboxes
                  }
              }
      
              // Show a message to log in
              $message_field = array(
                  'type' => 'html',
                  'content' => "<p style='color: red;'>Please log in to select your child from the list, or enter your child's details below to add them.</p>",
              );
      
              // Insert the message field at the top of the form
              array_unshift($form['fields'], GF_Fields::create($message_field));
          }
      
          return $form;
      }

//------------------------------------Script--------------------------
add_action('wp_footer', 'gf_radio_button_dropdown_script');
function gf_radio_button_dropdown_script() {
	 $uid = $_SESSION['uid'];
      // Check if the user is logged in
      if ($_SESSION['uid']) {

    ?>
   
   <script>
    
    jQuery(document).ready(function($) {
	//-------------------------BWC Fit----------------------------------------
		$('input[name="input_15"]').closest('.gfield_radio').addClass('radio-inline');
        var radioFieldId = 'input_15';  
        var dropdownFieldId = '#input_4_16';   
        var firstInput = '#input_4_8_3';  
        var lastInput = '#input_4_8_6';   
		var radioField = '#choice_4_15_0';
		var optionInput = '#input_4_1';
		var gradeInput = '#input_4_5';
		var jerseyInput = '#input_4_7';
		var schoolInput = '#input_4_12';
		var dobInput = '#input_4_14';
        

        // Check if the radio button is selected
       
		$(dropdownFieldId).prepend('<option value="0">Select an option</option>');
		$(dropdownFieldId).find('option[value=""]').remove();
		$(dropdownFieldId).find('option[value="No players found"]').remove();
		$(dropdownFieldId).val('0');    
		$(radioField).closest('.gfield').hide();
        $(dropdownFieldId).closest('.gfield').hide();
        $(firstInput).closest('.gfield').hide();
        $(lastInput).closest('.gfield').hide();
		$(optionInput).change(function() {
            var radioButton4 = document.querySelector('input[name="input_15"][value="Choose a Child"]');
            var radioButton42 = document.querySelector('input[name="input_15"][value="Create a Child"]');
            var selectElement = document.getElementById('input_4_16');
            var optionCount = selectElement.options.length;
            if (optionCount<=1) {
                    var element1 = document.getElementById('field_4_16');
                    element1.style.position = 'absolute';
                    radioButton4.checked = false; 
                    radioButton42.checked = true;
                    $('#field_4_8').show();
                    $('#choice_4_15_1').prop('disabled', true);
                    $(firstInput).attr('required', true); 
				    $(lastInput).attr('required', true); 
            } 
			$(radioField).closest('.gfield').show();
			$(radioField).attr('required', true); 
			$(gradeInput).attr('required', true); 
			$(schoolInput).attr('required', true); 
			$(jerseyInput).attr('required', true);
			
			if ($(dropdownFieldId).val() === "0") {
				$(dropdownFieldId).attr('required', true);
			}
			$(dobInput).attr('required', true);
			$(dropdownFieldId).closest('.gfield').show(); 
		
        $('input[name="input_15"]').change(function() {
            var selectedValue = $('input[name="input_15"]:checked').val();
            if (selectedValue == 'Create a Child') {
                $(dropdownFieldId).closest('.gfield').hide(); 
                $(firstInput).closest('.gfield').show(); 
                $(lastInput).closest('.gfield').show();
				$(firstInput).attr('required', true); 
				$(lastInput).attr('required', true); 
            } 
            else {
                $(dropdownFieldId).closest('.gfield').show(); 
                $(firstInput).closest('.gfield').hide(); 
                $(lastInput).closest('.gfield').hide(); 
				$(dropdownFieldId).attr('required', true);
				$(firstInput).attr('required', false); 
				$(lastInput).attr('required', false); 
            }
        });
		$('#gform_submit_button_4').click(function(event) {
			var selectedValue = $('input[name="input_15"]:checked').val();
            if (selectedValue == 'Choose a Child') {
			var selectedValue = jQuery('#input_4_16').val();
			if (selectedValue === "0") {
				toastr.error("Please select a Player name.");
				// alert("Please select a Player name.");
                event.preventDefault(); 

			}
		}
		});
	});
 // $('input[name="input_15"]:checked').trigger('change');
  //-------------------------Group Bowling----------------------------------------
 // $('input[name="input_15"]').closest('.gfield_radio').addClass('radio-inline');
        var radioFieldId3 = 'input_15';  
        var dropdownFieldId3 = '#input_3_16';   
        var firstInput3 = '#input_3_8_3';  
        var lastInput3 = '#input_3_8_6';   
		var radioField3 = '#choice_3_15_0';
		var optionInput3 = '#input_3_1';
		var gradeInput3 = '#input_3_5';
		var jerseyInput3 = '#input_3_7';
		var schoolInput3 = '#input_3_12';
		var dobInput3 = '#input_3_14';
		$(dropdownFieldId3).prepend('<option value="0">Select an option</option>');
		$(dropdownFieldId3).find('option[value=""]').remove();
		$(dropdownFieldId3).find('option[value="No players found"]').remove();
		$(dropdownFieldId3).val('0');    
		$(radioField3).closest('.gfield').hide();
    $(dropdownFieldId3).closest('.gfield').hide();
    $(firstInput3).closest('.gfield').hide();
    $(lastInput3).closest('.gfield').hide();
		$(optionInput3).change(function() {
            var radioButton3 = document.querySelector('input[name="input_15"][value="Choose a Child"]');
            var radioButton32 = document.querySelector('input[name="input_15"][value="Create a Child"]');
            var selectElement3 = document.getElementById('input_3_16');
            var optionCount3 = selectElement3.options.length;
            console.log(optionCount3);
             if (optionCount3<=1) {
                    var element3 = document.getElementById('field_3_16');
                    element3.style.position = 'absolute';
                    radioButton3.checked = false; 
                    radioButton32.checked = true;
                    $('#field_3_8').show();
                    $('#choice_3_15_1').prop('disabled', true);
                    $(firstInput3).attr('required', true); 
				    $(lastInput3).attr('required', true); 
             } 

			$(radioField3).closest('.gfield').show();
			$(radioField3).attr('required', true); 
			$(gradeInput3).attr('required', true); 
			$(schoolInput3).attr('required', true); 
			$(jerseyInput3).attr('required', true);
			
			if ($(dropdownFieldId3).val() === "0") {
				$(dropdownFieldId3).attr('required', true);
			}
			$(dobInput3).attr('required', true);
			$(dropdownFieldId3).closest('.gfield').show(); 
		
        $('input[name="input_15"]').change(function() {
            var selectedValue3 = $('input[name="input_15"]:checked').val();
            if (selectedValue3 == 'Create a Child') {
                $(dropdownFieldId3).closest('.gfield').hide(); 
                $(firstInput3).closest('.gfield').show(); 
                $(lastInput3).closest('.gfield').show();
				$(firstInput3).attr('required', true); 
				$(lastInput3).attr('required', true); 
            } 
            else {
                $(dropdownFieldId3).closest('.gfield').show(); 
                $(firstInput3).closest('.gfield').hide(); 
                $(lastInput3).closest('.gfield').hide(); 
				$(dropdownFieldId3).attr('required', true);
				$(firstInput3).attr('required', false); 
				$(lastInput3).attr('required', false); 
            }
        });
		$('#gform_submit_button_3').click(function(event) {
			var selectedValue3 = $('input[name="input_15"]:checked').val();
            if (selectedValue3 == 'Choose a Child') {
			var selectedValue3 = jQuery('#input_3_16').val();
			if (selectedValue3 === "0") {
				toastr.error("Please select a Player name.");
				// alert("Please select a Player name.");
        event.preventDefault(); 

			}
		}
		});
	});
//  // $('input[name="input_15"]:checked').trigger('change');
//   //-------------------------Group Single Sessions----------------------------------------
 // $('input[name="input_15"]').closest('.gfield_radio').addClass('radio-inline');
        var radioFieldId1 = 'input_15';  
        var dropdownFieldId1 = '#input_1_16';   
        var firstInput1 = '#input_1_8_3';  
        var lastInput1 = '#input_1_8_6';   
		var radioField1 = '#choice_1_15_0';
		var optionInput1 = '#input_1_1';
		var gradeInput1 = '#input_1_5';
		var jerseyInput1 = '#input_1_7';
		var schoolInput1 = '#input_1_12';
		var dobInput1 = '#input_1_14';
		$(dropdownFieldId1).prepend('<option value="0">Select an option</option>');
		$(dropdownFieldId1).find('option[value=""]').remove();
		$(dropdownFieldId1).find('option[value="No players found"]').remove();
		$(dropdownFieldId1).val('0');    
		$(radioField1).closest('.gfield').hide();
        $(dropdownFieldId1).closest('.gfield').hide();
        $(firstInput1).closest('.gfield').hide();
        $(lastInput1).closest('.gfield').hide();
		$(optionInput1).change(function() {
            var radioButton1 = document.querySelector('input[name="input_15"][value="Choose a Child"]');
            var radioButton12 = document.querySelector('input[name="input_15"][value="Create a Child"]');
            var selectElement1 = document.getElementById('input_1_16');
            var optionCount1 = selectElement1.options.length;
            if (optionCount1<=1) {
                    var element1 = document.getElementById('field_1_16');
                    element1.style.position = 'absolute';
                    radioButton1.checked = false; 
                    radioButton12.checked = true;
                    $('#field_1_8').show();
                    $('#choice_1_15_1').prop('disabled', true);
                    $(firstInput1).attr('required', true); 
				    $(lastInput1).attr('required', true); 
            } 
			$(radioField1).closest('.gfield').show();
			$(radioField1).attr('required', true); 
			$(gradeInput1).attr('required', true); 
			$(schoolInput1).attr('required', true); 
			$(jerseyInput1).attr('required', true);
			
			if ($(dropdownFieldId1).val() === "0") {
				$(dropdownFieldId1).attr('required', true);
			}
			$(dobInput1).attr('required', true);
			$(dropdownFieldId1).closest('.gfield').show(); 
		
        $('input[name="input_15"]').change(function() {
            var selectedValue1 = $('input[name="input_15"]:checked').val();
            if (selectedValue1 == 'Create a Child') {
                $(dropdownFieldId1).closest('.gfield').hide(); 
                $(firstInput1).closest('.gfield').show(); 
                $(lastInput1).closest('.gfield').show();
				$(firstInput1).attr('required', true); 
				$(lastInput1).attr('required', true); 
            } 
            else {
                $(dropdownFieldId1).closest('.gfield').show(); 
                $(firstInput1).closest('.gfield').hide(); 
                $(lastInput1).closest('.gfield').hide(); 
				$(dropdownFieldId1).attr('required', true);
				$(firstInput1).attr('required', false); 
				$(lastInput1).attr('required', false); 
            }
        });
		$('#gform_submit_button_1').click(function(event) {
			var selectedValue1 = $('input[name="input_15"]:checked').val();
            if (selectedValue1 == 'Choose a Child') {
			var selectedValue1 = jQuery('#input_1_16').val();
			if (selectedValue1 === "0") {
				toastr.error("Please select a Player name.");
				// alert("Please select a Player name.");
        event.preventDefault(); 

			}
		}
		});
	});
//  // $('input[name="input_15"]:checked').trigger('change');
//   //-------------------------In Gym 1-on-1 Session----------------------------------------
 // $('input[name="input_15"]').closest('.gfield_radio').addClass('radio-inline');
        var radioFieldId5 = 'input_15';  
        var dropdownFieldId5 = '#input_5_16';   
        var firstInput5 = '#input_5_8_3';  
        var lastInput5 = '#input_5_8_6';   
		var radioField5 = '#choice_5_15_0';
		var optionInput5 = '#input_5_1';
		var gradeInput5 = '#input_5_5';
		var jerseyInput5 = '#input_5_7';
		var schoolInput5 = '#input_5_12';
		var dobInput5 = '#input_5_14';
		$(dropdownFieldId5).prepend('<option value="0">Select an option</option>');
		$(dropdownFieldId5).find('option[value=""]').remove();
		$(dropdownFieldId5).find('option[value="No players found"]').remove();
		$(dropdownFieldId5).val('0');    
		$(radioField5).closest('.gfield').hide();
    $(dropdownFieldId5).closest('.gfield').hide();
    $(firstInput5).closest('.gfield').hide();
    $(lastInput5).closest('.gfield').hide();
		$(optionInput5).change(function() {
            var radioButton5 = document.querySelector('input[name="input_15"][value="Choose a Child"]');
            var radioButton52 = document.querySelector('input[name="input_15"][value="Create a Child"]');
            var selectElement5 = document.getElementById('input_5_16');
            var optionCount5 = selectElement5.options.length;
            if (optionCount5<=1) {
                    var element5 = document.getElementById('field_5_16');
                    element5.style.position = 'absolute';
                    radioButton5.checked = false; 
                    radioButton52.checked = true;
                    $('#field_5_8').show();
                    $('#choice_5_15_1').prop('disabled', true);
                    $(firstInput5).attr('required', true); 
				    $(lastInput5).attr('required', true); 
            } 
			$(radioField5).closest('.gfield').show();
			$(radioField5).attr('required', true); 
			$(gradeInput5).attr('required', true); 
			$(schoolInput5).attr('required', true); 
			$(jerseyInput5).attr('required', true);
			
			if ($(dropdownFieldId5).val() === "0") {
				$(dropdownFieldId5).attr('required', true);
			}
			$(dobInput5).attr('required', true);
			$(dropdownFieldId5).closest('.gfield').show(); 
		
        $('input[name="input_15"]').change(function() {
            var selectedValue5 = $('input[name="input_15"]:checked').val();
            if (selectedValue5 == 'Create a Child') {
                $(dropdownFieldId5).closest('.gfield').hide(); 
                $(firstInput5).closest('.gfield').show(); 
                $(lastInput5).closest('.gfield').show();
				$(firstInput5).attr('required', true); 
				$(lastInput5).attr('required', true); 
            } 
            else {
                $(dropdownFieldId5).closest('.gfield').show(); 
                $(firstInput5).closest('.gfield').hide(); 
                $(lastInput5).closest('.gfield').hide(); 
				$(dropdownFieldId5).attr('required', true);
				$(firstInput5).attr('required', false); 
				$(lastInput5).attr('required', false); 
            }
        });
		$('#gform_submit_button_5').click(function(event) {
			var selectedValue5 = $('input[name="input_15"]:checked').val();
            if (selectedValue5 == 'Choose a Child') {
			var selectedValue5 = jQuery('#input_5_16').val();
			if (selectedValue5 === "0") {
				toastr.error("Please select a Player name.");
				// alert("Please select a Player name.");
        event.preventDefault(); 

			}
		}
		});
	});
  $('input[name="input_15"]:checked').trigger('change');

//    //-------------------------Specialty Session----------------------------------------
 //  $('input[name="input_15"]').closest('.gfield_radio').addClass('radio-inline');
        var radioFieldId6 = 'input_15';  
        var dropdownFieldId6 = '#input_6_16';   
        var firstInput6 = '#input_6_8_3';  
        var lastInput6 = '#input_6_8_6';   
		var radioField6 = '#choice_6_15_0';
		var optionInput6 = '#input_6_1';
		var gradeInput6 = '#input_6_5';
		var jerseyInput6 = '#input_6_7';
		var schoolInput6 = '#input_6_12';
		var dobInput6 = '#input_6_14';
		$(dropdownFieldId6).prepend('<option value="0">Select an option</option>');
		$(dropdownFieldId6).find('option[value=""]').remove();
		$(dropdownFieldId6).find('option[value="No players found"]').remove();
		$(dropdownFieldId6).val('0');    
		$(radioField6).closest('.gfield').hide();
    $(dropdownFieldId6).closest('.gfield').hide();
    $(firstInput6).closest('.gfield').hide();
    $(lastInput6).closest('.gfield').hide();
		$(optionInput6).change(function() {
            var radioButton6 = document.querySelector('input[name="input_15"][value="Choose a Child"]');
            var radioButton62 = document.querySelector('input[name="input_15"][value="Create a Child"]');
            var selectElement6 = document.getElementById('input_6_16');
            var optionCount6 = selectElement6.options.length;
            if (optionCount6<=1) {
                    var element6 = document.getElementById('field_6_16');
                    element6.style.position = 'absolute';
                    radioButton6.checked = false; 
                    radioButton62.checked = true;
                    $('#field_6_8').show();
                    $('#choice_6_15_1').prop('disabled', true);
                    $(firstInput6).attr('required', true); 
				    $(lastInput6).attr('required', true); 
            } 
			$(radioField6).closest('.gfield').show();
			$(radioField6).attr('required', true); 
			$(gradeInput6).attr('required', true); 
			$(schoolInput6).attr('required', true); 
			$(jerseyInput6).attr('required', true);
			
			if ($(dropdownFieldId6).val() === "0") {
				$(dropdownFieldId6).attr('required', true);
			}
			$(dobInput6).attr('required', true);
			$(dropdownFieldId6).closest('.gfield').show(); 
		
        $('input[name="input_15"]').change(function() {
            var selectedValue6 = $('input[name="input_15"]:checked').val();
            if (selectedValue6 == 'Create a Child') {
                $(dropdownFieldId6).closest('.gfield').hide(); 
                $(firstInput6).closest('.gfield').show(); 
                $(lastInput6).closest('.gfield').show();
				$(firstInput6).attr('required', true); 
				$(lastInput6).attr('required', true); 
            } 
            else {
                $(dropdownFieldId6).closest('.gfield').show(); 
                $(firstInput6).closest('.gfield').hide(); 
                $(lastInput6).closest('.gfield').hide(); 
				$(dropdownFieldId6).attr('required', true);
				$(firstInput6).attr('required', false); 
				$(lastInput6).attr('required', false); 
            }
        });
		$('#gform_submit_button_6').click(function(event) {
			var selectedValue6 = $('input[name="input_15"]:checked').val();
            if (selectedValue6 == 'Choose a Child') {
			var selectedValue6 = jQuery('#input_6_16').val();
			if (selectedValue6 === "0") {
				toastr.error("Please select a Player name.");
				// alert("Please select a Player name.");
        event.preventDefault(); 

			}
		}
		});
	});
 // $('input[name="input_15"]:checked').trigger('change');
//    //-------------------------Group Unlimited----------------------------------------
   $('input[name="input_15"]').closest('.gfield_radio').addClass('radio-inline');
        var radioFieldId2 = 'input_15';  
        var dropdownFieldId2 = '#input_2_16';   
        var firstInput2 = '#input_2_8_3';  
        var lastInput2 = '#input_2_8_6';   
		var radioField2 = '#choice_2_15_0';
		var optionInput2 = '#input_2_1';
		var gradeInput2 = '#input_2_5';
		var jerseyInput2 = '#input_2_7';
		var schoolInput2 = '#input_2_12';
		var dobInput2 = '#input_2_14';
		$(dropdownFieldId2).prepend('<option value="0">Select an option</option>');
		$(dropdownFieldId2).find('option[value=""]').remove();
		$(dropdownFieldId2).find('option[value="No players found"]').remove();
		$(dropdownFieldId2).val('0');    
		$(radioField2).closest('.gfield').hide();
    $(dropdownFieldId2).closest('.gfield').hide();
    $(firstInput2).closest('.gfield').hide();
    $(lastInput2).closest('.gfield').hide();
		$(optionInput2).change(function() {
            var radioButton2 = document.querySelector('input[name="input_15"][value="Choose a Child"]');
            var radioButton22 = document.querySelector('input[name="input_15"][value="Create a Child"]');
            var selectElement2 = document.getElementById('input_2_16');
            var optionCount2 = selectElement2.options.length;
            console.log(optionCount2);
            if (optionCount2<=1) {
                document.querySelector('label[for="input_2_16"]').style.display = 'none';
                document.getElementById('input_2_16').style.display = 'none';
                    var element2 = document.getElementById('field_2_16');
                    element2.style.position = 'absolute';
                    element2.style.display = 'none';
                    
                    radioButton2.checked = false; 
                    radioButton22.checked = true;
                    $('#field_2_8').show();
                    $('#choice_2_15_1').prop('disabled', true);
                    $(firstInput2).attr('required', true); 
				    $(lastInput2).attr('required', true); 
            } 
			$(radioField2).closest('.gfield').show();
			$(radioField2).attr('required', true); 
			$(gradeInput2).attr('required', true); 
			$(schoolInput2).attr('required', true); 
			$(jerseyInput2).attr('required', true);
			
			if ($(dropdownFieldId2).val() === "0") {
				$(dropdownFieldId2).attr('required', true);
			}
			$(dobInput2).attr('required', true);
			$(dropdownFieldId2).closest('.gfield').show(); 
		
        $('input[name="input_15"]').change(function() {
            var selectedValue2 = $('input[name="input_15"]:checked').val();
            if (selectedValue2 == 'Create a Child') {
                $(dropdownFieldId2).closest('.gfield').hide(); 
                $(firstInput2).closest('.gfield').show(); 
                $(lastInput2).closest('.gfield').show();
				$(firstInput2).attr('required', true); 
				$(lastInput2).attr('required', true); 
            } 
            else {
                $(dropdownFieldId2).closest('.gfield').show(); 
                $(firstInput2).closest('.gfield').hide(); 
                $(lastInput2).closest('.gfield').hide(); 
				$(dropdownFieldId2).attr('required', true);
				$(firstInput2).attr('required', false); 
				$(lastInput2).attr('required', false); 
            }
        });
		$('#gform_submit_button_2').click(function(event) {
			var selectedValue2 = $('input[name="input_15"]:checked').val();
            if (selectedValue2 == 'Choose a Child') {
			var selectedValue2 = jQuery('#input_2_16').val();
			if (selectedValue2 === "0") {
				toastr.error("Please select a Player name.");
				// alert("Please select a Player name.");
        event.preventDefault(); 

			}
		}
		});
	});
  $('input[name="input_15"]:checked').trigger('change');


    });
</script>
<style>
    .radio-inline {
        display: flex;
        align-items: center; /* Aligns items vertically in the center */
        gap: 10px; /* Adds space between the radio buttons */
    }
    button#gform_submit_button_4 {
    margin-top: -38px;
}
</style>
    <?php
	}
	else{ ?>
    <script>
      jQuery(document).ready(function($) {
//--------------------BWC Fit------------------------------
          var firstInput4 = '#input_4_8_3';  
          var lastInput4 = '#input_4_8_6';   
      var radioField4 = '#choice_4_15_0';
      var optionInput4 = '#input_4_1';
      var gradeInput4 = '#input_4_5';
      var jerseyInput4 = '#input_4_7';
      var schoolInput4 = '#input_4_12';
      var dobInput4 = '#input_4_14';  
      $(radioField4).closest('.gfield').hide();
      $(firstInput4).closest('.gfield').hide();
      $(lastInput4).closest('.gfield').hide();
  
      $(optionInput4).change(function() {
        document.getElementById('field_4_16').style.display = 'none';
        $(firstInput4).closest('.gfield').show(); // Show first name input
        $(lastInput4).closest('.gfield').show(); // Show last name input
        $(gradeInput4).attr('required', true); 
        $(schoolInput4).attr('required', true); 
        $(jerseyInput4).attr('required', true);
        $(dobInput4).attr('required', true);
        $(firstInput4).attr('required', true); 
        $(lastInput4).attr('required', true); 
        var radioButton4 = document.querySelector('input[name="input_15"][value="Create a Child"]');
      if (radioButton4) {
          radioButton4.checked = true; // Set the radio button to checked if it exists
      } else {
          console.error('Radio button not found: input[name="input_15"][value="Create a Child"]');
      }
      });
      //------------------Group Bowling---------------------------
  
      var firstInput3 = '#input_3_8_3';  
          var lastInput3 = '#input_3_8_6';   
      var radioField3 = '#choice_3_15_0';
      var optionInput3 = '#input_3_1';
      var gradeInput3 = '#input_3_5';
      var jerseyInput3 = '#input_3_7';
      var schoolInput3 = '#input_3_12';
      var dobInput3 = '#input_3_14';  
      $(radioField3).closest('.gfield').hide();
      $(firstInput3).closest('.gfield').hide();
          $(lastInput3).closest('.gfield').hide();
  
      $(optionInput3).change(function() {
        document.getElementById('field_3_16').style.display = 'none';
        $(firstInput3).closest('.gfield').show(); // Show first name input
        $(lastInput3).closest('.gfield').show(); // Show last name input
        $(gradeInput3).attr('required', true); 
        $(schoolInput3).attr('required', true); 
        $(jerseyInput3).attr('required', true);
        $(dobInput3).attr('required', true);
        $(firstInput3).attr('required', true); 
        $(lastInput3).attr('required', true); 
        var radioButton3 = document.querySelector('input[name="input_15"][value="Create a Child"]');
      if (radioButton3) {
          radioButton3.checked = true; // Set the radio button to checked if it exists
      } else {
          console.error('Radio button not found: input[name="input_15"][value="Create a Child"]');
      }
      });
      //------------------Group Single Sessions---------------------------
  
  
      var firstInput1 = '#input_1_8_3';  
          var lastInput1 = '#input_1_8_6';   
      var radioField1 = '#choice_1_15_0';
      var optionInput1 = '#input_1_1';
      var gradeInput1 = '#input_1_5';
      var jerseyInput1 = '#input_1_7';
      var schoolInput1 = '#input_1_12';
      var dobInput1 = '#input_1_14';  
      var dropdownFieldId1 = '#input_1_16';   
      $(radioField1).closest('.gfield').hide();
      $(firstInput1).closest('.gfield').hide();
          $(lastInput1).closest('.gfield').hide();
      $(dropdownFieldId1).closest('.gfield').hide();
  
      $(optionInput1).change(function() {
        document.getElementById('field_1_16').style.display = 'none';
        $(firstInput1).closest('.gfield').show(); // Show first name input
        $(lastInput1).closest('.gfield').show(); // Show last name input
        $(gradeInput1).attr('required', true); 
        $(schoolInput1).attr('required', true); 
        $(jerseyInput1).attr('required', true);
        $(dobInput1).attr('required', true);
        $(firstInput1).attr('required', true); 
        $(lastInput1).attr('required', true); 
        var radioButton1 = document.querySelector('input[name="input_15"][value="Create a Child"]');
      if (radioButton1) {
          radioButton1.checked = true; // Set the radio button to checked if it exists
      } else {
          console.error('Radio button not found: input[name="input_15"][value="Create a Child"]');
      }
      });
  
      //------------------In Gym 1-on-1 Session---------------------------
  
      var firstInput5 = '#input_5_8_3';  
          var lastInput5 = '#input_5_8_6';   
      var radioField5 = '#choice_5_15_0';
      var optionInput5 = '#input_5_1';
      var gradeInput5 = '#input_5_5';
      var jerseyInput5 = '#input_5_7';
      var schoolInput5 = '#input_5_12';
      var dobInput5 = '#input_5_14';  
      $(radioField5).closest('.gfield').hide();
      $(firstInput5).closest('.gfield').hide();
          $(lastInput5).closest('.gfield').hide();
  
      $(optionInput5).change(function() {
        document.getElementById('field_5_16').style.display = 'none';
        $(firstInput5).closest('.gfield').show(); // Show first name input
        $(lastInput5).closest('.gfield').show(); // Show last name input
        $(gradeInput5).attr('required', true); 
        $(schoolInput5).attr('required', true); 
        $(jerseyInput5).attr('required', true);
        $(dobInput5).attr('required', true);
        $(firstInput5).attr('required', true); 
        $(lastInput5).attr('required', true); 
        var radioButton5 = document.querySelector('input[name="input_15"][value="Create a Child"]');
      if (radioButton5) {
          radioButton5.checked = true; // Set the radio button to checked if it exists
      } else {
          console.error('Radio button not found: input[name="input_15"][value="Create a Child"]');
      }
      });
        //------------------Specialty Session---------------------------
  
        var firstInput6 = '#input_6_8_3';  
          var lastInput6 = '#input_6_8_6';   
      var radioField6 = '#choice_6_15_0';
      var optionInput6 = '#input_6_1';
      var gradeInput6 = '#input_6_5';
      var jerseyInput6 = '#input_6_7';
      var schoolInput6 = '#input_6_12';
      var dobInput6 = '#input_6_14';  
      $(radioField6).closest('.gfield').hide();
      $(firstInput6).closest('.gfield').hide();
          $(lastInput6).closest('.gfield').hide();
  
      $(optionInput6).change(function() {
        document.getElementById('field_6_16').style.display = 'none';
        $(firstInput6).closest('.gfield').show(); // Show first name input
        $(lastInput6).closest('.gfield').show(); // Show last name input
        $(gradeInput6).attr('required', true); 
        $(schoolInput6).attr('required', true); 
        $(jerseyInput6).attr('required', true);
        $(dobInput6).attr('required', true);
        $(firstInput6).attr('required', true); 
        $(lastInput6).attr('required', true); 
        var radioButton6 = document.querySelector('input[name="input_15"][value="Create a Child"]');
      if (radioButton6) {
          radioButton6.checked = true; // Set the radio button to checked if it exists
      } else {
          console.error('Radio button not found: input[name="input_15"][value="Create a Child"]');
      }
      });
          //------------------Group Unlimited---------------------------
  
          var firstInput2 = '#input_2_8_3';  
          var lastInput2 = '#input_2_8_6';   
      var radioField2 = '#choice_2_15_0';
      var optionInput2 = '#input_2_1';
      var gradeInput2 = '#input_2_5';
      var jerseyInput2 = '#input_2_7';
      var schoolInput2 = '#input_2_12';
      var dobInput2 = '#input_2_14';  
      var dropdown2 = '#input_2_16';  
      $(radioField2).closest('.gfield').hide();
      $(firstInput2).closest('.gfield').hide();
          $(lastInput2).closest('.gfield').hide();
          $(dropdown2).closest('.gfield').hide();
  
      $(optionInput2).change(function() {
        document.getElementById('field_2_16').style.display = 'none';
        $(firstInput2).closest('.gfield').show(); // Show first name input
        $(lastInput2).closest('.gfield').show(); // Show last name input
        $(gradeInput2).attr('required', true); 
        $(schoolInput2).attr('required', true); 
        $(jerseyInput2).attr('required', true);
        $(dobInput2).attr('required', true);
        $(firstInput2).attr('required', true); 
        $(lastInput2).attr('required', true); 
        var radioButton2 = document.querySelector('input[name="input_15"][value="Create a Child"]');
      if (radioButton2) {
          radioButton2.checked = true; // Set the radio button to checked if it exists
      } else {
          console.error('Radio button not found: input[name="input_15"][value="Create a Child"]');
      }
      });
  });
  </script>
      
  <?php	}

?>
<script>

</script>
<?php
}

//----------------------------------------------------------------------------


add_filter('woocommerce_add_cart_item_data', 'duplicate_cart_item', 10, 3);
function duplicate_cart_item($cart_item_data, $product_id, $variation_id) {
    $should_duplicate = true; 
    session_start();
    $product = wc_get_product($product_id);
    if (isset($_SESSION['status']) && $_SESSION['status'] == 'signup'  && $_SESSION['self_register']==1) {
    if ($product_id=='1723' || $product_id=='1727') {
     
        $cart_item_data['product_sku'] = $product->get_sku();
        $cart_item_data['product_name'] = $product->get_name();
        $cart_item_data['_gravity_form_data'] = get_gravity_form_data_for_product($product_id);
        $cart_item_data['_gravity_form_lead'] = get_gravity_form_lead_for_product($product_id);
      }
    }

    if ($should_duplicate) {
        $cart_item_data['duplicate_item'] = true; 
    }

    return $cart_item_data;
}
function get_gravity_form_data_for_product($product_id) {
    if ($product_id == 1727) {
      $form_data = [
          'id' => 5,
      ];
    } elseif ($product_id == 1723) {
       
        $form_data = [
            'id' => 1, 
        ];
    } else {
        $form_data = [
            'id' => 5, 
        ];
    }
    return $form_data;
}

function get_gravity_form_lead_for_product($product_id) {
if (isset($_SESSION['status']) && $_SESSION['status'] == 'signup'  && $_SESSION['self_register']==1) {   
if($product_id==1727) 
{
  $form_data = [
    'form_id' => 5, 
    'source_url' => $siteurl.'/product/group-single-sessions/',
    'ip' => '103.170.54.39',
    '1' => '1000 Session|100', 
    '15' => 'Create a Child',
    '8.2' => '', 
    '8.3' => '', 
    '8.4' => '', 
    '8.6' => '', 
    '8.8' => '', 
    '16' => '', 
    '14' => '', 
    '5' => '',
    '7' => '',
    '12' => '',
    '2' => '100000',
    '9' => '',
    '10' => '', 
    '11' => '', 
];
}
else
{
  $form_data = [
    'form_id' => 5, 
    'source_url' => $siteurl.'/product/group-single-sessions/',
    'ip' => '103.170.54.39',
    '1' => '1000 Session|50', 
    '15' => 'Create a Child',
    '8.2' => '', 
    '8.3' => '', 
    '8.4' => '', 
    '8.6' => '', 
    '8.8' => '', 
    '16' => '', 
    '14' => '', 
    '5' => '',
    '7' => '',
    '12' => '',
    '2' => '50000',
    '9' => '',
    '10' => '', 
    '11' => '', 
];
}

$previous_cart_item_lead = null;
    $cart_items = WC()->cart->get_cart();
if (!empty($cart_items)) {
  foreach ($cart_items as $cart_item_key => $cart_item) {
      if ($cart_item['product_id'] != $product_id) {
          if (isset($cart_item['_gravity_form_lead'])) {
              $previous_cart_item_lead = $cart_item['_gravity_form_lead'];
              break; 
          }
      }
      else
      {
        if (isset($cart_item['_gravity_form_lead'])) {
          $previous_cart_item_lead = $cart_item['_gravity_form_lead'];
          break; 
      }
      }
  }
}

if ($previous_cart_item_lead) {
  foreach ($previous_cart_item_lead as $key => $value) {
    if ($key != '1' && $key != '2') {
      $form_data[$key] = $value;
  }
  }
}

return $form_data;
}
}

add_action('woocommerce_cart_loaded_from_session', 'create_duplicate_cart_item', 20);
function create_duplicate_cart_item() {
  session_start();
  if (isset($_SESSION['status']) && $_SESSION['status'] == 'signup'  && $_SESSION['self_register']==1) {
      $gravity_data = WC()->session->get('gravity_data'); 
      $item_duplicated = WC()->session->get('item_duplicated', false); 

      if ($item_duplicated) {
          return;
      }

      $cart_items = WC()->cart->get_cart();
      if (empty($cart_items)) {
        if (isset($_SESSION['status'])) {
          unset($_SESSION['status']);
      }
          return; 
      }
      //----------------------------------------------------------------
        // Initialize variables to store keys and items
        $first_cart_item_key = null;
        $second_cart_item_key = null;
        $third_cart_item_key = null;
        $fourth_cart_item_key = null;

        $first_cart_item = null;
        $second_cart_item = null;
        $third_cart_item = null;
        $fourth_cart_item = null;

        // Counter to track the item position
        $item_position = 0;

        // Loop through the cart items
        foreach ($cart_items as $cart_item_key => $cart_item) {
            $item_position++;
            if ($item_position == 1) {
                $first_cart_item_key = $cart_item_key;
                $first_cart_item = $cart_item; // Store the first item
            } elseif ($item_position == 2) {
                $second_cart_item_key = $cart_item_key;
                $second_cart_item = $cart_item; // Store the second item
            } elseif ($item_position == 3) {
                $third_cart_item_key = $cart_item_key;
                $third_cart_item = $cart_item; // Store the third item
            }elseif ($item_position == 4) {
                $fourth_cart_item_key = $cart_item_key;
                $fourth_cart_item = $cart_item; // Store the third item
            }
            // Exit loop if we already have the first three items
            if ($item_position >= 4) {
                break;
            }
        }
        
      //----------------------------------------------------------------

    //   $first_cart_item_key = key($cart_items);
    //   $first_cart_item = reset($cart_items);

      if (isset($first_cart_item['duplicate_item']) && $first_cart_item['duplicate_item'] == true) {

          unset($first_cart_item['duplicate_item']);
          
          $new_cart_item = $first_cart_item;

          $new_product_id = 1727; 
          $new_cart_item['product_id'] = $new_product_id;
 
          if (isset($first_cart_item['gravity_form_data'])) {
              $new_cart_item['session_details'] = $first_cart_item['_gravity_form_data']['session_details']; 
              $new_cart_item['_gravity_form_lead'] = [
                  'form_id' => 5,
                  'source_url' => $siteurl.'/product/in-gym-1-on-1-session/',
              ];
          }

          WC()->cart->add_to_cart(
              $new_cart_item['product_id'], 
              1000, 
              $new_cart_item['variation_id'] ?? null, 
              $new_cart_item['variation'] ?? [], 
              $new_cart_item['_gravity_form_lead'],
              $new_cart_item 
          );

          $new_product_id = 1723; 
          $new_cart_item['product_id'] = $new_product_id;

          if (isset($first_cart_item['gravity_form_data'])) {
              $new_cart_item['session_details'] = $first_cart_item['_gravity_form_data']['session_details']; 
              $new_cart_item['_gravity_form_lead'] = [
                  'form_id' => 1,
                  'source_url' => $siteurl.'/product/group-single-sessions/',
              ];
          }
          WC()->cart->add_to_cart(
              $new_cart_item['product_id'], 
              1000,  
              $new_cart_item['variation_id'] ?? null, 
              $new_cart_item['variation'] ?? [],
              $new_cart_item['_gravity_form_lead'], 
              $new_cart_item 
          );
          if ($first_cart_item_key) {
            WC()->cart->remove_cart_item($first_cart_item_key);
        }
        if ($second_cart_item_key) {
            WC()->cart->remove_cart_item($second_cart_item_key);
        }
        if ($third_cart_item_key) {
            WC()->cart->remove_cart_item($third_cart_item_key);
        }
        if ($fourth_cart_item) {
            WC()->cart->remove_cart_item($fourth_cart_item);
        }
          WC()->session->set('item_duplicated', true);
      }
  }
}
add_action('woocommerce_thankyou', 'clear_session_status_after_checkout', 10, 1);

function clear_session_status_after_checkout($order_id) {
    if (!$order_id) {
        return;
    }

    // Start session if not already started
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }

    // Unset the specific session variable
    if (isset($_SESSION['status'])) {
        unset($_SESSION['status']);
    }
}


function output_base_url_js_variable() {
  ?>
  <script>
      var baseUrl = "<?php echo esc_url(BWC_API_LOGIN_ENDPOINT . '/wp-json/bwc-api/v1/'); ?>";
  </script>
  <?php
}
add_action('wp_head', 'output_base_url_js_variable');


add_action('woocommerce_payment_token_created', 'set_stripe_default_payment_method', 10, 2);

function set_stripe_default_payment_method($token_id, $user_id) {
    // Get the payment token object
    $token = WC_Payment_Tokens::get($token_id);

    // Ensure the token is for Stripe
    if ($token->get_gateway_id() !== 'stripe') {
        return;
    }

    // Get the Stripe customer ID for the user
    $stripe_customer_id = get_user_meta($user_id, '_stripe_customer_id', true);

    if (!$stripe_customer_id) {
        return; // Exit if no Stripe customer ID is found
    }

    // Get the Stripe payment method ID (token)
    $stripe_payment_method_id = $token->get_token();

    // Update the default payment method in Stripe
    $stripe = new \Stripe\StripeClient('sk_test_tFWZDonCqCPcg1hnIUOOKPzn'); // Replace with your Stripe secret key

    try {
        $stripe->customers->update($stripe_customer_id, [
            'invoice_settings' => [
                'default_payment_method' => $stripe_payment_method_id,
            ],
        ]);

        // Optionally, update user meta to reflect the default payment method
        update_user_meta($user_id, '_stripe_default_source', $stripe_payment_method_id);

    } catch (\Exception $e) {
        error_log('Error setting default payment method in Stripe: ' . $e->getMessage());
    }
}


add_action('init', function () {
    if (!validate_time_difference()) {
    }
});

function validate_time_difference() {
    //$server_time =date('Y-m-d H:i:s'); // Server time
    $serverTime = new DateTime('now');
    $serverTime=$serverTime->getTimestamp(); 
    $serverTimeFormatted = date('Y-m-d H:i:s', $serverTime);
    error_log('server_time' . $serverTimeFormatted);


    $utc_time = (new DateTime('now', new DateTimeZone('UTC')))->format('Y-m-d H:i:s');
    $system_time = getLocalTimeFromUtc($utc_time, 'Asia/Kolkata');
    error_log('system_time' . $system_time);

    $timezone=date_default_timezone_get();
    error_log('timezone' . $timezone);
    if (!$system_time) {
        return false;
    }
    // Calculate time difference
    $difference = strtotime($serverTimeFormatted) - strtotime($system_time);
    error_log('difference' . $difference);
    if (abs($difference) > 300) { 
        $to = [
            'annie@spericorn.com', 
            'user1@example.com', 
            'user2@example.com'
        ];
        $subject = 'Time Mismatch Notification';
        $message = "Time Mismatch Detected in BWC:<br><br>" .
           "Server Time: $serverTimeFormatted<br>" .
           "System Time: $system_time<br>" .
           "Time Difference: $difference seconds<br>" .
           "Default Time: $timezone";
        wp_mail($to, $subject, $message);

        error_log('Time mismatch detected. Notification sent.');
    }
}
function getLocalTimeFromUtc($utc_time, $local_time_zone = 'Asia/Kolkata') {
    if (empty($utc_time)) {
        error_log('UTC time is empty.');
        return null;
    }

    try {
        // Create a DateTime object for the UTC time
        $utc_datetime = new DateTime($utc_time, new DateTimeZone('UTC'));

        // Convert to the specified local time zone
        $utc_datetime->setTimezone(new DateTimeZone($local_time_zone));
        // Return the local time as a string in 'Y-m-d H:i:s' format
        return $utc_datetime->format('Y-m-d H:i:s');
    } catch (Exception $e) {
        error_log('Error converting time: ' . $e->getMessage());
        return null;
    }
}

// add_action('woocommerce_checkout_update_order_meta', 'attach_payment_method_before_payment', 10, 1);

// function attach_payment_method_before_payment($order_id) {
//     // Get the WooCommerce order object
//     error_log('stripe_customer_id'.$order_id);
//     $order = wc_get_order($order_id);
    
//     error_log('stripe_customer_id'.$order);
//     // Retrieve Stripe customer ID and payment method ID from order meta
//     $stripe_customer_id = $order->get_meta('_stripe_customer_id'); // Stripe customer ID
//     $payment_method_id = $order->get_meta('_stripe_source_id'); // Stripe payment method ID

//     error_log('stripe_customer_id'.$stripe_customer_id);
//     error_log('payment_method_id'.$payment_method_id);

//     if (!$stripe_customer_id || !$payment_method_id) {
//         // If no customer or payment method ID, log and exit
//         error_log('Stripe customer or payment method ID not found.');
//         return;
//     }

//     // Initialize Stripe API client
//     $stripe = new \Stripe\StripeClient('sk_test_tFWZDonCqCPcg1hnIUOOKPzn'); // Replace with your secret key

//     try {
//         // Check if the payment method is already attached to the customer
//         $payment_method = $stripe->paymentMethods->retrieve($payment_method_id);
        
//         if ($payment_method->customer != $stripe_customer_id) {
//             // Attach the payment method to the customer if it's not already attached
//             $payment_method = $stripe->paymentMethods->attach($payment_method_id, [
//                 'customer' => $stripe_customer_id,
//             ]);
            
//             error_log('Payment method attached to customer.');
//         } else {
//             error_log('Payment method is already attached to the customer.');
//         }

//         // Set the attached payment method as the default for the customer
//         $stripe->customers->update($stripe_customer_id, [
//             'invoice_settings' => [
//                 'default_payment_method' => $payment_method_id,
//             ],
//         ]);

//         // Optionally save the default payment method in user meta (for future use in WooCommerce)
//         update_user_meta($order->get_user_id(), '_stripe_default_payment_method', $payment_method_id);

//         // Log success
//         error_log('Payment method attached and set as default successfully.');

//     } catch (\Stripe\Exception\ApiErrorException $e) {
//         // Log any Stripe API errors
//         error_log('Error attaching payment method: ' . $e->getMessage());
//     }
// }

// Hook into WooCommerce order status transitions
add_action('woocommerce_order_status_processing', 'attach_payment_method_to_customer', 10, 1);
add_action('woocommerce_order_status_on-hold', 'attach_payment_method_to_customer', 10, 1);
add_action('woocommerce_payment_complete', 'attach_payment_method_to_customer', 10, 1);

function attach_payment_method_to_customer($order_id) {
    // Get the WooCommerce order object
    $order = wc_get_order($order_id);

    // Ensure the payment method is Stripe
    if ($order->get_payment_method() !== 'stripe') {
        return;
    }

    // Get the payment intent and payment method IDs from order metadata
    $payment_intent_id = $order->get_meta('_stripe_intent_id'); // PaymentIntent ID
    $payment_method_id = $order->get_meta('_stripe_source_id');  // PaymentMethod ID
    $stripe_customer_id = $order->get_meta('_stripe_customer_id'); // Stripe Customer ID (if already stored)

    if (empty($payment_intent_id) || empty($payment_method_id)) {
        error_log('Missing payment intent or payment method ID for order ID: ' . $order_id);
        return;
    }

    // Initialize Stripe API client
    $stripe = new \Stripe\StripeClient('sk_test_tFWZDonCqCPcg1hnIUOOKPzn'); // Replace with your Stripe secret key
    error_log('stripe: ' . print_r($stripe, true));
    // try {
        // Attempt to attach the payment method
        error_log('1...........');

        // Retrieve the payment method
        // $payment_method = $stripe->paymentMethods->retrieve($payment_method_id);
        
        // // Log the payment method details for debugging
        // error_log('Payment Method: ' . print_r($payment_method, true));
        
        // // Log the customer ID
        // error_log('stripe_customer_id...........'.$stripe_customer_id);
        
        // // Check if the payment method is already attached to the correct customer
        // if ($payment_method->customer !== $stripe_customer_id) {
        //     // Log the payment method ID that needs to be detached
        //     error_log('payment_method_id...........'.$payment_method_id);
        
        //     // Detach the payment method from its current customer
        //     $stripe->paymentMethods->detach($payment_method_id);
        
        //     // Attach the payment method to the correct customer
        //     $stripe->paymentMethods->attach($payment_method_id, [
        //         'customer' => $stripe_customer_id,
        //     ]);
        
        //     // Log that the payment method has been attached to the new customer
        //     error_log('payment_method attached to customer ID: '.$stripe_customer_id);
        
        //     // Set the payment method as the default for the customer
        //     $stripe->customers->update($stripe_customer_id, [
        //         'invoice_settings' => [
        //             'default_payment_method' => $payment_method_id,
        //         ],
        //     ]);
        
        //     // Log after updating the customer
        //     error_log('stripe_customer_id111...........'.$stripe_customer_id);
        // } else {
        //     // Log if no action is needed
        //     error_log('Payment method is already attached to the correct customer.');
        // }
        try {
            // Retrieve the payment method
            $payment_method = $stripe->paymentMethods->retrieve($payment_method_id);
            error_log('Payment Method: ' . print_r($payment_method, true));
        
            // Detach if previously attached
            $payment_method->detach();
            $payment_method = $stripe->paymentMethods->retrieve($payment_method_id);  // Ensure detachment
            error_log('Payment Method after detachment: ' . print_r($payment_method, true));
            
            // Attach to customer
            $payment_method->attach([
                'customer' => $stripe_customer_id,
            ]);
            error_log('Payment method successfully attached to customer: ' . $stripe_customer_id);
        
            // Set the payment method as the default for the customer
            $stripe->customers->update($stripe_customer_id, [
                'invoice_settings' => [
                    'default_payment_method' => $payment_method_id,
                ],
            ]);
            error_log('4...........');
        } catch (\Stripe\Exception\ApiErrorException $e) {
            error_log('Error occurred: ' . $e->getMessage());
        }
        

        // Save customer ID and payment method in user meta
        update_user_meta($order->get_user_id(), '_stripe_customer_id', $stripe_customer_id);
        update_user_meta($order->get_user_id(), '_stripe_default_payment_method', $payment_method_id);
        error_log('5...........');
    // } catch (\Stripe\Exception\ApiErrorException $e) {
    //     // Log error and provide clear feedback
    //     if (strpos($e->getMessage(), 'This PaymentMethod was previously used without being attached to a Customer') !== false) {
    //         error_log('Error: Payment method was not attached to the customer initially, please re-enter payment details.');
    //     } else {
    //         error_log('Error attaching payment method: ' . $e->getMessage());
    //     }
    // }
    
}





//////////login/logout nav menu corrections

add_filter( 'wp_nav_menu_objects', 'hide_my_account_logout_menu_items', 10, 2 );

function hide_my_account_logout_menu_items( $items, $args ) {
    if ( isset( $args->menu_id ) ) {
        foreach ( $items as $key => $item ) {
            if ( ( $item->title === 'My Account' || $item->url === site_url('/my-account/') ) && !isset($_SESSION['uid']) ) {
                unset( $items[ $key ] ); // Remove the item if the user is not logged in
                continue;
            }else if ( ( $item->title === 'Logout' || $item->url === wp_logout_url() || strpos($item->url, 'action=custom_logout') !== false ) && !isset($_SESSION['uid']) ) {
                unset( $items[ $key ] ); // Remove the item if the user is not logged in
                continue;
            }else if ( ( $item->title === 'Login' || $item->url === site_url('/login/')) && isset($_SESSION['uid']) ) {
                unset( $items[ $key ] ); // Remove the item if the user is not logged in
                continue;
            }else {
                $items[ $key ] = $item; 
            }
        }
    }

    return $items;
}



  ?>