<?php

function add_theme_scripts() {
	wp_register_script( 'site-script', get_stylesheet_directory_uri().'/assets/js/site_script.js', array ( 'jquery' ), time(), true);
	wp_enqueue_script('site-script');

	$default_language = '';
	wp_localize_script('site-script', 'siteData', array(
	        'site_url' => get_site_url(),
			'site_lang' => defined('ICL_LANGUAGE_CODE') ? ICL_LANGUAGE_CODE : '',
			'primary_lang' => $default_language,
			'ajaxurl' => admin_url('admin-ajax.php'),
			'chosen_text' => __('CHOSEN', 'fitsmartio_en'),
			'choose_text' => __('CHOOSE', 'fitsmartio_en'),
		)
	);
	wp_enqueue_style( 'site-style', get_stylesheet_directory_uri().'/assets/css/site_style.css', array(),time());
}
add_action('wp_enqueue_scripts', 'add_theme_scripts');

add_filter('woocommerce_checkout_redirect_empty_cart','__return_false');
add_filter('woocommerce_checkout_update_order_review_expired','__return_false');

function get_language_shortcode() {
    return apply_filters( 'wpml_current_language', null );
}
add_shortcode( 'language', 'get_language_shortcode' );

// Function to add a product to the cart by product ID if it doesn't exist
function add_product_to_cart_by_id($product_id) {

   if(empty(WC()->cart)) {
	return;
	}

    // Check if the product is already in the cart
    $cart = WC()->cart->get_cart();
    $product_in_cart = false;

    foreach ($cart as $cart_item_key => $cart_item) {
        if ($cart_item['product_id'] == $product_id) {
            $product_in_cart = true;
            break;
        }
    }

    // If the product is not in the cart, add it
    if (!$product_in_cart) {
		WC()->cart->empty_cart();
        WC()->cart->add_to_cart($product_id);
    }
}

function custom_init_function() {

    if (session_status() === PHP_SESSION_NONE && !headers_sent())
    {
        session_start();
    }

    if(!empty($_GET['id'])){
		add_product_to_cart_by_id($_GET['id']);
	}
}
add_action('init', 'custom_init_function', 1);


function add_product_to_cart_on_checkout_page() {
	$current_language = get_language_shortcode();

	$variation = get_query_var("variation");

    // Check if we are on the checkout page and the cart is empty
	if (is_checkout()){
		$_SESSION['cid'] = $_SERVER['QUERY_STRING'];

	}
	if( is_wc_endpoint_url( 'order-received' ) && isset( $_GET['key'] ) ) {

	}else{

		if (is_checkout() && WC()->cart->is_empty() && empty($_GET['id']) ) {
			// Replace 'PRODUCT_ID' with the actual product ID you want to add to the cart

			if($variation == 'v2')
			{
				$product_id = '1315';

			}else{
				$product_id = '1313';
			}

			if($current_language == 'fr')
			{
				if($variation == 'v2')
				{
					$product_id = '1433';
				}else{
					$product_id = '2514';
				}
			}elseif($current_language == 'nl')
			{
				if($variation == 'v2')
				{
					$product_id = '1420';
				}else{
					$product_id = '1415';
				}
			}elseif($current_language == 'benl')
			{
				if($variation == 'v2')
				{
					$product_id = '1496';
				}else{
					$product_id = '1490';
				}
			}elseif($current_language == 'befr')
			{
				if($variation == 'v2')
				{
					$product_id = '1481';
				}else{
				    $product_id = '1478';
				}
			}elseif($current_language == 'sv')
			{
				if($variation == 'v2')
				{
					$product_id = '3838';
				}else{
				    $product_id = '3836';
				}
			}elseif($current_language == 'no')
			{
				if($variation == 'v2')
				{
					$product_id = '3786';
				}else{
				    $product_id = '3784';
				}
			}elseif($current_language == 'da')
			{
				if($variation == 'v2')
				{
					$product_id = '3769';
				}else{
				    $product_id = '3767';
				}
			}elseif($current_language == 'fi')
			{
				if($variation == 'v2')
				{
					$product_id = '3786';
				}else{
				    $product_id = '3784';
				}
			}elseif($current_language == 'de')
			{
				if($variation == 'v2' && $current_language == 'de')
				{
					$product_id = '1373';
				}else{
					$product_id = '1370';
				}

			}elseif($current_language == 'pt-pt')
			{
				if($variation == 'v2')
				{
					$product_id = '1461'; // 3 unidades
				}else{
				    $product_id = '1457';
				}
			}elseif($current_language == 'ie')
			{
				if($variation == 'v2')
				{
					$product_id = '1002004'; // 5 pack, same as Uncategorized
				}else{
				    $product_id = '1002004'; // 5 pack
				}
			}

			$stock_status = get_post_meta($product_id, '_stock_status', true);
			$outofstock = 0;
			if ($stock_status == 'outofstock') {
				$product_id = '1315';
				if($current_language == 'nl' || $current_language == 'fr')
				{
					$product_id = '1420';
					$product_id = icl_object_id($product_id,'product',false,$current_language);
				}elseif($current_language == 'benl')
				{
					$product_id = '1496';
				}elseif($current_language == 'befr')
				{
					$product_id = '1481';
				}elseif($current_language == 'sv')
				{
					$product_id = '3838 ';
				}elseif($current_language == 'no')
				{
					$product_id = '3786';
				}elseif($current_language == 'da')
				{
					$product_id = '3769';
				}elseif($current_language == 'fi')
				{
					$product_id = '3786';
				}elseif($current_language == 'de')
				{
					$product_id = '1373';
				}elseif($current_language == 'pt-pt')
				{
					$product_id = '1491';
				}elseif($current_language == 'ie')
				{
					$product_id = '1002003'; // 3 pack
				}

				$stock_status = get_post_meta($product_id, '_stock_status', true);
				if ($stock_status == 'outofstock') {
					$product_id = '1314';
					if($current_language == 'nl' || $current_language == 'fr')
					{
						$product_id = '1419';
						$product_id = icl_object_id($product_id,'product',false,$current_language);
					}elseif($current_language == 'benl')
					{
						$product_id = '1491';
					}elseif($current_language == 'befr')
					{
						$product_id = '1482';
					}elseif($current_language == 'sv')
					{
						$product_id = '3837';
					}elseif($current_language == 'no')
					{
						$product_id = '3785';
					}elseif($current_language == 'fi')
					{
						$product_id = '3785';
					}elseif($current_language == 'da')
					{
						$product_id = '3768';
					}elseif($current_language == 'de')
					{
						$product_id = '1372';
					}elseif($current_language == 'pt-pt')
					{
						$product_id = '1460';
					}elseif($current_language == 'ie')
					{
						$product_id = '1002005'; // 1 pack
					}

					$stock_status = get_post_meta($product_id, '_stock_status', true);
					if ($stock_status == 'outofstock') {
						$redirect_url = get_site_url().'/out-of-stock';

						//wp_safe_redirect($redirect_url);
						//exit;
					}
				}
			}


			// Check if the product exists
			if (wc_get_product($product_id)) {
				// Add the product to the cart
				WC()->cart->add_to_cart($product_id);
				$current_query_string = $_SERVER['QUERY_STRING'];

				if(empty($current_query_string)){
					$redirect_url = wc_get_checkout_url();
				}else{
					$redirect_url = wc_get_checkout_url() . '?' . $current_query_string;
				}
				// Optionally, redirect to the cart page after adding the product
				//wp_safe_redirect($redirect_url);
				//exit;
			}

		}
	}

}
add_action('template_redirect', 'add_product_to_cart_on_checkout_page');

add_action('init', function(){
    add_rewrite_rule(
      '^checkout/([^/]+)([/]?)(.*)',
      //!IMPORTANT! THIS MUST BE IN SINGLE QUOTES!:
      'index.php?pagename=checkout&variation=$matches[1]',
      'top'
    );


});

add_filter('query_vars', function( $vars ){
    $vars[] = 'pagename';
    $vars[] = 'variation';
    return $vars;
});


/* Create Custom Endpoint */
add_action( 'rest_api_init', 'create_custon_endpoint' );
function create_custon_endpoint(){
    register_rest_route(
        'wp/v2',
        '/avgreviews',
        array(
            'methods' => 'GET',
            'callback' => 'fts_avgreviews_callback',
        )
    );
}

function fts_avgreviews_callback($data) {

	ob_start();

	global $wpdb;

	$current_lang = '';
	if(isset($data['lang']) && !empty($data['lang']))
	{
		$current_lang = $data['lang'];
	}

	$wp_posts_table = $wpdb->prefix."posts";
	$wp_postmeta_table = $wpdb->prefix."postmeta";
	$icl_translations_table = $wpdb->prefix."icl_translations";

	$query = "
		SELECT avg($wp_postmeta_table.meta_value) as avg_rating     
		FROM $wp_posts_table inner join $wp_postmeta_table ON $wp_posts_table.ID = $wp_postmeta_table.post_id 
		LEFT JOIN $icl_translations_table ON $wp_posts_table.ID = $icl_translations_table.element_id  
		WHERE $wp_posts_table.post_type = 'checkout_review' 
		AND $wp_posts_table.post_status = 'publish'
		AND $icl_translations_table.language_code = '$current_lang'
		AND $wp_postmeta_table.meta_key like 'rating_number'
		order by $wp_posts_table.post_date DESC
	";

	$results = $wpdb->get_row( $query );

	$avg_rating = 0;
	if(!empty($results))
	{
		$avg_rating = $results->avg_rating;
	}

	$response_arr = array(
	    'rating' => $avg_rating
	);

    return $response_arr;
}

add_filter( 'woocommerce_get_checkout_order_received_url', 'wpse_custom_action_after', PHP_INT_MAX, 3 );
function wpse_custom_action_after( $url, $order ) {
    // your custom changes to $actions array HERE
    // this will be executed after add_edit_address_subscription_action function
	if(!empty($_SESSION['cid'])){
		return $url.'&'.$_SESSION['cid'];
		unset ($_SESSION['cid']);
	}else{
		return $url;
	}
}

/* Short codes registration */
function register_include_shortcode($shortcode, $filename) {
    add_shortcode($shortcode, fn() => include_shortcode_file($filename));
}

function include_shortcode_file($filename) {
    ob_start();
    include get_stylesheet_directory() . '/includes/shortcode/' . $filename;
    return ob_get_clean();
}

$shortcodes = [
    'product_benefits' => 'product_benefits.php',
    'checkout_products' => 'checkout_products.php',
    'checkout_products_new' => 'checkout_products_new.php',
    'checkout_reviews' => 'checkout_reviews.php',
    'checkout_reviews_new' => 'checkout_reviews_new.php',

    'checkout_products_getfitex' => 'checkout_products_getfitex.php',
    'product_benefits_getfitex' => 'product_benefits_getfitex.php',
    'product_ingredients_getfitex' => 'product_ingredients_getfitex.php',
    'checkout_reviews_getfitex' => 'checkout_reviews_getfitex.php',
    'checkout_styles_getfitex' => 'checkout_styles_getfitex.php', // contains css styles

    'funnel_form_getfittex' => 'new-checkout/funnel_form_getfittex.php', // contains css styles
    'glucofit_theme' => 'glucofit_theme.php', // contains css styles
];

foreach ($shortcodes as $shortcode => $filename) {
    register_include_shortcode($shortcode, $filename);
}


function change_woocommerce_texts($translated_text, $text, $domain) {
	$my_current_lang = apply_filters( 'wpml_current_language', NULL );

	if($my_current_lang == 'de'){
		switch ($text) {
			case 'Sorry, it seems that there are no available payment methods for your state. Please contact us if you require assistance or wish to make alternate arrangements.':
				$translated_text = 'Es tut uns leid, es scheint, dass für Ihr Bundesland keine Zahlungsmethoden verfügbar sind. Bitte kontaktieren Sie uns, wenn Sie Hilfe benötigen oder alternative Vereinbarungen treffen möchten.';
				break;

			// Add more cases for other text strings you want to change
		}
	}else if($my_current_lang == 'nl'){
		switch ($text) {
			case 'Sorry, it seems that there are no available payment methods for your state. Please contact us if you require assistance or wish to make alternate arrangements.':
				$translated_text = 'Sorry, het lijkt erop dat er geen beschikbare betaalmethoden zijn voor uw staat. Neem contact met ons op als u hulp nodig heeft of alternatieve afspraken wilt maken.';
				break;
			// Add more cases for other text strings you want to change
		}
	}else if($my_current_lang == 'fr'){
		switch ($text) {
			case 'Sorry, it seems that there are no available payment methods for your state. Please contact us if you require assistance or wish to make alternate arrangements.':
				$translated_text = "Désolé, il semble qu’aucun mode de paiement ne soit disponible pour votre état. Veuillez nous contacter si vous avez besoin d'aide ou si vous souhaitez prendre d'autres dispositions.";
				break;
			// Add more cases for other text strings you want to change
		}
	}
	else if($my_current_lang == 'benl'){
		switch ($text) {
			case 'Sorry, it seems that there are no available payment methods for your state. Please contact us if you require assistance or wish to make alternate arrangements.':
				$translated_text = 'Sorry, het lijkt erop dat er geen beschikbare betaalmethoden zijn voor uw staat. Neem contact met ons op als u hulp nodig heeft of alternatieve afspraken wilt maken.';
				break;
			// Add more cases for other text strings you want to change
		}
	}
	else if($my_current_lang == 'befr'){
		switch ($text) {
			case 'Sorry, it seems that there are no available payment methods for your state. Please contact us if you require assistance or wish to make alternate arrangements.':
				$translated_text = "Désolé, il semble qu’aucun mode de paiement ne soit disponible pour votre état. Veuillez nous contacter si vous avez besoin d'aide ou si vous souhaitez prendre d'autres dispositions.";
				break;

			// Add more cases for other text strings you want to change
		}
	}else if($my_current_lang == 'pt-pt'){
		switch ($text) {
			case 'Sorry, it seems that there are no available payment methods for your state. Please contact us if you require assistance or wish to make alternate arrangements.':
				$translated_text = 'Desculpe, parece que não há métodos de pagamento disponíveis para o seu estado. Entre em contato conosco se precisar de assistência ou desejar fazer arranjos alternativos.';
				break;

			// Add more cases for other text strings you want to change
		}
	}
    return $translated_text;
}
add_filter('gettext', 'change_woocommerce_texts', 10, 3);

function express_paypal_payment_callback() {
    ob_start();

	$expcheckout_lbl = __("Express Checkout","fitsmartio_en");
	echo '<div class="fscheckout_expressbtn_ct"><div class="wc-ppcp-express-checkout">'.$expcheckout_lbl.'</div></div>';
    $content = ob_get_clean();
    return $content;
}
add_shortcode('express_paypal_payment','express_paypal_payment_callback');


function custom_post_type_checkout_reviews(){
    $labels = array(
        'name'               => 'Checkout Reviews',
        'singular_name'      => 'Checkout Review',
        'menu_name'          => 'Checkout Reviews',
        'add_new'            => 'Add New',
        'add_new_item'       => 'Add New Checkout Review',
        'edit_item'          => 'Edit Checkout Review',
        'new_item'           => 'New Checkout Review',
        'view_item'          => 'View Checkout Review',
        'search_items'       => 'Search Checkout Reviews',
        'not_found'          => 'No Checkout Reviews found',
        'not_found_in_trash' => 'No Checkout Reviews found in Trash',
        'parent_item_colon'  => '',
        'all_items'          => 'All Checkout Reviews',
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array( 'slug' => 'checkout-review' ),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => null,
		'show_in_rest'       => true,
		'rest_base'          => 'checkout_reviews',
		'rest_controller_class' => 'WP_REST_Posts_Controller',
        'supports'           => array( 'title','author','thumbnail'),
    );
    register_post_type( 'checkout_review', $args );
}
add_action( 'init', 'custom_post_type_checkout_reviews' );


// Add custom column to the checkout_review post type
function add_status_column($columns) {
    $columns['review_status'] = 'Approval Status';
    return $columns;
}
add_filter('manage_checkout_review_posts_columns', 'add_status_column');

// Display data in the custom column
function display_status_column($column, $post_id) {
    if ($column == 'review_status') {
        // Get and display the status of the post
        $status = get_post_status($post_id);

        // Output a dropdown to change the status dynamically
        echo '<select class="review-status-dropdown" data-post-id="' . esc_attr($post_id) . '">';
        echo '<option value="pending" ' . selected('pending', $status, false) . '>Pending</option>';
        echo '<option value="publish" ' . selected('publish', $status, false) . '>Publish</option>';
        echo '</select><p class="resp_text"><span></span><i class="fas fa-spinner fa-spin loader"></i></p>';
    }
}

add_action('manage_checkout_review_posts_custom_column', 'display_status_column', 10, 2);
function enqueue_admin_checkout_review_script_script() {

    if (isset($_GET['post_type']) && $_GET['post_type'] == 'checkout_review') {
        wp_enqueue_script('checkout_review_script', get_stylesheet_directory_uri() . '/assets/js/checkout_review_script.js', array('jquery'), time(), true);
    }
}
add_action('admin_enqueue_scripts', 'enqueue_admin_checkout_review_script_script');
// Handle AJAX request to update post status
function update_review_status() {
    if (isset($_POST['post_id'], $_POST['new_status'])) {
        $post_id = intval($_POST['post_id']);
        $new_status = sanitize_text_field($_POST['new_status']);

        // Update post status
        wp_update_post(array('ID' => $post_id, 'post_status' => $new_status));

        // Optionally, you can return a response
        echo 'Status updated successfully.';
    }else{
		// Optionally, you can return a response
        echo 'Please try again after sometime.';
	}

    wp_die(); // Always include this to terminate the script
}
add_action('wp_ajax_update_review_status', 'update_review_status');

add_action('wp_ajax_create_checkout_review', 'create_checkout_review', 10);
add_action('wp_ajax_nopriv_create_checkout_review', 'create_checkout_review', 10);

function create_checkout_review(){
	extract($_POST);

	 // Create the post
	$post_args = array(
		'post_title'    => $reviewername,
		'post_status'   => 'pending',
		'post_type'     => 'checkout_review',
	);

	$post_id = wp_insert_post($post_args);

	// Update ACF fields
	update_field('rating_number', $reviewrate, $post_id);
	update_field('rating_text', $reviewWrte, $post_id);


	// Return a response (you can customize this based on your needs)
	if ($post_id) {
		echo json_encode(array('success' => true, 'message' => __('Your review has been successfully submitted. It will now undergo the approval process by the admin. Thank you for your contribution!',"fitsmartio_en")));
	} else {
		echo json_encode(array('success' => false, 'message' => __("Something went wrong.","fitsmartio_en")));
	}

	/* if (is_user_logged_in()) { //login check
        $user_id = get_current_user_id();

        // Assuming you have a function to get the user's total order, replace the function below accordingly.
        $total_order = get_user_total_order($user_id);

        if ($total_order > 0) {//ORDER check

			//paste above code here
        } else {
            	echo json_encode(array('success' => false, 'message' => 'You have no orders to review.'));

        }
    } else {
        // User is not logged in, handle accordingly.
        // You may display a message or redirect the user to login.
        	echo json_encode(array('success' => false, 'message' =>  'Please log in to add review.'));
    } */


    // Always exit to avoid extra output
    wp_die();
}

add_filter( 'wfacp_wpml_checkout_page_id', function ( $checkout_id ) {
   $checkout_id=WFACP_Common::get_checkout_page_id();
   $map_checkout = [
      '1539' => [ 'de' => 1358,'nl'=>1519,'fr'=>1524,'pt-pt'=>1529,'befr'=>1534,'en'=>1337,
                  'sv'=>4009, 'no'=>4002, 'fi'=>3994, 'da'=>3929, 'ie'=>1002030], // 10679 is global checkout (english) of base language and 10698 is Spanish (alternate langague) comma saperate can be added more
   ]; // Change the country id's to small letters in case capital Case is not working for you. FOr eg: "it" for italy
	// echo ICL_LANGUAGE_CODE;  //to see current checkout page language please uncomment slashes from starting 'echo'
   if ( class_exists( 'WPML_TM_Records' ) ) {
      if ( isset( $map_checkout[ $checkout_id ] ) && isset( $map_checkout[ $checkout_id ][ ICL_LANGUAGE_CODE ] ) ) {
         $checkout_id = $map_checkout[ $checkout_id ][ ICL_LANGUAGE_CODE ];
      }
   }
// 	 echo ICL_LANGUAGE_CODE;
	//die;
   return $checkout_id;
}, 20);

add_action('wp_ajax_update_checkout', 'update_checkout_callback', 10);
add_action('wp_ajax_nopriv_update_checkout', 'update_checkout_callback', 10);

function update_checkout_callback(){
	$cvalue = $_POST['cvalue'];
	WC()->cart->empty_cart();
	WC()->cart->add_to_cart($cvalue);
	echo json_encode(array('success'=> '200','new_product' => $cvalue));
	die;
}
add_filter( 'woocommerce_adjust_non_base_location_prices', '__return_false' );


add_filter('default_checkout_billing_country', 'change_default_checkout_country',9999);
function change_default_checkout_country($default){

	$my_current_lang = get_language_shortcode();

	//echo "default $default | current_language $current_language ";
	if($my_current_lang == 'en'){
	    $default =  'GB';
	}elseif($my_current_lang == 'nl'){
	    $default =  'NL';
	}elseif($my_current_lang == 'fr'){
	    $default = 'FR';
	}elseif($my_current_lang == 'benl' || $my_current_lang == 'befr'){
	    $default = 'BE';
	}elseif($my_current_lang == 'no'){
	    $default = 'NO';
	}elseif($my_current_lang == 'da'){
	    $default = 'DK';
	}elseif($my_current_lang == 'fi'){
	    $default = 'FI';
	}elseif($my_current_lang == 'sv'){
	    $default = 'SE';
	}elseif($my_current_lang == 'ie'){
	    $default = 'IE';
	}else{
	    $default =  'DE';
	}

	return $default;
}

add_action('wp_footer', 'fts_custom_inline_script_footer');
function fts_custom_inline_script_footer(){
	$logo_site_url = get_site_url();
	$current_language = get_language_shortcode();

	if($current_language == 'en'){
	    $default =  'GB';
	}elseif($current_language == 'nl'){
	    $default =  'NL';
	}elseif($current_language == 'fr'){
	    $default = 'FR';
	}elseif($current_language == 'benl' || $current_language == 'befr'){
		$default = 'BE';
	}elseif($current_language == 'pt-pt'){
	    $default = 'PT';
	}elseif($current_language == 'no'){
	    $default = 'NO';
	}elseif($current_language == 'da'){
	    $default = 'DK';
	}elseif($current_language == 'fi'){
	    $default = 'FI';
	}elseif($current_language == 'sv'){
	    $default = 'SE';
	}elseif($current_language == 'ie'){
	    $default = 'IE';
	}else{
	    $default =  'DE';
	}
	if($current_language != 'en')
	{
		$logo_site_url = $logo_site_url."/$current_language/";
	}
	?>
	<script>
	jQuery('#billing_country').val('<?php echo $default; ?>').change();
	jQuery('.elementor-widget.elementor-widget-theme-site-logo').find("a").attr("href",'<?php echo $logo_site_url; ?>');

	jQuery(document).ready(function($){
	});

	//elementor-widget-theme-site-logo
	</script>
	<?php
}

// Email subject and body language correction
//function wp_mail_language_correction ($args) {
//
//    $message_map = require('email-lang-correction/message-map.php');
//    $subject_map = require('email-lang-correction/subject-map.php');
//    require_once 'email-lang-correction/functions.php';
//
//    $main_language = determine_language($args['to']);
//
//    if(!$main_language) {
//        return;
//    }
//
//    $args['subject'] = correct_subject($args['subject'], $main_language, $subject_map);
//    $args['message'] = correct_message($args['message'], $main_language, $message_map);
//
//
//	$log_data = date('Y-m-d H:i:s') . "\n";
//    $log_data .= "From: " . $args['headers']['From'] . "\n";
//    $log_data .= "To: " . $args['to'] . "\n";
//    $log_data .= "Subject: " . $args['subject'] . "\n";
//    $log_data .= "Message: " . $args['message'] . "\n";
//    $log_data .= "-----------------------------\n";
//
//    $log_file = WP_CONTENT_DIR . '/uploads/mail_log_2.txt';
//    file_put_contents($log_file, $log_data, FILE_APPEND);
//
//
//    return $args;
//}
//
//add_filter('wp_mail', 'wp_mail_language_correction', 0);



add_action('woocommerce_before_checkout_form', function() {
    $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
    echo '<div style="display:none;" id="available-gateways">';
    foreach ($available_gateways as $gateway) {
        echo '<div class="gateway">' . esc_html($gateway->id) . ': ' . esc_html($gateway->title) . '</div>';
    }
    echo '</div>';
});


// Correct IE checkout Postcode label (Eircode)
function enqueue_custom_address_i18n_script() {
	$language = get_language_shortcode();
    if (class_exists( 'WooCommerce' ) and $language == 'ie') {
        wp_enqueue_script( 'wc-address-i18n' ); // Enqueues the script before add custom
        $custom_script = "
            if ( typeof wc_address_i18n_params !== 'undefined' ) {
                wc_address_i18n_params.locale = wc_address_i18n_params.locale.replace('\"label\":\"Eircode\"', '\"label\":\"Postcode\"');
            }
		";
        wp_add_inline_script( 'wc-address-i18n', $custom_script, 'before' );
    }
}
add_action( 'wp_enqueue_scripts', 'enqueue_custom_address_i18n_script' );

//function wp_mail_logging( $phpmailer ) {
//    $current_locale = get_locale();
//
//    $log_data = date('Y-m-d H:i:s') . "\n";
//    $log_data .= "Locale: " . $current_locale . "\n";
//
//    $log_data .= "From: " . $phpmailer->From . "\n";
//    $log_data .= "FromName: " . $phpmailer->FromName . "\n";
//    $log_data .= "To: " . implode(', ', array_column($phpmailer->getToAddresses(), 0)) . "\n";
//    $log_data .= "CC: " . implode(', ', array_column($phpmailer->getCcAddresses(), 0)) . "\n";
//    $log_data .= "BCC: " . implode(', ', array_column($phpmailer->getBccAddresses(), 0)) . "\n";
//    $log_data .= "Subject: " . $phpmailer->Subject . "\n";
//
//    $headers = $phpmailer->getCustomHeaders();
//    if (!empty($headers)) {
//        $log_data .= "Custom Headers:\n";
//        foreach ($headers as $header) {
//            $log_data .= $header[0] . ': ' . $header[1] . "\n";
//        }
//    }
//
//    $log_data .= "Body:\n" . $phpmailer->Body . "\n";
//    $log_data .= "----------------------------------------\n";
//
//    $log_file = WP_CONTENT_DIR . '/uploads/mail_log.txt';
//
//    file_put_contents($log_file, $log_data, FILE_APPEND);
//}
//
//add_action('phpmailer_init', 'wp_mail_logging', 20);

function tt3child_register_acf_blocks() {
    /**
     * We register our block's with WordPress's handy
     * register_block_type();
     *
     * @link https://developer.wordpress.org/reference/functions/register_block_type/
     */
    register_block_type(__DIR__ . '/blocks/benefits-section');
    register_block_type(__DIR__ . '/blocks/ingredients-section');
    register_block_type(__DIR__ . '/blocks/reviews-section');
    register_block_type(__DIR__ . '/blocks/header-section');
    register_block_type(__DIR__ . '/blocks/footer-section');
    register_block_type(__DIR__ . '/blocks/friday-banner');
	register_block_type(__DIR__ . '/blocks/thank-you-section');
}
// Here we call our tt3child_register_acf_block() function on init.
add_action( 'init', 'tt3child_register_acf_blocks' );


//function add_gtm_code_from_acf_in_head(): void {
//    if( have_rows('gtm_scripts', 'option') ){
//        while( have_rows('gtm_scripts', 'option') ) : the_row();
//            if ( get_sub_field('dont_show_on') === false || !in_array(get_the_ID(), get_sub_field('dont_show_on')) ) {
//                echo get_sub_field('gtm_script');
//            }
//        endwhile;
//    }
//}
//
//add_action( 'wp_head', 'add_gtm_code_from_acf_in_head' );
//
//function acf_show_gtm_no_script(): void {
//    if( have_rows('gtm_scripts', 'option') ){
//        while( have_rows('gtm_scripts', 'option') ) : the_row();
//            if ( get_sub_field('dont_show_on') === false || !in_array(get_the_ID(), get_sub_field('dont_show_on')) ) {
//                echo get_sub_field('gtm_noscript');
//            }
//        endwhile;
//    }
//}
//
//add_action( 'wp_body_open', 'acf_show_gtm_no_script' );

function load_acf_option_pages()
{
    $option_pages = require('acf-options-pages/option_pages.php');
    require_once 'acf-options-pages/functions.php';

    init_acf_option_pages_from_array($option_pages);
}

add_action('init', 'load_acf_option_pages');

function init_custom_roles() {
	add_role('read-only', 'Read only', [
		'read' => true,
		'edit_posts' => true,
		'list_users' => true,
		'view_site_health_checks' => true,
		'manage_categories' => true,
		'view_woocommerce_reports' => true,
		'read_private_shop_orders' => true,
		'read_shop_orders' => true,
		'view_woocommerce_orders' => true,
		'read_private_products' => true,
		'read_private_shop_coupons' => true,
		'view_woocommerce_settings' => true,
		'view_admin_dashboard' => true
	]);

	add_role( 'parcelpanel_viewer', 'ParcelPanel Viewer', [
		'read' => true,
		'manage_woocommerce' => true, // Доступ к ParcelPanel
	]);
}

add_action('init', 'init_custom_roles');

function hide_menus_for_read_only_roles() {
	$user = wp_get_current_user();

	/* Only dashboard and parcelpanel menus for parcelpanel_viewer role */
	if (in_array('parcelpanel_viewer', $user->roles)) {
		global $menu;
		foreach ($menu as $key => $item) {
			if ($item[2] !== 'pp-admin' && $item[2] !== 'index.php') {
				unset($menu[$key]);
			}
		}
	}
}

add_action('admin_menu', 'hide_menus_for_read_only_roles', 999);

function add_lazy_loading_to_content_images($content) {
    if (!is_checkout()) {
        return $content;
    }

    return preg_replace('/<img(?![^>]*loading=)/i', '<img loading="lazy"', $content);
}
add_filter('the_content', 'add_lazy_loading_to_content_images', PHP_INT_MAX);

function add_lazy_loading_to_shortcode_output($output) {
    if (strpos($output, '<img') !== false) { // Only modify output containing images
        $output = preg_replace('/<img(?![^>]*loading=)/i', '<img loading="lazy"', $output);
    }
    return $output;
}
add_filter('do_shortcode_tag', 'add_lazy_loading_to_shortcode_output', PHP_INT_MAX, 3);

function add_lazy_loading_to_funnelkit_payment_icons($icon, $gateway_id) {
    if (!is_checkout()) {
        return $icon;
    }

    return preg_replace('/<img(?![^>]*loading=)/i', '<img loading="lazy"', $icon);
}
add_filter('woocommerce_gateway_icon', 'add_lazy_loading_to_funnelkit_payment_icons', 10, 2);

//function disable_elementor_scripts() {
//    if (is_checkout()) {
//        wp_dequeue_script('elementor-frontend');
//        wp_dequeue_script('elementor-frontend');
//        wp_dequeue_script('elementor-common');
//        wp_dequeue_script('hello-theme-frontend');
//        wp_dequeue_style('elementor-frontend');
//        wp_deregister_style('elementor-frontend');
//        wp_dequeue_style('hello-elementor');
//        wp_dequeue_style('hello-elementor-theme-style');
//        wp_dequeue_style('hello-elementor-header-footer');
//        wp_dequeue_style('elementor-post-52');
//        wp_dequeue_style('elementor-post-7');
//        wp_dequeue_style('elementor-post-540');
//    }
//}
//add_action('wp_enqueue_scripts', 'disable_elementor_scripts', PHP_INT_MAX);