system.directive('fulfillprintlogistic', function () {
    return {
        controller: function ($scope, $http, Upload, $q) {
            this.__proto__ = new BaseFulfillController($scope, $http);
            $scope.debug = false;
            if (user_email == 'tienanhbui0597@gmail.com') $scope.debug = true;

            $scope.printLogisticCurrentOrder = {};
            $scope.printLogisticStates = {
                initialized: false,
                product_types: []
            };

            let productTemplateIds = [];

            const getProductTypes = () => {
                const requestObj = $scope.buildLocaleData('/print-suppliers/print-logistic/product-type', {}, $scope.fulFillLocale);
                return $http.get(requestObj.url, {
                    params: requestObj.params
                }).then((response) => {
                    if (response.data) {
                        $scope.printLogisticStates.product_types = response.data;
                    }
                });
            }
          
            const initializePrintLogistic = async function () {
                return new Promise((resolve) => {
                    Promise.all([getProductTypes()]).then(() => {
                        resolve();
                    });
                });
            }

            const postToPrintLogistic = (printLogisticOrder) => 
            {
                toastr.options.positionClass = "toast-bottom-left";
                
                const requestObj = $scope.buildLocaleData('/print-suppliers/print-logistic/api?method=POST&end_point=order/add ', printLogisticOrder, $scope.fulFillLocale);

                $http.post(requestObj.url, { params: requestObj.params, ignore_localization: 1 }).then(function (response)
                {
                    if (response.data.status == 'Success') {
                        toastr.success('Successfully');
                        $('#modalFulfillPrintLogistic').modal('hide');
                    } else {
                        toastr.error('Has an Error! Please contact technical team.  | ' + JSON.stringify(response.data));
                    }

                    const mapItemPrintProvider = {};
                    const printervalOrder = angular.copy($scope.printLogisticCurrentOrder);
                    for (let index = 0; index < printervalOrder.items.length; index++) {
                        const item = printervalOrder.items[index];
                        mapItemPrintProvider[item.id] = 'PRINTLOGISTIC';
                    }

                    afterFulfillAction(printLogisticOrder, {mapItemPrintProvider});

                    stopLoadingButton('#btnPostPrintLogisticOrder');
                    
                }).catch(function(error) {
                    toastr.error('Has an Error! Please contact technical team. | ' + JSON.stringify(error));
                    toastr.warning($scope.getFailFulfillMessage('printlogistic'));
                    $('#modalFulfillPrintLogistic').modal('hide');
                    stopLoadingButton('#btnPostPrintLogisticOrder');
                });
            }

            const orderPrintLogistic = () => 
            {
                safeApply();

                const printervalOrder = angular.copy($scope.printLogisticCurrentOrder);
            
                if (printLogistic_validateItem(printervalOrder.items).validated) 
                {
                    const printLogisticOrderBody = buildFulfillOrderBody(printervalOrder);

                    const param = {
                        title: 'Create Order',
                        customText: 'Post order to Print Logistic!',
                        confirmButtonText: 'Ok',
                        cancelButtonText: 'Back'
                    };

                    swal({
                        title: param.title,
                        html: param.customText,
                        type: "warning",
                        showConfirmButton: true,
                        showCancelButton: true,
                        confirmButtonText: param.confirmButtonText,
                        cancelButtonText: param.cancelButtonText
                    }).then(async function (isConfirm) 
                    {
                        if (isConfirm.value) {
                        
                            loadingButton('#btnPostPrintLogisticOrder');

                            postProfiles(printervalOrder);

                            postToPrintLogistic(printLogisticOrderBody);

                        } else {
                            console.log(printLogisticOrderBody);
                        }

                    });

                } else  { // show error validate
                    document.getElementById("errorModalPrintLogistic").style.display = "block";
                }
            }

            const printLogistic_validateItem = (items) =>
            {
                let validated = true;
                let messages = {};

                for (let i = 0; i < items.length; i++) {
                    const itemData = items[i];
                    messages[itemData.product_sku_id] = [];

                    if (!getPrintSku(itemData)) {
                        validated = false;
                        messages[itemData.product_sku_id].push(itemData.name + ' || Missing Print Logistic SKU.');
                    }

                    const artworks = itemData.printLogistic.artworks;
                    if (!artworks.back.url && !artworks.front.url) {
                        validated = false;
                        messages[itemData.product_sku_id].push(itemData.name + ' || Missing Design.');
                    }

                }

                $scope.printLogisticStates.messages = messages;

                return {
                    validated,
                    messages
                };
            }

            const buildFulfillOrderBody = (currentOrder) => 
            {
                const fullName = currentOrder.customer.full_name;
                const partsName = fullName.split(' ');
                const lengthName = partsName.length;

                const lastName = partsName.pop();
                let firstName = partsName.join(' ');

                if (lengthName < 2) {
                    firstName = lastName;
                }

                let city = ' ';
                if (currentOrder.city_name) {
                    city = currentOrder.city_name;
                }

                const inventoryItems = getInventoryItems(currentOrder);
                let orderReferenceId = "API";
                if (printerval_locate && printerval_locate !== '') {
                    orderReferenceId += "_" + printerval_locate.toUpperCase();
                }
                orderReferenceId += "_" + currentOrder.code;

                const orderBody = {
                    "job_id": orderReferenceId + '_' + new Date().getTime().toString().substr(-4),
                    "job_provider": "Printerval",
                    "special_handling": "",
                    "cancelled": "false",
                    "inventory_items": inventoryItems.items,
                    "placements": inventoryItems.placementTokens,
                    "mockups": inventoryItems.mockupTokens,
                    "artworks": inventoryItems.artworkTokens,
                    "shipments": [
                        {
                            "type": (currentOrder.shipping_type === 'standard' ? 'Standard' : 'Express'),
                            "transport_data": [
                                {
                                    "company": "",
                                    "name": firstName,
                                    "surname": lastName,
                                    "address_1": currentOrder.delivery_address,
                                    "address_2": currentOrder.optional_address,
                                    "city": city,
                                    "post-code": currentOrder.zip_code,
                                    "country": currentOrder.country.iso,
                                    "phone": currentOrder.customer.phone,
                                    "email": currentOrder.customer.email
                                }
                            ]
                        }
                    ]
                };

                return orderBody;
            }

            const buildProfiles = (order) =>
            {
                const profiles = [];
                for (let i = 0; i < order.items.length; i++) 
                {
                    const item = order.items[i];
                    const options = {
                        artworks: item.printLogistic.artworks,
                        color: item.printLogistic.color,
                        type: item.printLogistic.type,
                        size: item.printLogistic.size,
                        sku: getPrintSku(item)
                    }

                    profiles.push({
                        product_id: item.product_id,
                        is_template_product: isTemplateProduct(item.product_id),
                        product_sku_id: item.product_sku_id,
                        order_id: item.id,
                        order_item_id: item.id,
                        options,
                        type: 'print-logistic'
                    });
                }
                return profiles;
            }

            const fetchProfiles = () =>
            {
                $scope.getDesignJobOrder($scope.printLogisticCurrentOrder);

                const requestObj = $scope.buildLocaleData('/print-suppliers/get-profile', {
                    type: 'print-logistic',
                    order_items: $scope.printLogisticCurrentOrder.items
                }, $scope.fulFillLocale);

                $http.post(requestObj.url, requestObj.params).then(function(response) {
                    if (response.data.status === 'successful') {
                        $scope.profiles = {
                            profiles: response.data.profiles,
                            designs: response.data.designs
                        };
                        productTemplateIds = response.data.product_template_ids;
                        applyProfiles();
                    }
                }, function(error) {
                    toastr.error('Error load profiles!');
                });
            }

            const postProfiles = (order) => 
            {
                const profiles = buildProfiles(order);

                const errMessage = 'Error save profile. Please contact technical team.';
                const promisePostProfile = new Promise(function (resolve, reject) {
                    const requestObj = $scope.buildLocaleData('/print-suppliers/profile', profiles, $scope.fulFillLocale);
                    $http.post(requestObj.url, requestObj.params).then(function(response) {
                        if (response.data.status === "successful") {
                            resolve(response.data.data);
                        } else {
                            toastr.error(errMessage);
                            reject();
                        }
                    });
                });

                const promises = [promisePostProfile];

                return Promise.all(promises);
            }

            const applyProfiles = async () => 
            {
                $scope.printLogisticCurrentOrder.items.forEach(async printOrderItem => {

                    let profile = null;
                    let designs;

                    if (!printOrderItem.printLogistic.profile) {
                        printOrderItem.printLogistic.profile = {};
                    }

                    if (isTemplateProduct(printOrderItem.product_id)) {
                        profile = $scope.profiles.profiles.find(function (item) {
                            return parseInt(item.product_id) === parseInt(printOrderItem.product_id) && item.is_template_product;
                        });
                        designs = $scope.findDesign(printOrderItem, true, $scope.profiles.designs);
                    } else {
                        profile = $scope.profiles.profiles.find(function (item) {
                            return parseInt(item.product_sku_id) === parseInt(printOrderItem.product_sku_id) && !item.is_template_product;
                        });
                        designs =  $scope.findDesign(printOrderItem, false, $scope.profiles.designs);
                    }

                    printOrderItem.printLogistic.patternDesigns = [];
                    if(designs && designs.length) {
                        printOrderItem.printLogistic.patternDesigns = designs;

                        setTimeout(() => {
                            $('[data-magnify=gallery]').magnify({
                                zIndex: 10000
                            });
                        }, 500);
                    }

                    if(profile) 
                    {
                        const profileOptions = profile.options;

                        if (typeof profileOptions.artworks != 'undefined') {
                            if (profileOptions.artworks.front.url) {
                                printOrderItem.printLogistic.artworks.front.url = profileOptions.artworks.front.url;
                            }
                            if (profileOptions.artworks.back.url) {
                                printOrderItem.printLogistic.artworks.back.url = profileOptions.artworks.back.url;
                            }
                            if (profileOptions.artworks.right_sleeve.url) {
                                printOrderItem.printLogistic.artworks.right_sleeve.url = profileOptions.artworks.right_sleeve.url;
                            }
                            if (profileOptions.artworks.left_sleeve.url) {
                                printOrderItem.printLogistic.artworks.left_sleeve.url = profileOptions.artworks.left_sleeve.url;
                            }
                            if (profileOptions.artworks.neck.url) {
                                printOrderItem.printLogistic.artworks.neck.url = profileOptions.artworks.neck.url;
                            }
                        }
                        if (typeof profileOptions.type != 'undefined') {
                            printOrderItem.printLogistic.type = profileOptions.type;
                        }
                        if (typeof profileOptions.size != 'undefined') {
                            printOrderItem.printLogistic.size = profileOptions.size;
                        }
                        if (typeof profileOptions.color != 'undefined') {
                            printOrderItem.printLogistic.color = profileOptions.color;
                        }
    
                        await $scope.changeProductTypeOption(printOrderItem);
                        await $scope.changeProductColorOption(printOrderItem);
                        await $scope.changeProductSizeOption(printOrderItem);
    
                        if (typeof profileOptions.sku != 'undefined') {
                            setPrintSku(printOrderItem.printLogistic, profileOptions.sku);
                        }
                    }

                });
            }

            const afterFulfillAction = async function (fulfillOrderPayload, additionalData = {}) 
            {
                logPrintifyFulFill(fulfillOrderPayload);

                const orderMeta = {
                    order_id: $scope.printLogisticCurrentOrder.id,
                };

                if (additionalData && typeof additionalData.mapItemPrintProvider) {
                    orderMeta.print_provider = additionalData.mapItemPrintProvider;
                }

                requestObj = $scope.buildLocaleData('/print-suppliers/fulfill/attach-order-meta', orderMeta, $scope.fulFillLocale);
                
                return $http.post(requestObj.url, requestObj.params);
            }

            const logPrintifyFulFill = function(plOrder, isLogData = false) 
            {
                let logData;

                if (!isLogData) {
                    plOrder.printify_shop_id = $scope.printifyAccount.shop_id;
                    logData = {
                        actor_email: user_email,
                        event_type: 'PRINTLOGISTIC-FULFILLMENT',
                        target_id: $scope.printLogisticCurrentOrder.id,
                        data: plOrder
                    };

                } else {
                    logData = plOrder;
                }

                const requestObj = $scope.buildLocaleData('/print-suppliers/fulfill/log', logData, $scope.fulFillLocale);
                $http.post(requestObj.url, requestObj.params).then(() => {});

            }

            const isTemplateProduct = (productId) => {
                return productTemplateIds.includes(productId);
            }

            const getInventoryItems = (order) =>
            {
                const items = [];
                const artworkTokens = [];
                const mockupTokens = [];
                const placementTokens = [];
            
                for (let i = 0; i < order.items.length; i++) 
                {
                    const item = order.items[i];
                    const printSku = getPrintSku(item); 

                    const layouts = [];
                    const artworks = item.printLogistic.artworks;
                    for (const key in artworks) {
                        if (Object.hasOwnProperty.call(artworks, key)) 
                        {
                            const artwork = artworks[key];

                            if (artwork.url) 
                            {
                                const layoutKey = item.id + '_' + key;

                                layouts.push({
                                    "artwork_token":    layoutKey + "_art",
                                    "mockup_token":     layoutKey + "_mck",
                                    "placement_token":  layoutKey + "_plc",
                                    "location":         key
                                });
    
                                artworkTokens.push({ 
                                    "token": layoutKey + "_art",
                                    "url":   artwork.url 
                                });

                                mockupTokens.push( { 
                                    "token": layoutKey + "_mck",
                                    "url":   item.image_url 
                                });

                                placementTokens.push({
                                    "token": layoutKey + "_plc",
                                    "x_offset": 0,
                                    "y_offset": 0
                                });
                            }

                        }
                    }

                    items.push({
                        "sku": printSku.sku,
                        "quantity": item.quantity,
                        "description": `${printSku.color} ${printSku.product_type} ${printSku.size} ${printSku.brand}`,
                        "layouts": layouts
                    });
                }

                return {
                    items,
                    artworkTokens,
                    mockupTokens,
                    placementTokens
                };
            }

            const getPrintSku = (item) => 
            {
                try {
                    for (let i = 0; i < item.printLogistic.skus.length; i++) {
                        const sku = item.printLogistic.skus[i];
                        if (sku.selected == true) return sku;
                    }
                } catch (error) {
                    console.warn(error);
                }

                return null;
            }

            const setPrintSku = (printLogistic, newSku) => 
            {
                for (let i = 0; i < printLogistic.skus.length; i++) {
                    const sku = printLogistic.skus[i];
                    if (newSku.id == sku.id) {
                        printLogistic.skus[i].selected = true;
                        loadColorCode(printLogistic.skus[i]);
                        break;
                    }
                }

                safeApply();
            }

            const loadingButton = function (selector, text = 'Processing...') {
                $(selector).attr('dt-text', $(selector).text());
                $(selector).text(text);
                $(selector).attr("disabled", true);
            }

            const stopLoadingButton = function (selector) {
                $(selector).html($(selector).attr('dt-text'));
                $(selector).attr("disabled", false);
            }

            const loadColorCode = function(sku) {
                const requestObj = $scope.buildLocaleData('/print-suppliers/printify/find-color', {
                    name: sku.color
                }, $scope.fulFillLocale);

                $http.get(requestObj.url, {
                    params: requestObj.params
                }).then((response) => {
                    if (response.data.result) {
                        sku.colorCode = response.data.result;
                    }
                });
            }

            $scope.orderPrintLogistic = orderPrintLogistic;

            $scope.changeProductTypeOption = (item) => 
            {
                const requestObj = $scope.buildLocaleData('/print-suppliers/print-logistic/product-sku', {
                    product_type: item.printLogistic.type,
                    group: 'color'
                }, $scope.fulFillLocale);

                return $http.get(requestObj.url, {
                    params: requestObj.params
                }).then((response) => {
                    if (response.data) 
                    {
                        item.printLogistic.skus = response.data;
                        const colors = [];
                        for (let i = 0; i < response.data.length; i++) {
                            const element = response.data[i];
                            colors.push(element.color);
                        }
                        item.printLogistic.colors = colors;
                    }
                });
            }

            $scope.getColorCode = function(item) {
                if (item.printLogistic.skus) {
                    const sku = getPrintSku(item);
                    if (sku && sku.colorCode) return sku.colorCode.hex;
                }
                return '#fff';
            }

            $scope.changeProductColorOption = (item) => 
            {
                const requestObj = $scope.buildLocaleData('/print-suppliers/print-logistic/product-sku', {
                    product_type: item.printLogistic.type,
                    product_color: item.printLogistic.color
                }, $scope.fulFillLocale);

                return $http.get(requestObj.url, {
                    params: requestObj.params
                }).then((response) => {
                    if (response.data) 
                    {
                        item.printLogistic.skus = response.data;
                        const sizes = [];
                        for (let i = 0; i < response.data.length; i++) {
                            const element = response.data[i];
                            if (!sizes.includes(element.size)) sizes.push(element.size);
                        }
                        item.printLogistic.sizes = sizes;

                        if (item.printLogistic.size && item.printLogistic.sizes.includes(item.printLogistic.size)) {
                            $scope.changeProductSizeOption(item);
                        } else {
                            item.printLogistic.size = null;
                        }
                    }
                });
            }

            $scope.choosePrintLogisticSku = (item, sku) => {
                for (let i = 0; i < item.printLogistic.skus.length; i++) {
                    const element = item.printLogistic.skus[i];
                    element.selected = false;
                }

                loadColorCode(sku);
                
                sku.selected = true;
            }

            $scope.changeProductSizeOption = (item) => {

                const requestObj = $scope.buildLocaleData('/print-suppliers/print-logistic/product-sku', {
                    product_type: item.printLogistic.type,
                    product_color: item.printLogistic.color,
                    product_size: item.printLogistic.size,
                }, $scope.fulFillLocale);

                return $http.get(requestObj.url, {
                    params: requestObj.params
                }).then((response) => {
                    if (response.data) {
                        item.printLogistic.skus = response.data;
                        const brands = [];
                        for (let i = 0; i < response.data.length; i++) {
                            const element = response.data[i];
                            if (!brands.includes(element.brand)) brands.push(element.brand);
                        }
                        item.printLogistic.brands = brands;
                    }
                });
            }

            $scope.changeProductBrandOption = (item) => {
                const requestObj = $scope.buildLocaleData('/print-suppliers/print-logistic/product-sku', {
                    product_type: item.printLogistic.type,
                    product_color: item.printLogistic.color,
                    product_size: item.printLogistic.size,
                    product_brand: item.printLogistic.brand,
                }, $scope.fulFillLocale);

                return $http.get(requestObj.url, {
                    params: requestObj.params
                }).then((response) => {
                    if (response.data) {
                        item.printLogistic.skus = response.data;
                    }
                });
            }

            $scope.printLogistic_uploadImages = async function (files, item, designFile) {
                let supportedFilesType = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif'];
                let supportedFilesExtensions = ['jpg', 'jpeg', 'png', 'gif'];

                item.printLogistic.states.uploading = true;

                if (files) {
                    try {

                        let imagesUploaded = [];
                        let imageFile = null;
                        if (files && files.length) {
                            imageFile = files[0];

                            let fileExtension = imageFile.name.split('.').pop();
                            fileExtension = fileExtension.toLowerCase();
                            if (
                                supportedFilesExtensions.includes(fileExtension) &&
                                supportedFilesType.includes(imageFile.type)
                            ) {
                                imagesUploaded = await $scope.gelato_uploads(files);
                            } else {
                                toastr.error('Error! format supported: jpg, jpeg, png, gif');
                            }
                        }

                        if (imagesUploaded.length) {
                            $scope.$applyAsync(function () {
                                let imageUrl = imagesUploaded.pop();
                                if (imageUrl) {
                                    designFile.extension = imageFile.name.split('.').pop();
                                    designFile.url = imageUrl;
                                }
                                item.printLogistic.states.uploading = false;
                            });
                        }

                    } catch (error) {
                        console.log(error);
                        toastr.error('Error upload images!');
                    }
                }
            };

            $scope.printLogistic_uploads = function (files) 
            {
                if (typeof googleCloudStorageBucket != 'undefined') {
                    baseFileManagerUrl = googleCloudStorageBucket;
                }
                return new Promise(function (resolve, reject) {
                    Upload.upload({
                        url: baseFileManagerUrl + '/upload',
                        data: { upload: files, type: 'design' }
                    }).then(function (resp) {
                        if (resp.data.status === 'successful') {
                            let upload = resp.data.upload;
                            resolve(upload);
                        } else {
                            reject(0);
                        }
                    }, function (resp) {
                        reject(0);
                    }, function (evt) {
                        $scope.progressPercentage = 100.0 * evt.loaded / evt.total;
                    });
                });
            };

            $scope.printLogistic_chooseDesign = function (design, designFile, item) {
                if (!design.is_design_comfirm) {
                    toastr.error('Design is not confirmed');
                    return;
                }
                if (designFile.url !== design.url) {
                    designFile.url = design.url;
                    designFile.extension = design.url.split('.').pop();
                    $scope.printLogistic_changeDesignUrl(designFile);
                    safeApply();
                }
            }

            $scope.printLogistic_changeDesignUrl = function (designFile)
            {
                console.log(designFile)
                designFile.extension = designFile.url.split('.').pop();
                designFile.designPositions = {};

                safeApply();
            }

            $scope.printLogistic_openFulfillForm = async function (orderOrCard) 
            {
                let order = angular.copy(orderOrCard);

                if (typeof orderOrCard.order_id != 'undefined') 
                {
                    $scope.loadingOrderInfo = true; 
                    order = await $scope.loadOrderInfo(orderOrCard.order_id, orderOrCard.locale_code);
                    $scope.loadingOrderInfo = false;

                    $scope.fulFillLocale = orderOrCard.locale_code;

                    safeApply();

                    if (!order) return toastr.error('Error! Cannot find order infomation...');

                } else {
                    if (typeof order.location != 'undefined' && order.location !== '') {
                        $scope.fulFillLocale = angular.copy(order.location);
                    } else {
                        $scope.fulFillLocale = null;
                    }
                }

                if (!$scope.printLogisticStates.initialized) {
                    await initializePrintLogistic();
                    $scope.printLogisticStates.initialized = true;
                }

                $scope.printLogisticCurrentOrder = angular.copy(order);
                $scope.getSuggestsPrinting($scope.printLogisticCurrentOrder.code);
                if ($scope.printLogisticCurrentOrder.attributes.customer_info) {
                    $scope.printLogisticCurrentOrder.customer.phone = $scope.printLogisticCurrentOrder.attributes.customer_info.phone;
                    $scope.printLogisticCurrentOrder.customer.full_name = $scope.printLogisticCurrentOrder.attributes.customer_info.full_name;
                }

                if ($scope.printLogisticCurrentOrder.shipping_type != 'express') {
                    $scope.printLogisticCurrentOrder.shipping_type = 'standard';
                }

                if ($scope.printLogisticCurrentOrder.customer) {

                    if (typeof $scope.printLogisticCurrentOrder.attributes.gift_info != 'undefined' && $scope.printLogisticCurrentOrder.attributes.gift_info.name) {
                        $scope.printLogisticCurrentOrder.customer.full_name = $scope.printLogisticCurrentOrder.attributes.gift_info.name;
                        if ($scope.printLogisticCurrentOrder.attributes.gift_info.phone) {
                            $scope.printLogisticCurrentOrder.customer.phone = $scope.printLogisticCurrentOrder.attributes.gift_info.phone;
                        }
                    }

                    $scope.printLogisticCurrentOrder.customer.full_name = $scope.capitalizeFirstLetter($scope.printLogisticCurrentOrder.customer.full_name);
                    if (window.user_email) {
                        $scope.printLogisticCurrentOrder.customer.email = window.user_email;
                    }
                }

                // init print logistic attr
                for (let i = 0; i < $scope.printLogisticCurrentOrder.items.length; i++) {
                    $scope.printLogisticCurrentOrder.items[i].printLogistic = {
                        artworks: {
                            front: {
                                location: 'front',
                            },
                            back: {
                                location: 'back',
                            },
                            right_sleeve: {
                                location: 'right_sleeve',
                            },
                            left_sleeve: {
                                location: 'left_sleeve',
                            },
                            neck: {
                                location: 'neck',
                            },
                        },
                        product_types: [],
                        product_colors: [],
                        skus: [],
                        states: {}
                    };
                }

                for (let i = 0; i < $scope.printLogisticCurrentOrder.items.length; i++) {
                    $scope.getCustomConfigs($scope.printLogisticCurrentOrder.items[i]);
                }

                fetchProfiles();

                $scope.checkEstimateCosts($scope.printLogisticCurrentOrder, toastr);

                safeApply();

                $('#modalFulfillPrintLogistic').modal({
                    modal: true,
                    persist: true,
                    position: [30, 0],
                    autoPosition: true
                });
            }

            $scope.printLogistic_copyProfileData = function(orderItem)
            {
                try 
                {
                    const profile = getSingleProfile(orderItem);

                    $scope.copyToClipboard(JSON.stringify(profile));
                    toastr.success('Copied profile!');

                } catch (error) {
                    console.warn(error);
                    toastr.error('Error, cannot copy profile!');
                }
            }

            $scope.printLogistic_pasteProfileData = function(orderItem)
            {
                try {
                    navigator.clipboard.readText()
                    .then(text => {

                        // const text = `{"product_id":23947,"is_template_product":false,"product_sku_id":2301060,"order_id":4695,"order_item_id":4695,"options":{"artworks":{"front":{"extension":"jpg","url":"https://assets.printerval.com/2023/05/10/wallpaperflare-8029884d02286ee23e29e3cf4af9443c.jpg"},"back":{}},"color":"Fire Red/ Arctic White","type":"Jacket","size":null,"sku":{"id":2,"sku":2602024,"brand":"AWDis","product_type":"Jacket","style":"AWJH043","product_name":"VARSITY JACKET","color":"Fire Red/ Arctic White","size":"M","selected":true}},"type":"print-logistic"}`;

                        profile = JSON.parse(text);
                        applySingleProfile(profile, orderItem);
                    })
                    .catch(err => {
                        console.error('Failed to read clipboard contents: ', err);
                    });
                } catch (error) {
                    toastr.error('Error, cannot paste profile!');
                    toastr.error(error);
                }
            }

            const getSingleProfile = function(orderItem)
            {
                const profiles = buildProfiles(angular.copy($scope.printLogisticCurrentOrder));

                const filteredProfiles = profiles.filter(profile => {
                    return profile.order_item_id == orderItem.id 
                });

                if (filteredProfiles.length) return filteredProfiles[0];
            }

            const applySingleProfile = async function(profile, orderItem)
            {
                const profileOptions = profile.options;

                if (typeof profileOptions.artworks != 'undefined') {
                    if (profileOptions.artworks.front.url) {
                        orderItem.printLogistic.artworks.front.url = profileOptions.artworks.front.url;
                    }
                    if (profileOptions.artworks.back.url) {
                        orderItem.printLogistic.artworks.back.url = profileOptions.artworks.back.url;
                    }
                    if (profileOptions.artworks.right_sleeve.url) {
                        orderItem.printLogistic.artworks.right_sleeve.url = profileOptions.artworks.right_sleeve.url;
                    }
                    if (profileOptions.artworks.left_sleeve.url) {
                        orderItem.printLogistic.artworks.left_sleeve.url = profileOptions.artworks.left_sleeve.url;
                    }
                    if (profileOptions.artworks.neck.url) {
                        orderItem.printLogistic.artworks.neck.url = profileOptions.artworks.neck.url;
                    }
                }
                if (typeof profileOptions.type != 'undefined') {
                    orderItem.printLogistic.type = profileOptions.type;
                }
                if (typeof profileOptions.size != 'undefined') {
                    orderItem.printLogistic.size = profileOptions.size;
                }
                if (typeof profileOptions.color != 'undefined') {
                    orderItem.printLogistic.color = profileOptions.color;
                }

                await $scope.changeProductTypeOption(orderItem);
                await $scope.changeProductColorOption(orderItem);
                await $scope.changeProductSizeOption(orderItem);

                if (typeof profileOptions.sku != 'undefined') {
                    setPrintSku(orderItem.printLogistic, profileOptions.sku);
                }
            }

            function safeApply() {
                if ($scope.$root.$$phase !== '$apply' && $scope.$root.$$phase !== '$digest') {
                    $scope.$apply();
                }
            }
        }
    };
});
