<?php

require get_stylesheet_directory() . '/includes/checkout.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()
{
    if (is_checkout()) {
        $_SESSION['cid'] = $_SERVER['QUERY_STRING'];
    }
    if (is_wc_endpoint_url('order-received') && isset($_GET['key'])) {
        return;
    }

    if (is_checkout() && WC()->cart->is_empty() && empty($_GET['id'])) {
        $lang = get_language_shortcode();
        $variation = get_query_var("variation");
        $set = ($variation === 'v2') ? 'LCTC' : 'HCTC';

        $config = require get_stylesheet_directory() . '/includes/config/defaultCheckoutProducts.php';
        $product_id = $config[$set][$lang] ?? $config[$set]['de'] ?? null; // de - in euro

        if ($product_id && wc_get_product($product_id)) {
            WC()->cart->add_to_cart($product_id);
        }
    }
}
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

    'checkout_reviews_v4' => 'checkout_reviews_v4.php',

    '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 = pll__("Express Checkout");
	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' );

function v4_products_callback() {
    ob_start();
    include get_stylesheet_directory().'/includes/shortcode/v4_products.php';
    $content = ob_get_clean();
    return $content;
}
add_shortcode('v4_products', 'v4_products_callback');

function v4_checkout_callback() {
    ob_start();
    include get_stylesheet_directory().'/includes/shortcode/v4_checkout.php';
    $content = ob_get_clean();
    return $content;
}
add_shortcode('v4_checkout', 'v4_checkout_callback');

function v5_products_callback() {
    ob_start();
    include get_stylesheet_directory().'/includes/shortcode/v5_products.php';
    $content = ob_get_clean();
    return $content;
}
add_shortcode('v5_products', 'v5_products_callback');

function v5_checkout_callback() {
    ob_start();
    include get_stylesheet_directory().'/includes/shortcode/v5_checkout.php';
    $content = ob_get_clean();
    return $content;
}
add_shortcode('v5_checkout', 'v5_checkout_callback');

function v5_checkout_reviews_callback() {
    ob_start();
    include get_stylesheet_directory().'/includes/shortcode/v5_checkout_reviews.php';
    $content = ob_get_clean();
    return $content;
}
add_shortcode('v5_checkout_reviews', 'v5_checkout_reviews_callback');

// 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 ) {
	if ( ! function_exists( 'pll_current_language' ) ) {
		return $checkout_id;
	}

	$language = pll_current_language( 'locale' );

	$map_checkout = [
		'3007015' => [
			'de_DE'    => 3007115,
			'nl_NL'    => 3007136,
			'fr_FR'    => 3007122,
			'pt_PT' => 1529,
			'be_FR'  => 3007130,
			'be_NL'  => 3007140,
			'en_US'    => 3007015,
			'sv_SE'    => 4000182,
			'nb_NO'    => 4002,
			'fi'    => 4000201,
			'da_DK'    => 4000180,
			'ie_IE'    => 3007106
		],
	];

	if ( isset( $map_checkout[ $checkout_id ] ) && isset( $map_checkout[ $checkout_id ][ $language ] ) ) {
		$checkout_id = $map_checkout[ $checkout_id ][ $language ];
		$ins=WFACP_Common::remove_actions( 'template_redirect', 'PLL_Canonical', 'check_canonical_url' );
	}

	return $checkout_id;
}, 200);

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'];

    $_pf = new WC_Product_Factory();
    $product = $_pf->get_product($cvalue);

    WC()->cart->empty_cart();
    WC()->cart->add_to_cart($cvalue);
    echo json_encode(array('success' => '200', 'new_product' => $cvalue, 'product_price' => $product->get_price()));
    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/reviews-v4-section');
    register_block_type(__DIR__ . '/blocks/header-section');
    register_block_type(__DIR__ . '/blocks/footer-section');
	register_block_type(__DIR__ . '/blocks/footer-v4-section');
    register_block_type(__DIR__ . '/blocks/friday-banner');
	register_block_type(__DIR__ . '/blocks/thank-you-section');
	register_block_type(__DIR__ . '/blocks/v5-header-section');
	register_block_type(__DIR__ . '/blocks/v5-customers-section');
	register_block_type(__DIR__ . '/blocks/v5-benefits-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 redirect_404_in_shop() {
    if (is_404() && strpos($_SERVER['REQUEST_URI'], '/shop/') === 0) {
        wp_redirect('/', 301);
        exit();
    }
}
add_action('template_redirect', 'redirect_404_in_shop');

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_cors_headers( $headers ) {
    $headers['Access-Control-Allow-Origin'] = '*';
    $headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE';
    $headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization';
    return $headers;
}
add_filter( 'wp_headers', 'add_cors_headers' );

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

    return str_replace('<img', '<img loading="lazy" ', $content);
}
add_filter('the_content', 'add_lazy_loading_to_content_images', PHP_INT_MAX);

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

add_action('wp_head', function () {
    if ( ! str_contains($_SERVER['REQUEST_URI'], 'order-confirmed') ) {
        return;
    }
    ?>
    <script>
        (function() {
            const { href } = window.location;
            if ((href.includes('#038;') || href.includes('&#038;')) && !href.includes('ampfix=1')) {
                let fixed = href.replace(/#038;|&#038;/g, '&');
                fixed += (fixed.includes('?') ? '&' : '?') + 'ampfix=1';
                window.location.replace(fixed);
            }
        })();
    </script>
    <?php
});

if ( function_exists( 'pll_register_string' ) ) add_action( 'admin_init', 'pll_tc_strings_setup' );
function pll_tc_strings_setup() {
	$groupedStrings = require('includes/polylang/strings.php');

	foreach ($groupedStrings as $group => $strings) {
		foreach ($strings as $name => $string) {
			pll_register_string($name, $string, $group);
		}
	}
}


add_filter('wfacp_smart_button_legend_title', function () {
    return pll__('Express Checkout');
});

add_filter('wfacp_smart_button_or_text', function () {
    return pll__('OR');
});

//add_filter('woocommerce_checkout_coupon_message', function () {
//    return pll__('Have a coupon? Click here to enter your code');
//});

add_filter( 'woocommerce_checkout_coupon_message', function () {
   return '<a class="wfacp_main_showcoupon wfacp_showcoupon">' . pll__( 'Have a coupon?' ) . ' ' . pll__( 'Click here to enter your code' ) . '</a>' ;
});

function polylang_support_legacy( $translated_text, $text, $domain ) {
    if ($domain == 'integration-adyen-woocommerce') {
        return pll__($text);
    }

	return $translated_text;
}
add_filter( 'gettext', 'polylang_support_legacy', 20, 3 );

function load_hide_buttons_for_adyen_payment_methods() {
    wp_enqueue_script('google_pay_hide_buttons', get_stylesheet_directory_uri() . '/assets/js/woosa_hide_buttons.js', [ 'jquery' ], '1.0', true);
}

add_action('wp_enqueue_scripts', 'load_hide_buttons_for_adyen_payment_methods');

add_filter( 'woocommerce_get_return_url', 'correct_woo_redirect_url', 10, 2 );

function correct_woo_redirect_url( $return_url, $order ){
    if (!$order instanceof WC_Order) {
        return $return_url;
    }

    $lang = function_exists('pll_get_post_language')
        ? pll_get_post_language( $order->get_id(), 'slug' )
        : false;

    if ($lang && function_exists( 'PLL' ) && ! str_contains( $return_url, "/{$lang}/" )) {
        return PLL()->links_model->add_language_to_link( $return_url, $lang );
    }

    return $return_url;
}

function polylang_support_mollie($translated_text, $text, $domain) {
    if ('mollie-payments-for-woocommerce' == $domain) {
        return pll__($text);
    }
    return $translated_text;
}
add_filter( 'gettext', 'polylang_support_mollie', 20, 3 );

function cut_first_thankyou($url)
{
    $hasWfocu = str_contains($url, 'wfocu-si=');
    if ($hasWfocu) {
        $url = remove_query_arg('wfocu-si', $url);
        $url = add_query_arg('nt', '1', $url);
    }
    return $url;
}

add_filter('woocommerce_api_request_url', 'cut_first_thankyou', PHP_INT_MAX);
add_filter('woocommerce_get_return_url', 'cut_first_thankyou', PHP_INT_MAX, 2);
add_filter('woocommerce_get_checkout_order_received_url', 'cut_first_thankyou', PHP_INT_MAX, 2);

// Change the order of payment methods on FR checkouts, move Card to the top
add_filter('woocommerce_available_payment_gateways', 'setAdyenCardFirstForFr', 20);
function setAdyenCardFirstForFr($gateways)
{
    if (is_admin() || !is_checkout()) {
        return $gateways;
    }

    $lang = function_exists('pll_current_language')
        ? pll_current_language()
        : (defined('ICL_LANGUAGE_CODE') ? ICL_LANGUAGE_CODE : '');

    $frenchLocales = ['fr', 'fr_FR'];

    if (in_array($lang, $frenchLocales, true)) {
        $paymentName = 'woosa_adyen_card';
        if (isset($gateways[$paymentName])) {
            $firstGateway = [$paymentName => $gateways[$paymentName]];
            unset($gateways[$paymentName]);
            $gateways = array_merge($firstGateway, $gateways);
        }
    }
    return $gateways;
}