<?php

/**
 * Theme setup.
 */
function tailpress_setup() {
	add_theme_support( 'title-tag' );

	register_nav_menus(
		array(
			'primary' => __( 'Primary Menu', 'tailpress' ),
		)
	);

	add_theme_support(
		'html5',
		array(
			'search-form',
			'comment-form',
			'comment-list',
			'gallery',
			'caption',
		)
	);

    add_theme_support( 'custom-logo' );
	add_theme_support( 'post-thumbnails' );

	add_theme_support( 'align-wide' );
	add_theme_support( 'wp-block-styles' );

	add_theme_support( 'responsive-embeds' );

	add_theme_support( 'editor-styles' );
	add_editor_style( 'css/editor-style.css' );
}

add_action( 'after_setup_theme', 'tailpress_setup' );

/**
 * Enqueue theme assets.
 */
function tailpress_enqueue_scripts() {
	$theme = wp_get_theme();

	wp_enqueue_style( 'tailpress', tailpress_asset( 'css/app.css' ), array(), '0.3' );
	wp_enqueue_script( 'tailpress', tailpress_asset( 'js/app.js' ), array(), '0.3' );
}

add_action( 'wp_enqueue_scripts', 'tailpress_enqueue_scripts' );

/**
 * Get asset path.
 *
 * @param string  $path Path to asset.
 *
 * @return string
 */
function tailpress_asset( $path ) {
	if ( wp_get_environment_type() === 'production' ) {
		return get_stylesheet_directory_uri() . '/' . $path;
	}

	return add_query_arg( 'time', time(),  get_stylesheet_directory_uri() . '/' . $path );
}

/**
 * Adds option 'li_class' to 'wp_nav_menu'.
 *
 * @param string  $classes String of classes.
 * @param mixed   $item The current item.
 * @param WP_Term $args Holds the nav menu arguments.
 *
 * @return array
 */
function tailpress_nav_menu_add_li_class( $classes, $item, $args, $depth ) {
	if ( isset( $args->li_class ) ) {
		$classes[] = $args->li_class;
	}

	if ( isset( $args->{"li_class_$depth"} ) ) {
		$classes[] = $args->{"li_class_$depth"};
	}

	return $classes;
}

add_filter( 'nav_menu_css_class', 'tailpress_nav_menu_add_li_class', 10, 4 );

/**
 * Adds option 'submenu_class' to 'wp_nav_menu'.
 *
 * @param string  $classes String of classes.
 * @param mixed   $item The current item.
 * @param WP_Term $args Holds the nav menu arguments.
 *
 * @return array
 */
function tailpress_nav_menu_add_submenu_class( $classes, $args, $depth ) {
	if ( isset( $args->submenu_class ) ) {
		$classes[] = $args->submenu_class;
	}

	if ( isset( $args->{"submenu_class_$depth"} ) ) {
		$classes[] = $args->{"submenu_class_$depth"};
	}

	return $classes;
}

add_filter( 'nav_menu_submenu_css_class', 'tailpress_nav_menu_add_submenu_class', 10, 3 );


function get_current_room() {
    return pll_current_language() === 'gym' ? 'gym' : 'fitness';
}

$modal_file = get_template_directory() . '/template-parts/la-components/functions/modals.php';
$block_file = get_template_directory() . '/template-parts/la-components/functions/blocks.php';
$forms_file = get_template_directory() . '/template-parts/la-components/functions/forms.php';
$breadcrumbs_file = get_template_directory() . '/template-parts/la-components/functions/breadcrumbs.php';

if (file_exists($breadcrumbs_file)) {
    require_once $breadcrumbs_file;
}
if (file_exists($block_file)) {
    require_once $block_file;
}
if (file_exists($modal_file)) {
    require_once $modal_file;
}

if (file_exists($forms_file)) {
    require_once $forms_file;
}
function enqueue_swiper_assets() {
    wp_enqueue_style(
        'swiper-css',
        'https://cdnjs.cloudflare.com/ajax/libs/Swiper/8.4.7/swiper-bundle.min.css',
        array(),
        '8.4.7'
    );

    wp_enqueue_script(
        'swiper-js',
        'https://cdnjs.cloudflare.com/ajax/libs/Swiper/8.4.7/swiper-bundle.min.js',
        array(),
        '8.4.7',
        true
    );
}

add_action('wp_enqueue_scripts', 'enqueue_swiper_assets');

add_action('admin_enqueue_scripts', 'enqueue_swiper_assets');

add_action('enqueue_block_editor_assets', 'enqueue_swiper_assets');

function display_icon($field_name)
{
    $icon = get_field($field_name, 'option');
    $icon_id = isset($icon['icon_url']) ? $icon['icon_url'] : 0;
    if ($icon_id) {
        echo wp_get_attachment_image($icon_id, 'full');
    }
}

function wider_language_cols() {
    echo '<style>
    .wp-list-table td[class*=column-language_], 
    .wp-list-table th[class*=column-language_] {
        width: 3em !important;
    }
    </style>';
}
add_action('admin_head', 'wider_language_cols');

function get_simple_menu_items($menu_name = 'Шапка сайта') {
    $menu = wp_get_nav_menu_object($menu_name);

    if (!$menu) {
        return array();
    }

    $menu_items = wp_get_nav_menu_items($menu->term_id);
    $current_lang = function_exists('pll_current_language') ? pll_current_language() : null;

    if (!$menu_items) {
        return array();
    }

    $clean_title = function($title) {
        return trim(preg_replace('/\s*\([^)]*\)/', '', $title));
    };

    $simple_items = array();

    foreach ($menu_items as $item) {
        if ($current_lang === 'gym' && $item->type === 'post_type_archive' && $item->object === 'training') {
            continue;
        }

        $url = $item->url;
        $title = $clean_title($item->title);

        if ($current_lang && $item->object == 'page' && function_exists('pll_get_post')) {
            $translated_page_id = pll_get_post($item->object_id, $current_lang);
            if ($translated_page_id) {
                $url = get_permalink($translated_page_id);
                $translated_title = get_the_title($translated_page_id);
                if ($translated_title) {
                    $title = $clean_title($translated_title);
                }
            }
        }

        $simple_items[] = array(
            'title' => $title,
            'url' => $url,
            'id' => $item->ID
        );
    }

    return $simple_items;
}

function add_dark_class_to_editor() {
    $screen = get_current_screen();
    if (!$screen || !in_array($screen->base, ['post', 'page'])) {
        return;
    }
    $current_lang = '';

    if (isset($_GET['post'])) {
        $current_lang = pll_get_post_language($_GET['post']);
    } elseif (isset($_GET['lang'])) {
        $current_lang = $_GET['lang'];
    } else {
        $current_lang = pll_current_language();
    }

    if ($current_lang === 'gym') {
        ?>
        <script>
            jQuery(document).ready(function($) {
                $('#editor').addClass('dark');
            });
        </script>
        <?php
    }
}
add_action('admin_head', 'add_dark_class_to_editor');


function create_archive_acf_pages() {
    if (!function_exists('acf_add_options_sub_page')) {
        return;
    }

    // Получаем все кастомные типы записей с архивами
    $post_types = get_post_types(array(
        'public' => true,
        'has_archive' => true,
        '_builtin' => false
    ), 'objects');

    foreach ($post_types as $post_type) {
        acf_add_options_sub_page(array(
            'page_title' => 'Настройки страницы ' . $post_type->labels->name,
            'menu_title' => 'Настройки страницы',
            'menu_slug' => $post_type->name . '-archive-settings',
            'parent_slug' => 'edit.php?post_type=' . $post_type->name,
            'capability' => 'edit_posts',
        ));
    }
}
add_action('acf/init', 'create_archive_acf_pages');


function register_archive_acf_fields() {
    if (!function_exists('acf_add_local_field_group')) {
        return;
    }


    $languages = get_archive_languages();

    $post_types = get_post_types(array(
        'public' => true,
        'has_archive' => true,
        '_builtin' => false
    ), 'objects');

    foreach ($post_types as $post_type) {
        register_fields_for_archive($post_type, $languages);
    }
}
add_action('acf/init', 'register_archive_acf_fields');

function get_archive_languages() {
    if (function_exists('pll_languages_list')) {
        $languages = array();
        $pll_languages = pll_languages_list(array('fields' => array()));

        foreach ($pll_languages as $lang) {
            $languages[$lang->slug] = $lang->name;
        }

        return $languages;
    }

    return array(
        'gym' => 'gym зал',
        'fitness' => 'fitness зал'
    );
}

function register_fields_for_archive($post_type, $languages) {
    $post_type_name = $post_type->name;
    $post_type_label = $post_type->labels->name;

    $fields = array();

    foreach ($languages as $lang_code => $lang_name) {
        $fields[] = array(
            'key' => 'field_tab_' . $post_type_name . '_' . $lang_code,
            'label' => $lang_name,
            'type' => 'tab',
            'placement' => 'top',
        );

        // Поля для этого языка
        $fields[] = array(
            'key' => 'field_' . $post_type_name . '_h1_text_' . $lang_code,
            'label' => 'Заголовок H1',
            'name' => $post_type_name . '_h1_text_' . $lang_code,
            'type' => 'wysiwyg',
            'toolbar' => 'basic',
            'media_upload' => 0,
            'delay' => 0,
        );

        $fields[] = array(
            'key' => 'field_' . $post_type_name . '_subtitle_' . $lang_code,
            'label' => 'Подзаголовок',
            'name' => $post_type_name . '_subtitle_' . $lang_code,
            'type' => 'textarea',
            'rows' => 3,
        );

        if ($post_type_name === 'trainer') {
            $fields[] = array(
                'key' => 'field_' . $post_type_name . '_team_photo_' . $lang_code,
                'label' => 'Фото команды',
                'name' => $post_type_name . '_team_photo_' . $lang_code,
                'type' => 'image',
                'return_format' => 'array',
                'preview_size' => 'medium',
            );

            $fields[] = array(
                'key' => 'field_' . $post_type_name . '_description_' . $lang_code,
                'label' => 'Описание страницы',
                'name' => $post_type_name . '_description_' . $lang_code,
                'type' => 'textarea',
                'rows' => 5,
            );
        }
    }

    acf_add_local_field_group(array(
        'key' => 'group_' . $post_type_name . '_archive',
        'title' => 'Настройки страницы ' . $post_type_label,
        'fields' => $fields,
        'location' => array(
            array(
                array(
                    'param' => 'options_page',
                    'operator' => '==',
                    'value' => $post_type_name . '-archive-settings',
                ),
            ),
        ),
    ));
}

function get_archive_field($post_type, $field_name, $default = '') {
    if (!function_exists('get_field')) {
        return $default;
    }

    $current_lang = function_exists('pll_current_language') ? pll_current_language() : 'ru';
    $field_key = $post_type . '_' . $field_name . '_' . $current_lang;

    $value = get_field($field_key, 'option');

    return $value ? $value : $default;
}



function checkTelForSpam($phone_value)
{

    $clean_phone = preg_replace('/\D/', '', $phone_value);


    if (substr($clean_phone, 0, 1) === '8') {
        $clean_phone = '7' . substr($clean_phone, 1);
    }


    if (strlen($clean_phone) !== 11 || substr($clean_phone, 0, 1) !== '7') {
        return false;
    }

    return true;
}

function maspik_custom_validate_fluentforms_tel($errorMessage, $field, $formData, $fields, $form)
{
    $fieldName = $field['name'];

    if (empty($formData[$fieldName])) {
        return $errorMessage;
    }

    $field_value = $formData[$fieldName];

    $valid = checkTelForSpam($field_value);

    if (!$valid) {
        $errorMessage = "Введите корректный номер телефона";
    }

    return $errorMessage;
}

add_filter('fluentform/validate_input_item_phone', 'maspik_custom_validate_fluentforms_tel', 10, 5);



function cookie_popup_enqueue_scripts() {
    wp_enqueue_script('jquery');

    $custom_css = "
        .page-block-shadow {
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12), 0 2px 6px rgba(0, 0, 0, 0.08);
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
        }
        
        .red-button-shadow {
            box-shadow: 0 4px 16px rgba(224, 30, 46, 0.25), 0 2px 4px rgba(224, 30, 46, 0.1);
            transition: all 0.2s ease;
        }
        
        .red-button-shadow:hover {
            box-shadow: 0 6px 20px rgba(224, 30, 46, 0.35), 0 3px 6px rgba(224, 30, 46, 0.15);
            transform: translateY(-1px);
        }
        
        .red-button-shadow:active {
            transform: translateY(0);
            box-shadow: 0 2px 8px rgba(224, 30, 46, 0.3);
        }
    ";
    wp_add_inline_style('wp-block-library', $custom_css);
}
add_action('wp_enqueue_scripts', 'cookie_popup_enqueue_scripts');

function cookie_popup_html() {
    ?>
    <div id="cookiePopup" class="fixed bottom-[16px] left-[16px] right-[16px] min-[768px]:left-auto min-[768px]:right-[16px] max-[480px]:left-[8px] max-[480px]:right-[8px] max-[480px]:bottom-[8px] p-[24px] max-[480px]:p-[16px] rounded-[1.6rem] page-block-shadow z-[9999] transform translate-y-[100%] opacity-[0] transition-all duration-[500ms] ease-out">
        <div class="mb-[16px] text-[14px] leading-[1.5]">
            Мы используем файлы cookie  чтобы сайт работал быстрее.
        </div>
        <button
                id="acceptCookiesBtn"
                class="!max-w-fit h-[40px] max-[768px]:text-[16px] cursor-pointer mx-auto px-[14px] !no-underline transition red-gradient-hover gap-[12px] w-full rounded-[90px] flex items-center justify-center "
        >
            <span class="max-[768px]:text-[16px] font-[600] text-[18px] leading-[195%] text-[#f8f8f8]">Хорошо</span>
        </button>
    </div>

    <script>
        jQuery(document).ready(function($) {
            checkCookieConsent();

            $('#acceptCookiesBtn').on('click', function() {
                acceptCookies();
            });

            function checkCookieConsent() {
                const consent = localStorage.getItem('cookieConsent');
                if (!consent) {
                    setTimeout(showCookiePopup, 500);
                }
            }

            function showCookiePopup() {
                $('#cookiePopup').removeClass('translate-y-[100%] opacity-[0]').addClass('translate-y-[0] opacity-[100]');
            }

            function acceptCookies() {
                $('#cookiePopup').addClass('translate-y-[100%] opacity-[0]').removeClass('translate-y-[0] opacity-[100]');
                localStorage.setItem('cookieConsent', 'accepted');
                enableAnalytics();
            }

            function enableAnalytics() {

            }
        });
    </script>
    <?php
}
add_action('wp_footer', 'cookie_popup_html');
?>