<?php
/**
 * Maho
 *
 * @category    design
 * @package     default_default
 * @copyright   Copyright (c) 2006-2020 Magento, Inc. (https://magento.com)
 * @copyright   Copyright (c) 2022-2024 The OpenMage Contributors (https://openmage.org)
 * @copyright   Copyright (c) 2024 Maho (https://mahocommerce.com)
 * @license     https://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

/** @var Mage_Usa_Model_Shipping_Carrier_Ups $upsModel */
$upsModel = Mage::getSingleton('usa/shipping_carrier_ups');
$orShipArr = $upsModel->getCode('originShipment');
$defShipArr = $upsModel->getCode('method');
$allMethodsCodes = [];
foreach (Mage::getModel('usa/shipping_carrier_ups_source_method')->toOptionArray() as $method) {
    $allMethodsCodes[]= $method['value'];
}
/** @var Mage_Adminhtml_Block_Template $this */
$sectionCode = $this->getRequest()->getParam('section');
$websiteCode = $this->getRequest()->getParam('website');
$storeCode = $this->getRequest()->getParam('store');

if (!$storeCode && $websiteCode) {
    /** @var Mage_Core_Model_Website $web */
    $web = Mage::getModel('Mage_Core_Model_Website')->load($websiteCode);
    $storedAllowedMethods = explode(',', $web->getConfig('carriers/ups/allowed_methods'));
    $storedOriginShipment = $web->getConfig('carriers/ups/origin_shipment');
    $storedFreeShipment   = $web->getConfig('carriers/ups/free_method');
    $storedUpsType        = $web->getConfig('carriers/ups/type');
} elseif ($storeCode) {
    $storedAllowedMethods = explode(',', Mage::getStoreConfig('carriers/ups/allowed_methods', $storeCode));
    $storedOriginShipment = Mage::getStoreConfig('carriers/ups/origin_shipment', $storeCode);
    $storedFreeShipment   = Mage::getStoreConfig('carriers/ups/free_method', $storeCode);
    $storedUpsType        = Mage::getStoreConfig('carriers/ups/type', $storeCode);
} else {
    $storedAllowedMethods = explode(',', Mage::getStoreConfig('carriers/ups/allowed_methods'));
    $storedOriginShipment = Mage::getStoreConfig('carriers/ups/origin_shipment');
    $storedFreeShipment   = Mage::getStoreConfig('carriers/ups/free_method');
    $storedUpsType        = Mage::getStoreConfig('carriers/ups/type');
}
if (!in_array($storedOriginShipment, array_keys($orShipArr))) {
    $storedOriginShipment = '';
}
if ($storedFreeShipment != '' && !in_array($storedFreeShipment, $allMethodsCodes)) {
    $storedFreeShipment = '';
}
if (!Mage::helper('usa')->validateUpsType($storedUpsType)) {
    $storedUpsType = '';
}
?>
<script type="text/javascript">
//<![CDATA[
    function hideRowArrayElements(arr)
    {
        for (var a = 0; a < arr.length; a++) {
            $(arr[a]).up(1).hide();
        }
    }

    function showRowArrayElements(arr)
    {
        for (var a = 0; a < arr.length; a++) {
            $(arr[a]).up(1).show();
        }
    }

    function inArray(arr, value)
    {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] === value) {
                return true;
            }
        }
        return false;
    }

    var upsXml = Class.create();
    upsXml.prototype = {
        initialize: function()
        {
            this.carriersUpsTypeId = 'carriers_ups_type';
            if (!$(this.carriersUpsTypeId)) {
                return;
            }
            
            this.checkingUpsXmlId = ['carriers_ups_gateway_xml_url','carriers_ups_username',
                'carriers_ups_password','carriers_ups_access_license_number'];
            this.checkingUpsRestId = ['carriers_ups_gateway_rest_url','carriers_ups_client_id',
                'carriers_ups_client_secret'];

            this.originShipmentTitle = '';
            this.allowedMethodsId = 'carriers_ups_allowed_methods';
            this.freeShipmentId = 'carriers_ups_free_method';

            this.onlyUpsXmlElements = ['carriers_ups_gateway_xml_url','carriers_ups_tracking_xml_url',
                'carriers_ups_shipconfirm_xml_url', 'carriers_ups_shipaccept_xml_url',
                'carriers_ups_username','carriers_ups_password','carriers_ups_access_license_number'];
            this.onlyUpsRestElements = ['carriers_ups_gateway_rest_url','carriers_ups_tracking_rest_url',
                'carriers_ups_shipconfirm_rest_url', 'carriers_ups_client_id','carriers_ups_client_secret'];

            this.storedOriginShipment = '<?= $storedOriginShipment ?>';
            this.storedFreeShipment = '<?= $storedFreeShipment ?>';
            this.storedUpsType = '<?= $storedUpsType ?>';
            <?php /** @var Mage_Core_Helper_Data $_coreHelper */ $_coreHelper = Mage::helper('core'); ?>
            this.storedAllowedMethods = <?= $_coreHelper->jsonEncode($storedAllowedMethods) ?>;
            this.originShipmentObj = <?= $_coreHelper->jsonEncode($orShipArr) ?>;
            this.originShipmentObj['default'] = <?= $_coreHelper->jsonEncode($defShipArr) ?>;

            this.setFormValues();
            Event.observe($(this.carriersUpsTypeId), 'change', this.setFormValues.bind(this));
            Event.observe($('carriers_ups_active'), 'change', this.setFormValues.bind(this));
        },
        updateAllowedMethods: function(originShipmentTitle)
        {
            var allowedMethods = $(this.allowedMethodsId), // multiselect
                freeMethod = $(this.freeShipmentId), // single-choice select
                originShipment = this.originShipmentObj[originShipmentTitle];

            while (allowedMethods.length > 0) {
                allowedMethods.remove(0);
            }

            while (freeMethod.length > 0) {
                freeMethod.remove(0);
            }

            freeMethod.insert(new Element('option', {value:''}).update('None'));

            var code, option;
            for (code in originShipment) {
                option = new Element('option', {value:code}).update(originShipment[code]);
                if ((originShipmentTitle == this.storedOriginShipment || originShipmentTitle == 'default')
                    && this.storedFreeShipment == code
                ) {
                    option.selected = true;
                }
                freeMethod.insert(option);

                option = new Element('option', {value:code}).update(originShipment[code]);
                if (this.storedUpsType == 'UPS') {
                    if (originShipmentTitle != 'default' || inArray(this.storedAllowedMethods, code)) {
                        option.selected = true;
                    }
                } else if (originShipmentTitle != this.storedOriginShipment
                    || inArray(this.storedAllowedMethods, code)
                ) {
                    option.selected = true;
                }

                if ((originShipmentTitle == 'default' || originShipmentTitle == this.storedOriginShipment)
                    && inArray(this.storedAllowedMethods, code)
                ) {
                    option.selected = true;
                }

                allowedMethods.insert(option);
            }
        },
        setFormValues: function()
        {
            var a;
            if ($F(this.carriersUpsTypeId) == 'UPS_XML') {
                if (document.getElementById('carriers_ups_active').value == 1) {
                    for (a = 0; a < this.checkingUpsXmlId.length; a++) {
                        $(this.checkingUpsXmlId[a]).addClassName('required-entry');
                    }
                    for (a = 0; a < this.checkingUpsRestId.length; a++) {
                        $(this.checkingUpsRestId[a]).addClassName('required-entry');
                    }
                } else {
                    for (a = 0; a < this.checkingUpsXmlId.length; a++) {
                        $(this.checkingUpsXmlId[a]).removeClassName('required-entry');
                    }
                    for (a = 0; a < this.checkingUpsRestId.length; a++) {
                        $(this.checkingUpsRestId[a]).removeClassName('required-entry');
                    }
                }
                Event.observe($('carriers_ups_origin_shipment'), 'change', this.changeOriginShipment.bind(this));
                showRowArrayElements(this.onlyUpsXmlElements);
                hideRowArrayElements(this.onlyUpsRestElements);
                this.changeOriginShipment(null, null);
            } else if ($F(this.carriersUpsTypeId) == 'UPS_REST') {
                if (document.getElementById('carriers_ups_active').value == 1) {
                    for (a = 0; a < this.checkingUpsRestId.length; a++) {
                        $(this.checkingUpsRestId[a]).addClassName('required-entry');
                    }
                    for (a = 0; a < this.checkingUpsXmlId.length; a++) {
                        $(this.checkingUpsXmlId[a]).addClassName('required-entry');
                    }
                } else {
                    for (a = 0; a < this.checkingUpsRestId.length; a++) {
                        $(this.checkingUpsRestId[a]).removeClassName('required-entry');
                    }
                    for (a = 0; a < this.checkingUpsXmlId.length; a++) {
                        $(this.checkingUpsXmlId[a]).removeClassName('required-entry');
                    }
                }
                Event.observe($('carriers_ups_origin_shipment'), 'change', this.changeOriginShipment.bind(this));
                showRowArrayElements(this.onlyUpsRestElements);
                hideRowArrayElements(this.onlyUpsXmlElements);
                this.changeOriginShipment(null, null);
            }
        },
        changeOriginShipment: function(Event, key)
        {
            this.originShipmentTitle = key ? key : $F('carriers_ups_origin_shipment');
            this.updateAllowedMethods(this.originShipmentTitle);
        }
    };
    xml = new upsXml();
    //]]>
</script>
