/*
 * @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
 */

/**
 * Базовый класс редактирования метода доставки заказа в админке
 *
 * @since 1.0.0
 */
class ECLCDEKAdminOrder extends ECLCDEK {
    /**
     * Параметры инициализации
     * @type {object}
     * @since 1.0.0
     */
    #params;

    constructor(params) {
        const _defaultParams = {
            common: {
                core: {
                    debug: true,
                    ajaxLoader: null,
                    disabled_class: "pe-none",
                },
                city_field_id: "jform_shipping_city",
                country_field_id: "jform_shipping_country",
                region_field_id: "jform_shipping_region",
                calculationParams: {},
                task: "order",
                client: "admin",
                deliveryType: "office",
                result: "",
                widgetParams: null,
            }
        }
        params ??= _defaultParams;
        let _loader = document.body.getElementsByTagName('joomla-core-loader');
        if (_loader.length === 0) {
            _loader = document.body.appendChild(document.createElement('joomla-core-loader'));
            params.common.core.ajaxLoader = _loader;
        } else {
            params.common.core.ajaxLoader = _loader[0];
        }
        super(params.common);
        this.#params = params;
        this.className = "ECLCDEKAdminOrder";
        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
     *
     * @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);
    }

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

    /**
     * Обработчик смены пользователем тарифа доставки
     *
     * @param {HTMLElement} el  Элемент Input с выбранным тарифом
     * @param {ECLCDEKAdminOrder} _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() {
    }

    /**
     * @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 {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;
        _cp.to.country_code = this.country_code;
        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
     */
    initializeResultsBlock() {
        super.initializeResultsBlock();
        let _recalculate = document.getElementById('jform_shipping_recalculate_price');
        if (_recalculate) {
            _recalculate.addEventListener("focus", event => this.validateCheckout(event, this));
        }
    }

    /**
     * Валидация данных заказа
     *
     * @param {Event} event Событие нажатия кнопки оформить заказ
     * @param {ECLCDEKFrontOrder} _this Текущий объект
     *
     * @since 1.0.0
     */
    validateCheckout(event, _this) {
        _this.debug('validateCheckout', "started", '...');
        let _val = "";
        let _recalculate = event.target;
        // Блокируем пересчет цены
        _recalculate.setAttribute("disabled", "disabled");
        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) {
            _this.debug('validateCheckout', "done success", '...');
            // Разблокируем пересчет цены
            _recalculate.removeAttribute("disabled");
            return false;
        } 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);
        }
    }

}