/*
 * @package    ECLCDEK shipping plugin СДЭК to RadicalMart
 * @subpackage    ECLCDEK
 * @version    1.0.1
 * @author Econsult Lab.
 * @copyright  Copyright (c) 2025 Econsult Lab. All rights reserved.
 * @license    GNU/GPL license: https://www.gnu.org/copyleft/gpl.html
 * @link       https://econsultlab.ru
 */

class ECLCDEKFrontOrder extends ECLCDEK {
    /**
     * Параметры инициализации
     * @type {object}
     * @since 1.0.0
     */
    #params;
    constructor(params) {
        const _defaultParams = {
            common: {
                core: {
                    debug: true,
                    ajaxLoader: null,
                    disabled_class:"uk-disabled",
                },
                city_field_id: "jform_shipping_city",
                country_field_id: "jform_shipping_country",
                region_field_id: "jform_shipping_region",
                calculationParams: {},
                task:"checkout",
                client:"site",
                deliveryType: "office",
                result: "",
                widgetParams: null,
            }
        }
        params ??= _defaultParams;
        let _loader = document.getElementById('checkout_shipping_loading');
        if(!_loader || _loader.length === 0) {
            _loader = document.appendChild(document.body.getElementById('checkout_shipping_loading'));
        }
        params.common.core.ajaxLoader = _loader;
        super(params.common);
        this.#params = params;
        this.className = "ECLCDEKFrontOrder";
        this.debug('constructor', "params", params);

        let _addr = "";
        let _msg = {
            type: "",
            text: "",
            formatted: ""
        };
        try {
            _addr = JSON.parse(this.results_block.result_input.value);
        } catch(err){
            _addr = "";
        }

        this.debug('constructor', "_addr", _addr);

        let _check = Object.keys(_addr).length === 0 || !_addr.address || !_addr.tariff;

        if(_check) {
            _msg = {
                type: "warning",
                text: Joomla.Text._("PLG_RADICALMART_SHIPPING_ECLCDEK_SETTINGS_MESSAGE_NEED_TO_"+(this.#params.common.deliveryType === "office"?"PVZ":"ADDRESS")),
                formatted: ""
            };
            this.initializeMap();
        }
        let _result = this.getBaseResult();
        _result.disabled_btns.map_btn = !_check;
        _result.disabled_btns.reset_btn = _check;
        _result.output_params.result = _addr;
        _result.output_params.calculation_params = this.#params.common.calculationParams;
        _result.message = _msg;

        this.current_results = _result;
        this.debug('constructor', "_result", _result);
        this.successCallBack = this.updateResult;
        this.errorCallBack = this.showError;
        this.getResultFormatted(_result);
    }

    /**
     * @inheritDoc
     *
     * @returns {object}
     *
     * @since 1.0.0
     */
    getCalculationParams(address) {
        let _cp = this.#params.common.calculationParams;
        _cp.to.code = this.city_code;
        _cp.to.city = this.city_name;
        _cp.to.region_code = this.region_code ?? "";
        _cp.to.region = this.region_name ?? "";
        _cp.to.address = address.address
        return _cp;
    }

    /**
     * @inheritDoc
     *
     * @since 1.0.0
     */
    preProcessAddress(address) {
        let _result = super.preProcessAddress(address);
        _result.client =this.#params.common.client;
        _result.task= this.#params.common.task;
        return _result;
    }

    /**
     * @inheritDoc
     *
     * @since 1.0.0
     */
    onReadyMap(_this) {
        super.onReadyMap(_this);
        let _result = _this.getBaseResult();
        _result.disabled_btns = {
            map_btn: false,
            reset_btn: true,
        };
        _result.message = {
            type: "primary",
            text: Joomla.Text._("PLG_RADICALMART_SHIPPING_ECLCDEK_SETTINGS_MESSAGE_READY_TO_CHOOSE_TO_"+(_this.#params.common.deliveryType === "office"?"PVZ":"ADDRESS")),
            formatted: ""
        };
        _this.successCallBack = _this.updateResult;
        _this.errorCallBack = _this.showError;
        _this.getResultFormatted(_result);
    }

    /**
     * @inheritDoc
     *
     * @returns {Result}
     *
     * @since 1.0.0
     */
    getBaseResult() {
        return super.getBaseResult();
    }

    /**
     * @inheritDoc
     *
     * @since 1.0.0
     */
    clearResult(_this) {
        _this.debug("clearResults","started",'...');

        let _result = _this.getBaseResult();
        _result.disabled_btns={
            map_btn: false,
            reset_btn: true,
        };
        _result.message ={
            type: "warning",
            text: Joomla.Text._("PLG_RADICALMART_SHIPPING_ECLCDEK_SETTINGS_MESSAGE_NEED_TO_"+(_this.#params.common.deliveryType === "office"?"PVZ":"ADDRESS")),
            formatted: ""
        }
        _this.successCallBack = this.updateResult;
        _this.errorCallBack = this.showError;
        _this.getResultFormatted(_result);
    }

    /**
     * Обработчик смены пользователем тарифа доставки
     *
     * @param {HTMLElement} el  Элемент Input с выбранным тарифом
     * @param {ECLCDEKFrontOrder} _this Текущий объект
     *
     * @since 1.0.0
     */
    onChangeTariff(el,_this){
        _this.debug("onChangeTariff","started",'...');
        _this.debug("onChangeTariff","el",el);
        if(el.getAttribute("name") === "tariff"){
            _this.debug("onChangeTariff","el.value",el.value);
            let _tariff;
            try {
                _tariff = JSON.parse(el.getAttribute("data-tariff"));
                let _formated_price = el.getAttribute("data-price");
                let _price = document.getElementById("delivery_sum");
                if(_price){
                    _price.innerHTML = Joomla.Text._("PLG_RADICALMART_SHIPPING_ECLCDEK_LAYOUT_RESULT_DELIVERY_PRICE").replace('%s',_formated_price);
                }
                let _time = document.getElementById("calendar_max");
                if(_time){
                    _time.innerHTML = Joomla.Text._("PLG_RADICALMART_SHIPPING_ECLCDEK_LAYOUT_RESULT_DELIVERY_TIME").replace('%s',_tariff.calendar_max);
                }

                // Обновляем тариф в данных формы
                if(this.results_block.result_input){
                    let _current = JSON.parse(_this.results_block.result_input.value);
                    _current.tariff = _tariff;
                    _this.results_block.result_input.value = JSON.stringify(_current);
                    _this.results_block.result_input.dispatchEvent(new Event('change'));
                }

                // Обновляем цены
                _this.updateCheckoutPrice();

            } catch (error){
                _tariff = ""
                _this.debug("onChangeTariff","error",error,"error");
            }
            _this.debug("onChangeTariff","_tariff",_tariff);
        }
        _this.debug("onChangeTariff","done",'...');
    }

    /**
     * Обновляет стоимость заказа
     *
     * @since 1.0.0
     */
    updateCheckoutPrice(){
        if(typeof window.RadicalMartCheckout !== "undefined") {
            let _t = window.RadicalMartCheckout();
            _t.updateDisplayData();
        }
    }

    /**
     * @inheritDoc
     *
     * @since 1.0.0
     */
    initializeResultsBlock() {
        super.initializeResultsBlock();
        let _checkout_btn = document.querySelector('*[radicalmart-checkout="submit-button"]');
        if(_checkout_btn) {
            _checkout_btn.removeAttribute("onClick");
            _checkout_btn.replaceWith(_checkout_btn.cloneNode(true));
            _checkout_btn = document.querySelector('*[radicalmart-checkout="submit-button"]');
            _checkout_btn.addEventListener("click", event=>this.validateCheckout(event,this));
        }
    }

    /**
     * Валидация данных при checkout
     *
     * @param {Event} event Событие нажатия кнопки оформить заказ
     * @param {ECLCDEKFrontOrder} _this Текущий объект
     *
     * @since 1.0.0
     */
    validateCheckout(event,_this) {
        _this.debug('validateCheckout',"started",'...');
        let _val = "";
        try {
            _val = JSON.parse(_this.results_block.result_input.value);
        } catch(e){
            _this.debug('validateCheckout',"ошибка e",e,'error');
        }
        if(typeof _val === "object" && Object.keys(_val).length) {
            if(typeof window.RadicalMartCheckout().createOrder === "function") {
                window.RadicalMartCheckout().createOrder();
            } else {
                _this.debug('validateCheckout',"window.RadicalMartCheckout().createOrder",typeof window.RadicalMartCheckout().createOrder,'error');
            }
        } else {
            Joomla.renderMessages({'error': [Joomla.Text._("PLG_RADICALMART_SHIPPING_ECLCDEK_MESSAGE_ERROR_NEED_"+_this.#params.common.deliveryType.toUpperCase())]});
            let _result = this.getBaseResult();
            _result.disabled_btns={
                map_btn: false,
                reset_btn: true,
            };
            _result.message ={
                type: "danger",
                text: Joomla.Text._("PLG_RADICALMART_SHIPPING_ECLCDEK_MESSAGE_ERROR_NEED_"+_this.#params.common.deliveryType.toUpperCase()),
                formatted: ""
            }
            _this.successCallBack = _this.updateResult;
            _this.errorCallBack = _this.showError;
            _this.getResultFormatted(_result);
        }
    }

    /**
     * Обновляет стоимость корзины при загрузке блока с тарифами
     * @inheritDoc
     * @since 1.0.0
     */
    updateResult(result) {
        super.updateResult(result);
        // Обновление стоимости корзины при загрузке блока с тарифами
        if(document.getElementById("cdek-tariffs-block")) {
            let _tariff_input = document.getElementById("cdek-tariffs-block").querySelector("input[checked='checked']");
            if(_tariff_input instanceof HTMLElement) {
                this.onChangeTariff(_tariff_input,this);
            }
        }
    }
}