<?php

namespace auctionforge\inc\controllers;

use stdClass;
use auctionforge\inc\BidSpiritRequest;
use auctionforge\inc\Debug;
use auctionforge\inc\helpers\Conditions;
use auctionforge\inc\helpers\LotHelper;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\helpers\View;
use auctionforge\inc\model\Auction;
use auctionforge\inc\model\Lot;
use WP_Post;
use WP_Query;
use WP_Term;

class BidspiritViews
{
    public function init()
    {
        add_action('bp_register_form_print_action', array($this, 'register_form_print'), 10, 1);
        add_action('bp_login_form_print_action', array($this, 'login_form_print'), 10, 1);
        add_action('bp_login_buttons_print_action', array($this, 'login_buttons_print'), 10, 1);

        add_action('bp_categories_filter_print_action', array($this, 'categories_filter_print'), 10, 1);

        add_action('bp_register_profile_buttons', array($this, 'profile_buttons_print'), 10, 1);

        add_action('bp_print_auction_time', array($this, 'print_auction_time'), 10, 1);

        add_action('bp_before_inner_content_auction', array($this, 'print_auction_approval_info'), 10, 1);
        add_action('bp_before_inner_content_auction', array($this, 'print_auction_notice_info'), 10, 1);
        add_action('bp_before_inner_content_lot', array($this, 'print_auction_approval_info'), 10, 1);
        add_action('bs_bidFormSection_action', array($this, 'print_additional_price_block'), 10, 1);
        add_action('bp_before_main_content', array($this, 'print_additional_info_block'), 10, 1);
        add_action('bp_after_main_content_ext', array($this, 'print_params_info_block'), 10, 2);
        add_action('bp_after_main_content_ext', array($this, 'print_house_info'), 10, 2);
        add_action('bp_before_bid_form_section', array($this, 'print_if_removed_item'), 10, 2);
        add_action('bp_vat_and_commission_field', [$this, 'vat_and_commission_field'], 10);

        add_action('bp_single_tool_lot', [$this, 'print_tools_lot']);

        add_action('bp_auction_list_not_found', array($this, 'auction_list_not_found'), 10, 1);

        add_action('bp_after_gallery_thumbs_action', array($this, 'print_after_gallery_thumbs_info'), 10, 4);

        add_action('bp_user_front_action', array($this, 'auction_starts_button_print'), 10, 1);

        add_action('wp_footer', array($this, 'bp_footer'), 99);
        add_action('wp_head', array($this, 'js_variables'));
        add_action('body_class', array($this, 'bp_body_class'));

        add_action('bp_after_description_auction', [$this, 'after_description_auction'], 10, 3);

        add_action('bp_auction_content_block', [$this, 'auction_content_block'], 10, 1);
        add_action('bp_tools_middle_block', [$this, 'tools_middle_block'], 10, 1);

        //search auction toolbar
        add_action('bp_tools_start_block', [$this, 'tool_sold_unsold'], 10, 1);

        //Elementor extensions
        add_filter('elementor/image_size/get_attachment_image_html', [$this, 'elementor_attachment_image_html'], 10, 4);

        // Bidspirit status feature page
        add_action('bidspirit_sync_progress', [$this, 'bidspirit_sync_progress']);
    }

    public function after_description_auction($auction, $auctionTitle, $auctionDay)
    {
        // displayHours is now rendered inline in templates/main/auction.php
        // with duplicate-detection. Removed from here to prevent double output.
    }

    public function auction_content_block($data)
    {
        /*if (0 || wp_is_mobile()) {
            echo View::render('templates.parts.chunks.search-field', compact('data'));
        }*/
    }

    public function tools_middle_block($data)
    {
        echo View::render('templates.parts.chunks.search-field', compact('data'));
        /*if (0 && !wp_is_mobile()) {
        }*/
    }

    public function tool_sold_unsold($data)
    {
        $auction = get_queried_object();
        if ($auction instanceof WP_Term) {
            $auctionState = SettingsHelper::getTermOption($auction->term_id, 'auction_state');
            $isArchived = Auction::isAuctionArchived($auctionState);
            if ($isArchived) {
                echo View::render('templates.parts.chunks.sold-unsold-field', compact('data'));
            }
        }
    }

    public function elementor_attachment_image_html($html, $settings, $image_size_key, $image_key)
    {
        global $post;

        if (isset($post->post_type) && $post->post_type == 'lot' && $html == '') {
            $lotHelper = new LotHelper($post->ID);
            $featureImage = $lotHelper->getFeatureImage();

            $html = '<img alt="'.$post->post_title.'" title="'.$post->post_title.'" src="'.$featureImage.'" class="lot__card" />';
        }

        return $html;
    }

    public function bidspirit_sync_progress()
    {
        $historyModel = new \auctionforge\inc\model\History();
        $data = $historyModel->getNotSyncItems();

        $activeAuctions = Auction::getActiveAuction();
        $pastAuctions = Auction::getArchiveAuction();


        $excludeAuctionIDs = array_unique(array_diff(SettingsHelper::getAuctionExclude(), array('')));
        $excludeAuctions = [];
        if (!empty($excludeAuctionIDs)) {
            foreach ($excludeAuctionIDs as $excludeAuctionID) {
                $excludeAuctions[] = Auction::findAuctionById($excludeAuctionID);
            }
        }

        $shopAuctions = SettingsHelper::getAuctionListFromSettings('shop_auction');
        $shopAuctionsTerms = get_terms([
            'taxonomy' => Auction::TERM,
            'include' => $shopAuctions
        ]);

        $auctionsData = [];
        $timeLeft = 0;
        if (!empty($data['total'])) {
            $timeLeft = round(((intval($data['total']) / RAW_LOT_LIMIT) * 60), 2);
        }

        if (!empty($data['rows'])) {
            foreach ($data['rows'] as $row) {
                $auctionsData[$row->auctionId][] = $row;
            }
        }

        $isAdmin = current_user_can('administrator');

        echo View::render('templates/chunks/sync-progress',
            compact('data', 'timeLeft', 'auctionsData', 'activeAuctions', 'pastAuctions', 'excludeAuctions', 'shopAuctionsTerms', 'isAdmin')
        );
    }

    public function register_form_print($data)
    {
        echo View::render('templates/parts/form-register', array(
            'data' => $data
        ));
    }

    public function profile_buttons_print($data)
    {
        echo View::render('templates/parts/chunks/profile-buttons', array(
            'data' => $data
        ));
    }

    public function login_form_print($data)
    {
        echo View::render('templates/parts/form-login', array(
            'data' => $data
        ));
    }

    public function login_buttons_print($data)
    {
        echo View::render('templates/parts/buttons-login', array(
            'data' => $data
        ));
    }

    public function categories_filter_print($data)
    {
        echo View::render('templates/shortcodes/buttons-login', array(
            'data' => $data
        ));
    }

    public function print_auction_time($data)
    {
        echo View::render('templates/parts/chunks/auction-start', array(
            'data' => $data
        ));
    }

    public function print_auction_approval_info($data)
    {
        echo View::render('templates/parts/chunks/approval-info', array(
            'data' => $data
        ));
    }

    public function print_additional_price_block($data)
    {
        echo View::render('templates/parts/chunks/additional-price', array(
            'data' => $data
        ));
    }

    public function print_additional_info_block($data)
    {
        echo View::render('templates/parts/chunks/additional-info', array(
            'data' => $data
        ));
    }

    public function print_params_info_block($post, $lotHelper)
    {
        echo View::render('templates.parts.chunks.params-info', array(
            'post' => $post,
            'lotHelper' => $lotHelper
        ));
    }

    public function print_house_info($post, $lotHelper)
    {
        echo View::render('templates.parts.chunks.house-info', array(
            'post' => $post,
            'lotHelper' => $lotHelper
        ));
    }

    public function print_if_removed_item($post, $lotHelper)
    {
        echo View::render('templates.parts.chunks.removed-item', array(
            'post' => $post,
            'lotHelper' => $lotHelper
        ));
    }

    public function vat_and_commission_field()
    {
        echo View::render('templates.parts.chunks.vat-and-commission-field', array());
    }

    public function print_tools_lot()
    {
        echo View::render('templates.parts.tools-lot', []);
    }

    public function auction_list_not_found($data)
    {
        echo View::render('templates.parts.chunks.auction_list_not_found', [
            'data' => $data
        ]);
    }

    public function print_after_gallery_thumbs_info($featureImage, $images, $video, $onlyForUserAuth)
    {
        if ($onlyForUserAuth) {
            echo View::render('templates.parts.chunks.gallery-thumbs-info', array(
                'data' => $featureImage
            ));
        }
    }

    public function print_auction_notice_info($data)
    {
        $auction = get_queried_object();
        if (empty($data)) {
            $data = array();
        }
        $data = array_merge($data, array(
            'auction' => $auction
        ));

        $authToken = SettingsHelper::getOption('auth_token', '');
        if ($authToken != "" || defined('AUCTIONFORGE_API_TOKEN')) {
            echo View::render('templates/parts/chunks/notice-info', array(
                'data' => $data
            ));
        }
    }

    public function auction_starts_button_print()
    {
        $auction = get_queried_object();
        echo View::render('templates.parts.chunks.auction-starts-button', compact('auction'));
    }

    function bp_footer() {
        global $post;

        echo View::render('templates.parts.modal-login', apply_filters('bp_footer_modal_login_data', array()));
        echo View::render('templates.parts.modal-register', apply_filters('bp_footer_modal_register_data', array()));
        echo View::render('templates.parts.modal-islive', apply_filters('bp_footer_modal_islive_data', array()));
        echo View::render('templates.parts.modal-search', apply_filters('bp_footer_modal_search_data', array()));
        echo View::render('templates.parts.user-templates', apply_filters('bp_footer_user_templates_data', array(
            'profilePage' => get_permalink(SettingsHelper::getOption('profile', 0))
        )));
        echo View::render('templates.parts.modal-photo', apply_filters('bp_modal_photo_templates_data', array()));

        echo View::render('templates.parts.profile-templates', apply_filters('bp_footer_profile_templates_data', array()));
        echo View::render('templates.js-chunks.approval-info', apply_filters('bp_footer_approval_info', array()));
        echo View::render('templates.js-chunks.payment-methods', apply_filters('bp_footer_payment_methods', array()));
        echo View::render('templates.parts.lot-templates', apply_filters('bp_footer_lot_templates_data', array()));

        echo View::render('templates.parts.profile.profile-page-gate', apply_filters('bp_footer_profile_page_gate_data', array()));
        echo View::render('templates.js-chunks.auction-live', apply_filters('bp_footer_auction_live_data', array()));
        echo View::render('templates.chunks.sprite', array());

        $postType = get_post_type();
        if (is_single() && $postType == 'lot') {

            /** @var WP_Term $auction */
            $auction = get_the_terms($post->ID, 'auction_number');
            if (!empty($auction)) {
                $auction = apply_filters('auctionforge_prepare_auction_object', $auction[0]);

                $auctionCommission = SettingsHelper::getTermOption($auction->term_id, 'auction_commission');
                $displayVatField = SettingsHelper::getOption('display_vat_field', 'on');
                $lotHelper = new LotHelper($post->ID);

                $title = $lotHelper->getOptionValue('lot_name', '');
                $title = LotHelper::getLotTitle($title, $post->post_content);
                $fullPriceVat = $lotHelper->getOptionValue('lot_fullPriceVat', '0');

                $lotIndex = $lotHelper->getOptionValue('lot_itemIndex', 0);
                $auctionDays = SettingsHelper::getTermOption($auction->term_id, 'auction_days');
                $auctionDay = Auction::getAuctionDayByItemID($lotIndex, $auctionDays);

                $termsPageId = SettingsHelper::getOption('terms', 0);
                $termsPageLink = LotHelper::getOptionPageLink($termsPageId);

                echo View::render('templates.parts.modal-bid', apply_filters('bp_footer_modal_bid_data', array(
                    'name' => $title,
                    'linkTerms' => $termsPageLink
                )));
                echo View::render('templates.js-chunks.presale-template', apply_filters('bp_footer_presale_template_data', array()));
                echo View::render('templates.js-chunks.post-sale-template', apply_filters('bp_footer_post_sale_template_data', array()));

                echo View::render('templates.js-chunks.modal-pre-sale', apply_filters('bp_footer_modal_pre_sale_data', array(
                    'name' => $title,
                    'linkTerms' => $termsPageLink
                )));
                echo View::render('templates.js-chunks.modal-post-sale', apply_filters('bp_footer_modal_post_sale_data', array(
                    'name' => $title,
                    'linkTerms' => $termsPageLink
                )));

                echo View::render('templates.js-chunks.modal-pre-sale-template', apply_filters('bp_footer_modal_pre_sale_template_data', array(
                    'auctionCommission' => $auctionCommission,
                    'displayVatField' => $displayVatField,
                    'lotHelper' => $lotHelper
                )));
                echo View::render('templates.js-chunks.modal-post-sale-template', apply_filters('bp_footer_modal_post_sale_template_data', array(
                    'auctionCommission' => $auctionCommission,
                    'displayVatField' => $displayVatField,
                    'lotHelper' => $lotHelper
                )));

                echo View::render('templates.js-chunks.modal-pre-sale-confirm-template', apply_filters('bp_footer_modal_pre_sale_confirm_template_data', array()));
                echo View::render('templates.js-chunks.modal-post-sale-confirm-template', apply_filters('bp_footer_modal_post_sale_confirm_template_data', array()));

                echo View::render('templates.js-chunks.house-info-template', apply_filters('bp_footer_house_info_template', array()));
                $postAuctionSaleOpenedUntil = false;
                if (isset($auctionDay->postAuctionSaleOpenedUntil)) {
                    $postAuctionSaleOpenedUntil = LotHelper::isOpenedUntil($auctionDay->postAuctionSaleOpenedUntil);
                }
                echo View::render('templates.parts.leading-bid-template', apply_filters('bp_footer_leading_bid_template_data', array(
                    'auctionCommission' => $auctionCommission,
                    'fullPriceVat' => $fullPriceVat,
                    'postAuctionSaleOpenedUntil' => $postAuctionSaleOpenedUntil
                )));

                echo View::render('templates.js-chunks.modal-steps', apply_filters('bp_footer_modal_steps_data', array()));
                echo View::render('templates.js-chunks.vat-and-commission', apply_filters('bp_vat_and_commission_data', array('displayVatField' => $displayVatField)));
            }
        } else {
            echo View::render('templates.parts.modal-bid-catalog', apply_filters('bp_footer_modal_bid_data', array()));
        }
        echo View::render('templates.js-chunks.search-section-template', apply_filters('bp_footer_search_section_template_data', array()));
    }

    function js_variables() {
        global $post;
        $variables = array (
            'ajax_url' => admin_url('admin-ajax.php'),
            'is_mobile' => wp_is_mobile(),
            'sandbox' => defined('WP_ENVIRONMENT_TYPE') && WP_ENVIRONMENT_TYPE,
        );
        $bsVariables = array(
            'polylang_time' => SettingsHelper::getOption('polylang_time', 'on'),
            'tax_number_required' => SettingsHelper::getOption('tax_number_required', 'off'),
            'link_profile' => get_permalink(SettingsHelper::getOption('profile', 0)),
            'link_upcoming_auctions' => get_permalink(SettingsHelper::getOption('auction_list', 0)),
            'link_past_auctions' => get_permalink(SettingsHelper::getOption('archive_list', 0)),
            'link_on_not_supported_browsers' => plugin_dir_url( __FILE__ ) . 'supported-browsers.html',
            'use_pagination' => SettingsHelper::getOption('use_pagination', 'off'),
            'lang' => (PolylangSupport::isFullSupport() && function_exists('pll_current_language')) ? pll_current_language() : "en",
            'hidden_class' => apply_filters('bp_hidden_class', 'hidden'),
            'loader_class' => apply_filters('bp_loader_class', 'bp-btn-loader'),
            'bids_in_catalog' => apply_filters('bp_bids_in_catalog', SettingsHelper::isChecked(Settings::BIDS_IN_CATALOG, false)),
            'only_for_user_auth' => apply_filters('bp_only_for_user_auth', SettingsHelper::isChecked(Settings::ONLY_FOR_USER_AUTH, false)),
            'page_terms' => apply_filters('bp_page_terms', LotHelper::getOptionPageLink(SettingsHelper::getOption('terms', 0))),
            'is_showcase_enable' => SettingsHelper::getOption('showcase_enable', false, 'file'),
            'auto_close_showcase' => SettingsHelper::getOption('showcase_auto_close', 0),
            'show_bidder_number' => SettingsHelper::getOption('bidden_number_in_profile', 'off'),
            'enable_recently_viewed' => SettingsHelper::getOption('enable_recently_viewed', 'off'),
            'enable_lot_analytics' => SettingsHelper::getOption('enable_lot_analytics', 'off'),
            'show_lot_view_counter' => SettingsHelper::getOption('show_lot_view_counter', 'off'),
            'show_bid_count' => SettingsHelper::getOption('show_bid_count', 'off'),
            'register_now_permalink' => (SettingsHelper::getOption('registration', "") != "") ? get_permalink(SettingsHelper::getOption('registration', "")) : "",
            'sign_in_permalink' => (SettingsHelper::getOption('authorization', "") != "") ? get_permalink(SettingsHelper::getOption('registration', "")) : "",
            'auction_house_state' => SettingsHelper::getOption('auction_house_state', ''),
            'enable_refund_policy' => SettingsHelper::getOption('enable_refund_policy', 'off'),
            'enable_chargeback_waiver' => SettingsHelper::getOption('enable_chargeback_waiver', 'off'),
        );

        $bsLang = array(
            'yes' => __('Yes'),
            'cancel' => __('Cancel'),
            'tax_number_required' => __('Tax number is required', 'auctionforge'),
            'tax_number_required_label' => __('Please fillable field "Tax number"', 'auctionforge'),
            'oldest_browser_text' => __('Bidspirit no longer supports this web browser.', 'auctionforge'),
            'oldest_browser_link_text' => __('Learn more about the browsers we support.', 'auctionforge'),
            'profile_password_reset' => __('We sent email with link to password reset', 'auctionforge'),
            'profile_email_not_found' => __('Email not found', 'auctionforge'),
            'profile_changes_saved' => __('Changes saved', 'auctionforge'),
            'profile_changes_saved_body' => __('', 'auctionforge'),
            'sort_by_number_lot' => __('Sort by Lot number', 'auctionforge'),
            'sort_by_high_price' => __('Sort by High price', 'auctionforge'),
            'sort_by_low_price' => __('Sort by Low price', 'auctionforge'),
            'not_approved_user' => __('Please complete your registration to participate in our auctions.', 'auctionforge'),
            'not_complete_user' => __('Please complete your details.', 'auctionforge'),
            'pending_user_state' => __('Your account is pending approval. You will receive an email when you are approved to bid.', 'auctionforge'),
            'approved_user_state' => __('You are not approved to bid yet.', 'auctionforge'),
            'register_title' => __('You\'re almost done', 'auctionforge'),
            'register_notice' => __('Please check your email for verification and account activation', 'auctionforge'),
            'login_success_hello' => __('Hello', 'auctionforge'),
            'login_success_hello_custom' => '',
            'login_success_hello_custom_default' => '',
            'login_success_full_hello' => __('Welcome %s1 %s2 %s3', 'auctionforge'),
            'buyout_notice' => sprintf(__("This lot may be purchased in a buyout price for %s. If someone else will buyout this lot, it will be sold to him. If you would you like to 
buyout this lot click %s", "auctionforge"), "#price#", "<a class='click-action' data-trigger='pre-sale-action' href='#'>" . __("here", "auctionforge") . "</a>"),
            'vat_lot_price_commission' => __('On lot\'s price, no vat on commission', 'auctionforge'),
            'success_high_bidder' => __('Success! You are the high bidder', 'auctionforge'),
            'higher_your_bid_has_been_outbid' => __('Your bid has been outbid by a higher bid', 'auctionforge'),
            'earlier_your_bid_has_been_outbid' => __('Your bid has been outbid by an earlier bid', 'auctionforge'),
            'sync_error' => __('Error synchronization', 'auctionforge'),
            'error' => __('Error', 'auctionforge'),
            'empty_response' => __("Empty response", 'auctionforge'),
            'honorific' => __('Honorific', 'auctionforge'),
            'first_name' => __('First Name', 'auctionforge'),
            'last_name' => __('Last Name', 'auctionforge'),
            'email' => __('Email', 'auctionforge'),
            'password' => __('Password', 'auctionforge'),
            'mobile_phone' => __('Mobile phone', 'auctionforge'),
            'phone' => __('Phone', 'auctionforge'),
            'second_phone' => __('Second phone', 'auctionforge'),
            'tax_number' => __('Tax number', 'auctionforge'),
            'state' => __('State', 'auctionforge'),
            'city' => __('City', 'auctionforge'),
            'address' => __('Address', 'auctionforge'),
            'zip_code' => __('Zip Code', 'auctionforge'),
            'a_user_with_email_already_exists' => __('A user with email already exists', 'auctionforge'),
            'illegal_value_for_field_password_-_too_short' => __('Illegal value for field password - too short', 'auctionforge'),
            'invalid_name' => __('Invalid name', 'auctionforge'),
            'select_value' => __('Category', 'auctionforge'),
            'select_value_old' => __('Select a value', 'auctionforge'),
            'copied' => __('Copied!', 'auctionforge'),
            'notice_personal_data' => __('You must accept the terms of the processing of personal data', 'auctionforge'),
            'not_found' => __('Not found', 'auctionforge'),
            'country_code' => __('Country code', 'auctionforge'),
            'remove_payment_method' => __('If you used this payment method to get approved to an auction your approval would be cancelled. are you sure you want to continue?', 'auctionforge'),
            'payment_method_required' => __('A payment method is required in order to be approved to bid in this auction', 'auctionforge'),
            'approval_info_approval_requested' => __('Please wait for the auction house to process your approval request', 'auctionforge'),
            'oops' => __('Oops...', 'auctionforge'),
            'you_are_still_pending_approval' => __('You are still pending approval at "%1s"', 'auctionforge'),
            'you_are_still_pending_approval_body' => __('If you have been waiting for some time, please feel free to contact us at %1s or %2s', 'auctionforge'),
            'access_denied' => __('Access denied', 'auctionforge'),
            'auction_preview_title' => __('Information', 'auctionforge'),
            'auction_preview_notice' => __("This is the preview of one of our lots for the upcoming auction.
If you are interested to participate, please wait for the catalog to be published. Once the catalog will be published, you will be able to place absentee bids. Have fun browsing.", 'auctionforge'),
            'showcase_success_title' => __("Product #title#", "auctionforge"),
            'showcase_success_notice' => __("was added to cart", "auctionforge"),
            'auto_charge_x_days_after' => __("If you win, the seller may charge your credit card #days# days after the auction ends", "auctionforge"),
            'storage_not_working' => __("Sites need support for localStorage to work correctly.", "auctionforge"),
            'lot_sync_is_queued' => __("Lot synchronization is queued.", "auctionforge"),
            'lot_sync_is_wrong' => __("An error has occurred.", "auctionforge"),
            'profile_error' => __("Not correct data.", "auctionforge"),
            'profile_field_error' => __("Illegal characters in field %s.", "auctionforge"),
            'bidder_number' => __("Bidder number %s", "auctionforge"),
            'recipient_name' => __("Recipient name", "auctionforge"),
            'select_file_to_upload' => __("Please select a file to upload", "auctionforge"),
            'photo_id_uploaded_successfully' => __("Photo id uploaded successfully", "auctionforge"),
            'you_want_to_remove_your_id_photo' => __("Are you sure you want to remove your id photo?", "auctionforge"),
            'id_photo_deleted' => __("id photo deleted", "auctionforge"),
            'want_to_delete_user' => __("Do you want to delete user?", "auctionforge"),
            'yes_delete_user' => __("Yes, delete user", "auctionforge"),
            'on_the_full_lots_price_and_commission' => __('On the full lot\'s price and commission', 'auctionforge'),
            'price_including_buyers_premium_and_vat' => __('Price including buyer’s premium and vat', 'auctionforge'),
            'vat' => __("VAT", "auctionforge"),
            'vat_ml' => __("_VAT", "auctionforge"),
            'on_item_price' => __("On item price", "auctionforge"),
            'exempted' => __("Exempted", "auctionforge"),
            'price_including_vat' => __("Price including vat", "auctionforge"),
            'total_with_commission' => __("Total with commission", "auctionforge"),
            'full_price_no_vat_or_buyers_permium' => __("Full price (no vat or buyer's permium)", "auctionforge"),
            'on_commission_only' => __("on commission only", "auctionforge"),
        );
        $bsVariables = apply_filters('auctionforge_bs_variables_filter', $bsVariables);
        $bsLang = apply_filters('auctionforge_bs_lang_filter', $bsLang);
        $serverUrl = SettingsHelper::getOption('server', '');

        echo '<script type="text/javascript">window.wp_data = ' . json_encode($variables) . ';</script>';
        echo '<script type="text/javascript">window.bs_data = ' . json_encode($bsVariables) . ';</script>';
        echo '<script type="text/javascript">window.bs_lang = ' . json_encode($bsLang) . ';</script>';
        echo '<script type="text/javascript">window.wp_nonce = \'' . wp_create_nonce("bp-ajax-string") . '\';</script>';
        echo '<script type="text/javascript">window.bidSpiritServer = \'' . $serverUrl . '\';</script>';
        echo '<script type="text/javascript">window.bidSpiritLang = \'' . MultiLanguageSupport::getCurrentLangCode() . '\';</script>';
        echo '<script type="text/javascript">window.bidSpiritCurrency = \'' . SettingsHelper::getOption('currency', '$') . '\';</script>';
        echo '<script type="text/javascript">window.bidSpiritHidePrice = \'' . SettingsHelper::getOption('hide_prices', '') . '\';</script>';
        echo '<script type="text/javascript">window.timeZone = \'' . SettingsHelper::getOption('time_zone', '+3') . '\';</script>';
        echo '<script type="text/javascript">window.timeZoneName = \'' . SettingsHelper::getOption(Settings::OPTIONS_TIMEZONES, '') . '\';</script>';
        echo '<script type="text/javascript">window.timeZoneLabel = \'' . SettingsHelper::getOption('time_zone_label', '') . '\';</script>';
        echo '<script type="text/javascript">window.browser_time = \'' . SettingsHelper::getOption('browser_time', 'on') . '\';</script>';
        echo '<script type="text/javascript">window.format_display_time = \'' . SettingsHelper::getOption('format_display_time', 1) . '\';</script>';
        echo '<script type="text/javascript">window.polylang_time = \'' . SettingsHelper::getOption('polylang_time', 'on') . '\';</script>';
    }

    public function bp_body_class($classes)
    {
        global $post;

        $auctionListKey = 'auction_list';
        $manualListKey = 'manual_auction_list';
        $archiveListKey = 'archive_list';
        $profileKey = 'profile';
        $welcomeKey = 'welcome_app_page';
        $auctionPolylangId = 0;
        $archivePolylangId = 0;
        $manualPolylangId = 0;
        $profilePolylangId = 0;
        $welcomePolylangId = 0;
        $pageAuctionListKey = SettingsHelper::getOption($auctionListKey, 0);
        $pageManualListKey = SettingsHelper::getOption($manualListKey, 0);
        $pageArchiveListKey = SettingsHelper::getOption($archiveListKey, 0);
        $pageProfileKey = SettingsHelper::getOption($profileKey, 0);
        $pageWelcomeKey = SettingsHelper::getOption($welcomeKey, 0);

        if (PolylangSupport::isPolylangActive()) {
            $lang = pll_current_language();
            $auctionPolylangId = pll_get_post($pageAuctionListKey, $lang);
            $archivePolylangId = pll_get_post($pageArchiveListKey, $lang);
            $manualPolylangId = pll_get_post($pageManualListKey, $lang);
            $profilePolylangId = pll_get_post($pageProfileKey, $lang);
            $welcomePolylangId = pll_get_post($pageWelcomeKey, $lang);
        }

        if (Conditions::isAuctionListTemplate($post, $pageAuctionListKey, $auctionPolylangId)) {
            $classes = array_merge($classes, ["bp_auction_list", "bp_auctions"]);
        }

        if (Conditions::isManualAuctionListTemplate($post, $manualListKey, $manualPolylangId)) {
            $classes = array_merge($classes, ["bp_manual_auction_list", "bp_auctions"]);
        }

        if (Conditions::isArchiveListTemplate($post, $pageArchiveListKey, $archivePolylangId)) {
            $classes = array_merge($classes, ["bp_archive_auction_list", "bp_auctions"]);
        }

        if (Conditions::isProfileTemplate($post, $pageProfileKey, $profilePolylangId)) {
            $classes = array_merge($classes, ["bp_profile_page", "bp_auctions"]);
        }

        if (Conditions::isPageTemplate($post, $pageWelcomeKey, $welcomePolylangId)) {
            $classes = array_merge($classes, ["bp_auctions"]);
        }

        if (is_single() && $post->post_type == BidspiritLots::POST_TYPE) {
            $auction = get_the_terms($post->ID, 'auction_number');
            if (!empty($auction)) {
                $auction = apply_filters('auctionforge_prepare_auction_object', $auction[0]);

                $auctionState = SettingsHelper::getTermOption($auction->term_id, 'auction_state');
                $isArchived = Auction::isAuctionArchived($auctionState);

                if ($isArchived) {
                    $classes[] = "bp_archived_auction";
                } else {
                    $classes[] = "bp_upcoming_auction";
                }

                $classes = array_merge($classes, ["bp_single_lot", "bp_auctions"]);
            }
        }

        if (is_tax('auction_number') && is_archive()) {
            /** @var WP_Term $auction */
            $auction = get_queried_object();
            $auctionState = SettingsHelper::getTermOption($auction->term_id, 'auction_state');
            $isArchived = Auction::isAuctionArchived($auctionState);
            $auctionDays = SettingsHelper::getTermOption($auction->term_id, 'auction_days');
            $classes[] = "bp_auctions";

            $part = get_query_var('part');
            if (!empty($part) && !empty($auctionDays[intval($part) - 1])) {
                $auctionDay = $auctionDays[intval($part) - 1];
            } else {
                $auctionDay = $auctionDays[0];
            }

            if ($isArchived) {
                $classes[] = "bp_archived_auction";
            } else {
                $classes[] = "bp_upcoming_auction";
            }

            if (isset($auctionDay->postAuctionSaleOpenedUntil) && ($auctionDay->postAuctionSaleOpenedUntil/1000 > time())) {
                $classes[] = "bp_postAuctionSaleOpened";
            } else {
                $classes[] = "bp_postAuctionSaleClosed";
            }
        }

        if (!empty($_SERVER['HTTP_USER_AGENT']) &&
            strpos(mb_strtolower($_SERVER['HTTP_USER_AGENT']), "in-app-browser") !== false) {
            $classes[] = "web2application";
        }

        return $classes;
    }
}
$bidspiritViews = new BidspiritViews();
$bidspiritViews->init();
