<?php
global $adforest_theme;
$site_logo = isset($adforest_theme['sb_site_logo']['url']) ? $adforest_theme['sb_site_logo']['url'] : ADFOREST_IMAGE_PATH . "/adt-logo.png";
$sb_sign_in_page = isset($adforest_theme['sb_sign_in_page']) ? $adforest_theme['sb_sign_in_page'] : "";
$sb_sign_up_page = isset($adforest_theme['sb_sign_up_page']) ? $adforest_theme['sb_sign_up_page'] : "";
$ad_in_menu_text = isset($adforest_theme['ad_in_menu_text']) ? $adforest_theme['ad_in_menu_text'] : "";
$sb_post_ad_page = isset($adforest_theme['sb_post_ad_page']) ? $adforest_theme['sb_post_ad_page'] : "";
$responsive_logo = isset($adforest_theme['sb_site_logo_mobile']['url']) ? $adforest_theme['sb_site_logo_mobile']['url'] : ADFOREST_IMAGE_PATH . "/adt-logo.png";
$home_page_logo = isset($adforest_theme['sb_home_logo']['url']) ? $adforest_theme['sb_home_logo']['url'] : ADFOREST_IMAGE_PATH . "/adt-logo.png";
$user_id = get_current_user_id();

$is_sticky_header = isset($adforest_theme['sb_sticky_header']) ? $adforest_theme['sb_sticky_header'] : '';
$sticky_class = "";
if ($is_sticky_header == '1') {
    $sticky_class = "";
}

$sb_profile_page = isset($adforest_theme['sb_profile_page']) ? $adforest_theme['sb_profile_page'] : '';

$topbar_cats = $adforest_theme['adforest_header_ad_cats_selection'] ?? [];
$center_index = floor((count($topbar_cats) - 1) / 2);
$default_cat_id = isset($topbar_cats[$center_index]) ? intval($topbar_cats[$center_index]) : 0;
$default_slug = '';

if ($default_cat_id) {
    $default_term = get_term($default_cat_id, 'ad_cats');
    if ($default_term && !is_wp_error($default_term)) {
        $default_slug = $default_term->slug;
    }
}
?>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        const params = new URLSearchParams(window.location.search);

        const defaultCatId = <?php echo json_encode( (int) $default_cat_id ); ?>;
        const defaultSlug = <?php echo json_encode( sanitize_title( $default_slug ) ); ?>;
        if (!params.has('cat_id') && defaultCatId && defaultSlug) {
            params.set('cat_id', defaultCatId);
            const newUrl = `${window.location.pathname}?${params.toString()}`;
            window.history.pushState({}, '', newUrl);

            const tabTriggerEl = document.querySelector(`#pills-${defaultSlug}-tab`);
            if (tabTriggerEl) {
                tabTriggerEl.click();
            }
            if (tabTriggerEl) {
                tabTriggerEl.classList.add('active');
                tabTriggerEl.setAttribute('aria-selected', 'true');

                document.querySelectorAll('.nav-link').forEach(el => {
                    if (el !== tabTriggerEl) {
                        el.classList.remove('active');
                        el.setAttribute('aria-selected', 'false');
                    }
                });

                const tabContentEl = document.querySelector(`#pills-${defaultSlug}`);
                if (tabContentEl) {
                    document.querySelectorAll('.tab-pane').forEach(el => el.classList.remove('show', 'active'));
                    tabContentEl.classList.add('show', 'active');
                }
            }
        }
    });
</script>
<?php
$ad_types = function_exists('adforest_get_ad_taxonomy_callback') ? adforest_get_ad_taxonomy_callback('ad_type') : '';
$locations = function_exists('adforest_get_ad_taxonomy_callback') ? adforest_get_ad_taxonomy_callback('ad_country') : '';
?>

<div class="adt-top-tabs-header <?php echo esc_attr($sticky_class); ?>">
    <div class="container">
        <div class="tabs-container">
            <div class="logo" data-mobile-logo="<?php echo esc_url($responsive_logo) ?>"
                 data-sticky-logo="<?php echo esc_url($responsive_logo) ?>" <?php echo is_user_logged_in() ? 'style="margin-right: 0px !important"' : ""; ?> >
                <a href="<?php echo esc_url(home_url('/')); ?>"><img src="<?php echo esc_url($site_logo); ?>"
                                                            alt="<?php echo esc_attr__('logo', 'adforest') ?>"></a>
            </div>
            <div class="tabs-wrapper">
                <?php if (!empty($topbar_cats)) : ?>
                    <ol class="nav nav-pills" id="pills-tab" role="tablist">
                        <?php foreach ($topbar_cats as $cat_id) :
                            $taxonomy = get_term($cat_id, 'ad_cats');

                            if (!is_wp_error($taxonomy) && $taxonomy) :
                                $taxonomy_image = get_option('adforest_taxonomy_image' . $taxonomy->term_id);
                                $current_cat_id = isset($_GET['cat_id']) ? intval($_GET['cat_id']) : 0;
                                $is_active = ($current_cat_id == $cat_id) ? 'active' : '';
                                ?>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link <?php echo esc_attr($is_active); ?>"
                                            id="pills-<?php echo esc_attr($taxonomy->slug); ?>-tab"
                                            data-bs-toggle="pill"
                                            data-bs-target="#pills-<?php echo esc_attr($taxonomy->slug); ?>"
                                            type="button" role="tab"
                                            aria-controls="pills-<?php echo esc_attr($taxonomy->slug); ?>"
                                            aria-selected="<?php echo esc_attr( $current_cat_id === $cat_id ? 'true' : 'false' ); ?>"
                                            onclick="setCategory(<?php echo esc_js($cat_id); ?>)">
                                        <div class="d-flex justify-content-center align-items-center">
                                            <img style="width: 18px; margin-right: 5px"
                                                 src="<?php echo esc_url($taxonomy_image); ?>"
                                                 alt="<?php echo esc_attr($taxonomy->name); ?>"/>
                                            <span><?php echo esc_html($taxonomy->name); ?></span>
                                        </div>
                                    </button>
                                </li>
                            <?php endif; endforeach; ?>
                    </ol>
                <?php endif; ?>

                <div class="tab-content" id="pills-tabContent">
                    <form action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" method="GET"
                          class="adt-hero-search-tabs">
                        <?php
                        // Preserve cat_id if it exists
                        if (isset($_GET['cat_id'])) : ?>
                            <input type="hidden" name="cat_id" value="<?php echo esc_attr($_GET['cat_id']); ?>">
                        <?php endif; ?>

                        <div class="search-filters-bar">
                            <div class="filter-box">
                                <label for="title"><?php echo esc_html__("Explore", "adforest"); ?></label>
                                <input type="text" id="title" name="title"
                                       placeholder="<?php echo esc_attr__('What Are You Looking for...', 'adforest'); ?>"
                                       value="<?php echo esc_attr(isset($_GET['title']) ? $_GET['title'] : ''); ?>">
                            </div>
                            <div class="filter-box type-box">
                                <label for="type"><?php echo esc_html__("Type", "adforest"); ?></label>
                                <select class="default-select" id="type" name="type">
                                    <option value=""><?php echo esc_html__("Select an Option", "adforest"); ?></option>
                                    <?php
                                    if (is_array($ad_types)) :
                                        foreach ($ad_types as $type) :
                                            $selected = (isset($_GET['type']) && $_GET['type'] === $type->name) ? 'selected' : '';
                                            ?>
                                            <option value="<?php echo esc_attr($type->name); ?>" <?php echo esc_attr($selected); ?>>
                                                <?php echo esc_html($type->name); ?>
                                            </option>
                                        <?php
                                        endforeach;
                                    endif;
                                    ?>
                                </select>
                            </div>
                            <div class="filter-box type-box">
                                <label for="location"><?php echo esc_html__("Location", "adforest"); ?></label>
                                <select class="default-select" id="location" name="location">
                                    <option value=""><?php echo esc_html__("Select an Option", "adforest"); ?></option>
                                    <?php
                                    if (is_array($locations)) :
                                        foreach ($locations as $location) :
                                            $selected = (isset($_GET['location']) && $_GET['location'] === $location->name) ? 'selected' : '';
                                            ?>
                                            <option value="<?php echo esc_attr($location->name); ?>" <?php echo esc_attr($selected); ?>>
                                                <?php echo esc_html($location->name); ?>
                                            </option>
                                        <?php
                                        endforeach;
                                    endif;
                                    ?>
                                </select>
                            </div>
                            <button class="search-button" type="submit">
                                <i class="fas fa-search"></i><?php echo esc_html__("Search", "adforest"); ?>
                            </button>
                        </div>
                        <?php echo adforest_search_params('title', 'type', 'location'); ?>
                    </form>
                </div>
            </div>

            <script>
                function setCategory(catId) {
                    const urlParams = new URLSearchParams(window.location.search);

                    urlParams.set('cat_id', catId);

                    const newUrl = `${window.location.pathname}?${urlParams.toString()}`;

                    window.location.href = newUrl;
                }
            </script>
            <div class="buttons-box">
                <?php if (!is_user_logged_in()) { ?>
                    <a href="<?php echo esc_url(get_the_permalink($sb_sign_in_page), 'adforest') ?>" class="sign-in"><i
                                class="fas fa-sign-in-alt"></i><?php echo esc_html__("Sign in", "adforest"); ?></a>
                    <a href="<?php echo esc_url(get_the_permalink($sb_sign_up_page), 'adforest') ?>" class="sign-up"><i
                                class="fas fa-sign-in-alt"></i><?php echo esc_html__("Register", "adforest"); ?></a>
                <?php } else { ?>
                    <div class="adt-user-avatar">
                        <a href="javascript:void(0)" data-bs-toggle="tooltip" data-bs-placement="top"
                           class="login-user">
                            <?php
                            $dp = '';
                            $unread_msgs = ADFOREST_MESSAGE_COUNT;
                            if (function_exists('adforest_get_user_dp')) {
                                $dp = adforest_get_user_dp($user_id);
                            }
                            ?>
                            <img class="img-circle" src="<?php echo esc_url($dp); ?>"
                                 alt="<?php esc_html__('user prfile picture', 'adforest'); ?>" width="32" height="32"></a>

                        <ul class="dropdown-user-login">
                            <li><a class="user_login_dropdown_text"
                                   href="<?php echo get_the_permalink($sb_profile_page); ?>"><i
                                            class="fa fa-user"></i> <?php echo esc_html__("Profile", "adforest"); ?></a></li>
                            <?php echo apply_filters('adforest_vendor_dashboard_profile', '', $user_id); ?>
                            <?php
                            if (isset($adforest_theme['communication_mode']) && ($adforest_theme['communication_mode'] == 'both' || $adforest_theme['communication_mode'] == 'message')) {
                                ?>
                                <li><a class="user_login_dropdown_text  "
                                       href="<?php echo adforest_set_url_param(trailingslashit(get_the_permalink($sb_profile_page)), 'page_type', 'msg'); ?>"><i
                                                class="fa fa-envelope"></i> <?php echo esc_html__('Messages', 'adforest'); ?>
                                        <span
                                                class="badge bg-danger"><?php echo esc_html(adforest_get_message_count()); ?></span></a>
                                </li>
                                <?php
                            }
                            if (isset($adforest_theme['sb_cart_in_menu']) && $adforest_theme['sb_cart_in_menu']) {
                                global $woocommerce;
                                ?>
                                <li><a class="user_login_dropdown_text" href="<?php echo wc_get_cart_url(); ?>"><i
                                                class="fa fa-shopping-cart"></i> <?php echo esc_html__('Cart', 'adforest'); ?>
                                        <span
                                                class="badge bg-danger"><?php echo adforest_return_echo($woocommerce->cart->cart_contents_count); ?></span></a>
                                </li> <?php } ?>

                            <li><a class="user_login_dropdown_text"
                                   href="<?php echo wp_logout_url(get_the_permalink($sb_sign_in_page)); ?>"><i
                                            class="fa fa-power-off"></i> <?php echo esc_html__("Logout", "adforest"); ?></a>
                            </li>
                        </ul>
                    </div>

                <?php } ?>
                <?php if ( isset($adforest_theme['ad_in_menu']) && $adforest_theme['ad_in_menu'] ) { ?>
                    <a href="<?php echo get_the_permalink($sb_post_ad_page); ?>"
                       class="btn-theme-secondary ad-post-btn"><i
                                class="fas fa-plus"></i><?php echo esc_html($ad_in_menu_text) ?></a>
                <?php } ?>
            </div>
        </div>
    </div>
</div>