'use strict';

angular
    .module('admin-team-profile', ['download'])
    .factory("adminTeamProfile", [
        'AppUtil', 'APIName', 'Events', '_', 'app', '$stateParams',
        function (AppUtil, APIName, Events, _, app, $stateParams) {

            return {
                // Load event for both project & team
                loadEvents: function (project, lastCreateDate, callback) {

                    if (!angular.isObject(project))
                        return;

                    var objUrl = {
                        method: APIName.GET_TEAM_HISTORY.method,
                        name: APIName.GET_TEAM_HISTORY.name + $stateParams.id
                    };

                    var types = [], events = Events.TEAM;

                    events.SHARED_SECURE_MAIL = Events.PROJECT.SHARED_SECURE_MAIL;

                    // Parameter
                    var param = {
                        last_update: 0, // Default value should be 1970. 1431835243
                        page_size: app.EVENT_PAGE_SIZE
                    };

                    var cb = callback;

                    // Without last update
                    if (angular.isFunction(lastCreateDate)) {

                        cb = lastCreateDate;
                    } else {
                        param.last_update = lastCreateDate;
                    }

                    // Get event type
                    _.forIn(events, function (v) {

                        (v.code) && (types.push(v.code));
                    });

                    param.history_types = types.join(",");
                    // Call request
                    AppUtil.createRequest(objUrl, param, function (res) {

                        if (res.hasOwnProperty("data")) {

                            cb && cb(res);
                        }
                    });
                }
            };
        }])

    .controller('AdminTeamProfile', [
        '$scope', 'AppUtil', 'APIName', '$http', '$stateParams', 'Events', 'util', 'adminTeamProfile',
        '_', 'objectStatus', '$state', 'checkbox', 'session', '$compile', '$route', 'app', 'APIStatus',
        'Auth', 'Download', 'userConfig', 'exchangeRate', '$anchorScroll', 'sortPage', '$window', '$uibModal',

        function ($scope, AppUtil, APIName, $http, $stateParams, Events, util, adminTeamProfile,
                  _, objectStatus, $state, checkbox, session, $compile, $route, app, APIStatus,
                  Auth, Download, userConfig, exchangeRate, $anchorScroll, sortPage, $window, $uibModal) {
            $scope.script_pattern = app.SCRIPT_PATTERN;

            $scope.currentUser = session.getUser();

            $scope.featureType = [
                {type: 'upload', name: util.translate('label.team.drm')},
                {type: 'non-drm', name: util.translate('label.team.non_drm')}
            ];

            $scope.teamPaymentInfo = null;

            $scope.changeTab = function (tab) {
                $scope.tab = tab;
                checkbox.cleanUp();
                if (tab === 1) {
                    getTeamInfo();
                }
                if (tab === 2) {
                    getTeamSetting();
                    AppUtil.createRequest({
                        name: APIName.GET_TEAM_PAYMENT_INFO.name + $scope.team_id,
                        method: APIName.GET_TEAM_PAYMENT_INFO.method
                    }, null, function (res) {
                        if (res && res.status === 200) {

                            $scope.teamPaymentInfo = res.data || {};
                            if (typeof $scope.teamPaymentInfo.price === 'undefined' || isNaN($scope.teamPaymentInfo.price)) {
                                $scope.teamPaymentInfo.price = 0;
                            }

                            var packageId = $scope.teamPaymentInfo.pricing_package_id || $scope.teamPaymentInfo.package_id || $scope.teamPaymentInfo.packageId;
                            if (packageId) {
                                AppUtil.createRequest({
                                    name: APIName.GET_PACKAGE_DETAIL.name + packageId,
                                    method: APIName.GET_PACKAGE_DETAIL.method,
                                    headers: {
                                        'auth-token': Auth.getToken()
                                    }
                                }, null, function (pkgRes) {
                                    console.log('Package detail response:', pkgRes);
                                    if (pkgRes && pkgRes.status === 200 && pkgRes.data) {
                                        $scope.teamPaymentInfo.package_name = pkgRes.data.name || '-';
                                        $scope.teamPaymentInfo.currency = pkgRes.data.currency || 'USD';
                                        $scope.teamPaymentInfo.billing_cycle = pkgRes.data.billing_cycle || 'MONTHLY';
                                        $scope.teamPaymentInfo.price = pkgRes.data.price || 0;
                                        console.log('Price after setting from API:', $scope.teamPaymentInfo.price, typeof $scope.teamPaymentInfo.price);
                                        if (isNaN($scope.teamPaymentInfo.price)) $scope.teamPaymentInfo.price = 0;
                                    } else {
                                        // fallback if error
                                        $scope.teamPaymentInfo.package_name = $scope.teamPaymentInfo.package_name || $scope.teamPaymentInfo.packageName || $scope.teamPaymentInfo.name || '-';
                                        $scope.teamPaymentInfo.currency = $scope.teamPaymentInfo.currency || 'USD';
                                        $scope.teamPaymentInfo.billing_cycle = $scope.teamPaymentInfo.billing_cycle || $scope.teamPaymentInfo.billingCycle || 'MONTHLY';
                                        $scope.teamPaymentInfo.price = $scope.teamPaymentInfo.price || $scope.teamPaymentInfo.amount || 0;
                                        console.log('Price after setting from fallback (if applicable):', $scope.teamPaymentInfo.price, typeof $scope.teamPaymentInfo.price);
                                    }
                                    $scope.teamPaymentInfo.expiry_date = $scope.teamPaymentInfo.expiry_date || $scope.teamPaymentInfo.expired_date || $scope.teamPaymentInfo.expiredDate || null;
                                    $scope.loadPaymentHistory();
                                }, function () {
                                    // fallback if error
                                    $scope.teamPaymentInfo.package_name = $scope.teamPaymentInfo.package_name || $scope.teamPaymentInfo.packageName || $scope.teamPaymentInfo.name || '-';
                                    $scope.teamPaymentInfo.currency = $scope.teamPaymentInfo.currency || 'USD';
                                    $scope.teamPaymentInfo.billing_cycle = $scope.teamPaymentInfo.billing_cycle || $scope.teamPaymentInfo.billingCycle || 'MONTHLY';
                                    $scope.teamPaymentInfo.price = $scope.teamPaymentInfo.price || $scope.teamPaymentInfo.amount || 0;
                                    $scope.teamPaymentInfo.expiry_date = $scope.teamPaymentInfo.expiry_date || $scope.teamPaymentInfo.expired_date || $scope.teamPaymentInfo.expiredDate || null;
                                    $scope.loadPaymentHistory();
                                });
                            } else {
                                // fallback if not packageId
                                $scope.teamPaymentInfo.package_name = $scope.teamPaymentInfo.package_name || $scope.teamPaymentInfo.packageName || $scope.teamPaymentInfo.name || '-';
                                $scope.teamPaymentInfo.currency = $scope.teamPaymentInfo.currency || 'USD';
                                $scope.teamPaymentInfo.billing_cycle = $scope.teamPaymentInfo.billing_cycle || $scope.teamPaymentInfo.billingCycle || 'MONTHLY';
                                //$scope.teamPaymentInfo.price = $scope.teamPaymentInfo.price || $scope.teamPaymentInfo.amount || 0;
                                $scope.teamPaymentInfo.expiry_date = $scope.teamPaymentInfo.expiry_date || $scope.teamPaymentInfo.expired_date || $scope.teamPaymentInfo.expiredDate || null;
                                $scope.loadPaymentHistory();
                            }
                        } else {
                            $scope.teamPaymentInfo = {
                                package_name: '-',
                                currency: 'USD',
                                billing_cycle: 'MONTHLY',
                                //price: 0,
                                expiry_date: null
                            };
                            $scope.loadPaymentHistory();
                        }
                    }, function () {
                        $scope.teamPaymentInfo = {
                            package_name: '-',
                            currency: 'USD',
                            billing_cycle: 'MONTHLY',
                            //price: 0,
                            expiry_date: null
                        };
                        $scope.loadPaymentHistory();
                    });
                    return;
                }
                if (tab === 4) {
                    $scope.selectedItems = [];
                    $scope.table_member.draw();
                }
                localStorage.tabs = tab;
            };

            var activeTab = localStorage.tabs;
            $scope.tab = Number(activeTab) || 1;
            localStorage.tabs = $scope.tab;

            $scope.specialCharPattern = app.SPECIAL_CHARS_PATTERN;
            $scope.urlPattern = app.URL_PATTERN;

            $scope.currentUser = session.getUser();
            $scope.isJapaneseLanguage = session.isJapanese();
            $scope.currentLang = session.getCurrentLanguage();

            $scope.team_id = $stateParams.id;
            $scope.company_id = $stateParams.company_id;

            $scope.teamId = $scope.currentUser.team_id;

            $scope.tab_team = util.translate("tab_title.team_setting");
            $scope.tab_bill = util.translate("tab_title.team_billing");
            $scope.tab_history = util.translate("tab_title.history");
            $scope.tab_member = util.translate("tab_title.members");

            $scope.disable = false;
            var params = {};
            if ($scope.currentUser.role_id === userConfig.SUPER_ADMIN.role) {
                params.company_id = $stateParams.company_id;
            }
            
            $scope.paymentMethods = [
                {type: 0, name: util.translate('payment_method.online')},
                {type: 1, name: util.translate('payment_method.offline')}
            ];

            $scope.billingCycles = [
                {value: 30, name: util.translate('billing_cycle.30d')},
                {value: 60, name: util.translate('billing_cycle.60d')},
                {value: 90, name: util.translate('billing_cycle.90d')}
            ];

            function _getBillingCycle(billing) {
                if (angular.isDefined(billing)) {
                    if (angular.isObject(billing)) {
                        return billing.name;
                    } else {

                        var _billing = _.find($scope.billingCycles, {value: billing});
                        if (_billing) {
                            return _billing;
                        } else {
                            return $scope.billingCycles[0];
                        }
                    }
                }
            }

            $scope.teamData = {};
            $scope.teamBilling = {};

            $scope.historyParams = {
            team_id: $scope.team_id,
            payment_type: 0,
            sort_field: 'createdDate',
            asc_sort: false,
            page_number: 1,
            page_size: 10
            };

            $scope.historyData = [];
            $scope.totalRecords = 0;
            $scope.rowOptions = [10, 25, 50, 100];
            $scope.loading = false;
            $scope.errorMessage = '';
            $scope.showReceiptDialog = false;
            $scope.receiptData = null;

            // DataTables cho Payment History
            var paymentHistoryPagingSettings = JSON.parse(localStorage.getItem(sortPage.PAYMENT_HISTORY));
            if (!paymentHistoryPagingSettings) {
                paymentHistoryPagingSettings = {
                    page_size: app.LIST_PAGE_SIZE,
                    page_number: 1,
                    display_start: 0,
                    sort_key: 0,
                    asc_sort: false
                }
            }

            $scope.paymentHistoryTable;

            $scope.paymentHistoryOpts = {
                "order": [
                    paymentHistoryPagingSettings.sort_key,
                    paymentHistoryPagingSettings.asc_sort ? "asc" : "desc"
                ],
                "searching": false,
                "lengthChange": false,
                "info": false,
                pageLength: paymentHistoryPagingSettings.page_size,
                displayStart: paymentHistoryPagingSettings.display_start,
                "ajax": function (data, callback) {
                    var storeParams = {
                        page_size: data.length,
                        display_start: 0,
                        sort_key: data.order[0].column,
                        page_number: data.start / data.length + 1,
                        sort_field: data.columns[data.order[0].column].data,
                        asc_sort: data.order[0].dir === "asc"
                    };

                    var params = {
                        payment_type: 0,
                        page_size: data.length,
                        page_number: data.start / data.length + 1,
                        sort_field: data.columns[data.order[0].column].data,
                        asc_sort: data.order[0].dir === "asc"
                    };

                    var objUrl = {
                        url: APIName.GET_PAYMENT_HISTORY.name + $stateParams.id + APIName.GET_PAYMENT_HISTORY.suffix,
                        method: APIName.GET_PAYMENT_HISTORY.method
                    };

                    AppUtil.createRequest(objUrl, params, function (response) {
                        var json = {
                            "draw": data.draw,
                            "recordsTotal": response.data.total_elements,
                            "recordsFiltered": response.data.total_elements,
                            "data": []
                        };
                        localStorage.setItem(sortPage.PAYMENT_HISTORY, JSON.stringify(storeParams));

                        $.each(response.data.content, function (index, payment) {
                            var paymentInfo = {
                                createdDate: payment.create_date,
                                totalPayment: payment.total_payment,
                                pricingPackage: payment.pricing_package,
                                paymentInfoId: payment.payment_info_id,
                                numberUser: payment.number_user || 0,
                                creditApplied: payment.credit_applied || 0,
                                totalPrice: payment.total_price || 0
                            };
                            json.data.push(paymentInfo);
                        });

                        console.log('DataTable data:', json.data);
                        callback(json);
                    }, function(error) {
                        console.error('Error loading payment history:', error);
                        var json = {
                            "draw": data.draw,
                            "recordsTotal": 0,
                            "recordsFiltered": 0,
                            "data": []
                        };
                        callback(json);
                    });
                },
                "rowCallback": function (row, data) {
                    $("td:eq(0)", row).addClass("text-center").html("<div>" + util.formatDateBasedOnDiff(data.createdDate, "", session.getCurrentLanguage(), session.getUser().time_zone) + "</div>");

                    var currency = data.pricingPackage ? data.pricingPackage.currency : 'USD';
                    if (currency === 'VND') {
                        $("td:eq(1)", row).addClass("text-right").html("<div style='padding-right: 20px'>{{" +
                            data.totalPayment + " | currency : ''}}&nbsp;" + "<span ng-i18next='label.currency_unit.vnd'/></div>");
                    } else if (currency === 'YEN') {
                        $("td:eq(1)", row).addClass("text-right").html("<div style='padding-right: 20px'>" +
                            "<span ng-i18next='label.currency_unit.yen'/>&nbsp;{{" + data.totalPayment + " | currency : ''}}</div>");
                    } else {
                        $("td:eq(1)", row).addClass("text-right").html("<div style='padding-right: 20px'>" +
                            "<span ng-i18next='label.currency_unit.usd'/>&nbsp;{{" + data.totalPayment + " | currency : ''}}</div>");
                    }

                    var html = $compile("<button class='btn btn-sm btn-default' ng-click='viewReceipt(" + JSON.stringify(data).replace(/"/g, '&quot;') + ")'><i class='fa fa-eye'></i></button>")($scope);
                    $("td:eq(2)", row).addClass("text-center").html(html);
                },
                "drawCallback": function (t) {
                    $compile(t.nTBody)($scope);
                },
                "columns": [
                    {"data": "createdDate"},
                    {"data": "totalPayment"},
                    {"data": "paymentInfoId"}
                ],
                "columnDefs": [
                    {'orderable': false, 'targets': [2]}
                ]
            };

            function getTeamInfo() {
                AppUtil.createRequest({
                    name: APIName.GET_TEAM.name + $stateParams.id,
                    method: "GET"
                }, {}, function (data) {

                    //disable change password & email button when the team is on pending status
                    if (data.data.status === objectStatus.PENDING) {
                        $scope.disable = true;
                    }

                    // Decode html
                    $scope.teamData.name = data.data.name;
                    $scope.teamData.emailAddress = data.data.email_address;
                    $scope.teamData.createDate = util.formatDateBasedOnDiff(data.data.create_date, "", session.getCurrentLanguage(), session.getUser().time_zone);
                    $scope.teamData.numberOfUser = data.data.number_of_user;
                    $scope.teamData.projectUsage = data.data.projects_usage;
                    $scope.teamData.payment_type = data.data.payment_type;
                    $scope.teamData.company_id = data.data.company_id;
                    $scope.teamData.status = data.data.status;
                    $scope.teamData.accessKey = data.data.access_key;
                    $scope.teamData.trial = (data.data.status === objectStatus.TRIAL);
                    $scope.teamData.isUseSecureDrive = data.data.use_secure_drive;
                    $scope.teamData.isUseSecureMail = data.data.use_secure_mail;
                    $scope.teamData.totalTransmissions = data.data.total_transmissions;
                    $scope.featureSetting = data.data.feature_setting;
                    $scope.teamData.featureSetting = _.find($scope.featureType, {type: $scope.featureSetting}).type;

                    // Cache origin
                    var orgin = angular.copy($scope.teamData);

                    // Watch model to see the change
                    $scope.$watch("teamData", function (newValue) {
                        // Compare input values with origin values
                        if (!newValue.isUseSecureMail && !orgin.isUseSecureMail) {
                            $scope.teamData.totalTransmissions = data.data.total_transmissions;
                            $scope.featureSetting = data.data.feature_setting;
                            $scope.teamData.featureSetting = _.find($scope.featureType, {type: $scope.featureSetting}).type;
                        }
                        $scope.isChange = !angular.equals(newValue, orgin);
                    }, true);

                }, function () {
                    $state.go(AppUtil.getLocation($scope.currentUser));
                });
            }

            getTeamInfo();

            function getTeamSetting() {
                AppUtil.createRequest({
                    name: APIName.GET_TEAM_SETTING.name,
                    method: APIName.GET_TEAM_SETTING.method
                }, {team_id: $scope.team_id, type: 0}, function (data) {
                    $scope.teamBilling.paymentType = data.data.payment_type;
                    $scope.teamBilling.billingCycle = $scope.currentBillingCycle = _getBillingCycle(data.data.billing_cycle);
                    setTimeout(function() {
                        if ($scope.paymentHistoryTable) {
                            $scope.paymentHistoryTable.draw();
                        }
                    }, 100);
                });
            }

            $scope.doBack = function () {
                $window.history.back();
            };

            $scope.submit = false;

            $scope.updateTeamInfo = function (valid) {
                if (!valid)
                    return;

                $scope.submit = true;
                var params = {
                    team_name: $scope.teamData.name,
                    is_trial: $scope.teamData.trial,
                    use_secure_drive: $scope.teamData.isUseSecureDrive,
                    use_secure_mail: $scope.teamData.isUseSecureMail
                };
                if ($scope.teamData.isUseSecureMail) {
                    params.feature_setting = $scope.teamData.featureSetting;
                    params.transmission_point = $scope.teamData.totalTransmissions
                }

                AppUtil.createRequest({
                    url: APIName.USER_UPDATE_TEAM.name + $stateParams.id,
                    method: APIName.USER_UPDATE_TEAM.method
                }, params, function () {

                    $scope.submit = false;
                    getTeamInfo();
                    AppUtil.showSuccess({
                        text: util.translate('default_toast.save_success')
                    });
                }, function (error) {
                    if (error.status === 1801) {
                        AppUtil.showError({
                            text: util.translate("errors.error_team_name")
                        });
                    } else if (error.status === 2713) {
                        AppUtil.showError({
                            text: util.translate("errors.customer_stripe")
                        });
                    } else {
                        AppUtil.showError({
                            text: util.translate("sever_errors." + error.status)
                        });
                    }
                    $scope.submit = false;
                });
            };

            // load event for team
            $scope.historyEvents = [];

            var EventTeam = $scope.Events = Events.TEAM;
            var EventProject = $scope.Events = Events.PROJECT;

            // whether a value is in the list or not
            $scope.isIn = function (value, list) {

                return util.contains(list, value);
            };

            // Show time with specific format
            $scope.showTimeFormat = function (date, format) {
                var fm = (format || "MM/DD/YYYY");
                return util.formatDate(date, fm, session.getCurrentLanguage(), session.getUser().time_zone);
            };

            // Member list
            $scope.teamMembers = {};

            var objUrl = {
                method: APIName.USER_LIST_ALL_BY_TEAM_ID.method,
                name: APIName.USER_LIST_ALL_BY_TEAM_ID.name + $stateParams.id + APIName.USER_LIST_ALL_BY_TEAM_ID.surfix
            };

            AppUtil.createRequest(objUrl, {}, function (res) {
                $scope.teamMembers = res.data;
            });

            // Get member name
            $scope.getMemberName = function (id) {

                var name = util.translate("pronoun.unknow");

                var m = _.find($scope.teamMembers, {user_id: id});

                if (m) {

                    name = m.first_name + " " + m.last_name;
                    if (session.getCurrentLanguage() === 'ja')
                        name = m.last_name + " " + m.first_name;
                }
                return name;
            };

            $scope.handleLessLength = function (str) {
                if (str) {
                    return (str.length > 25) ? str.substring(0, 25) + '...' : str;
                } else {
                    return '';
                }
            }

            $scope.getNameOrder = function (first, last) {
                var name = first + " " + last;
                if (session.getCurrentLanguage() !== 'en')
                    name = last + " " + first;
                return name;
            };

            // Get action text
            $scope.getText = function (hItem) {

                var content;

                // Detail of history
                var result = hItem.data && hItem.data.result,
                    length = (result) ? result.length : 0;

                switch (hItem.history_type) {

                    // Project
                    case EventTeam.PROJECT_ADDED.code:

                        content = util.translate("history.project.add_project");
                        break;

                    case EventTeam.PROJECT_UPDATED.code:

                        content = util.translate("history.project.update_project");
                        break;

                    case EventTeam.PROJECT_DELETED.code:

                        content = util.translate("history.project.delete_project");
                        break;

                    case EventTeam.PROJECT_COPY.code:

                        content = util.translate("history.project.copy_project");
                        break;

                    case EventTeam.TRANSFER_PROJECT.code:

                        content = util.translate("history.project.transferred_project");
                        break;
                    // User
                    // I think we are not allowed to add a user
                    case EventTeam.USER_ADDED.code:

                        content = util.translate("history.user.add_user");
                        break;

                    case EventTeam.USER_UPDATED.code:

                        content = util.translate("history.user.update_user");
                        break;

                    case EventTeam.USER_DELETED.code:

                        content = util.translate("history.user.delete_user");
                        break;

                    case EventTeam.USER_LOGIN.code:

                        content = util.translate("history.user.log_in");
                        break;

                    case EventTeam.USER_LOGOUT.code:

                        content = util.translate("history.user.log_out");
                        break;
                    case EventTeam.CREATE_MEMBER_GROUP.code:

                        content = util.translate("history.user_group.create_group");
                        break;

                    case EventTeam.UPDATE_MEMBER_GROUP.code:

                        content = util.translate("history.user_group.update_group");
                        break;

                    case EventTeam.DELETED_MEMBER_GROUP.code:

                        content = util.translate("history.user_group.delete_group");
                        break;
                    case EventTeam.ADD_MEMBER.code:

                        content = (length > 1) ? util.translate("history.user_group.add_member_groups", {"count": length})
                            : util.translate("history.user_group.add_member_group");
                        break;

                    case EventTeam.REMOVE_MEMBER.code:
                        content = (length > 1) ? util.translate("history.user_group.remove_member_groups", {"count": length})
                            : util.translate("history.user_group.remove_member_group");
                        break;

                    case EventTeam.MOVE_MEMBER.code:
                        content = (length > 1) ? util.translate("history.user_group.move_member_groups", {"count": length})
                            : util.translate("history.user_group.move_member_group");
                        break;

                    case EventProject.SHARED_SECURE_MAIL.code:
                        content = util.translate("history.project.share_secure_mail");
                        break;

                    default:
                        break;
                }

                return content;
            };

            // Set some letiables
            $scope.isEventLoading = false;
            $scope.noEvent = false;

            // Set then call
            ($scope.loadEvent = function () {

                // Is not loading & must has event
                // noEvent: Display no record on UI
                // isEventLoading: Display loader
                if (!$scope.isEventLoading && !$scope.noEvent) {

                    $scope.isEventLoading = true;

                    var length = $scope.historyEvents.length;

                    // Get last record
                    var lastDate = (length > 0) ? ($scope.historyEvents[length - 1].last_update || 0) : 0;

                    // Do load event
                    adminTeamProfile.loadEvents({}, lastDate, function (res) {
                        $scope.isEventLoading = false;

                        var data = res.data.content;
                        
                        if (data.length === 0) {

                            $scope.noEvent = true;
                            // Return
                            return;
                        }

                        // Concat
                        $scope.historyEvents = $scope.historyEvents.concat(data);
                    });

                }
            })();

            $scope.gotoTop = function () {
                // set the location.hash to the id of
                // the element you wish to scroll to.
                // $location.hash('top-page');

                // call $anchorScroll()
                $anchorScroll();
            };

            // show details modal
            $scope.openDetailsModal = function (item) {
                return $uibModal.open({
                    backdrop: 'static',
                    templateUrl: 'js/components/share/history-detail/history-detail-tmpl.html',
                    windowClass: 'large-Modal',
                    controller: 'HistoryDetail as ctrl',
                    resolve: {
                        history: function () {
                            return item;
                        }
                    }
                });
            };

            $scope.confirmActivation = function () {

                // Show modal
                AppUtil.confirm({
                    title: util.translate("message.team_activation.title"),
                    message: util.translate("message.team_activation.content"),
                    buttons: [{
                        label: util.translate("button.cancel"),
                        cssClass: 'btn btn-warning',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: util.translate("button.ok"),
                        cssClass: 'btn btn-primary',
                        action: function (dialog) {
                            // Do active
                            $scope.doActiveUser();
                            dialog.close();
                        }
                    }]
                });
            };

            $scope.confirmDeleteForever = function () {

                // Show modal
                AppUtil.confirm({
                    title: util.translate("message.team_delete.title"),
                    message: util.translate("message.team_delete.content"),
                    buttons: [{
                        label: util.translate("button.cancel"),
                        cssClass: 'btn btn-warning',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: util.translate("button.ok"),
                        cssClass: 'btn btn-primary',
                        action: function (dialog) {
                            // Do delete forever
                            $scope.doDeleteForeverTeam();
                            dialog.close();
                        }
                    }]
                });
            };

            //active user & team
            $scope.doActiveUser = function () {
                var objUrl = {
                    method: APIName.TEAM_STATUS.method,
                    name: APIName.TEAM_STATUS.name + $scope.team_id + APIName.TEAM_STATUS.surfix + 1
                };

                AppUtil.createRequest(objUrl, {}, function (res) {
                    if (res.status === 200) {
                        $scope.teamData.status = res.data.status;
                        AppUtil.showSuccess({
                            text: util.translate("default_toast.activate_success")
                        });
                    }

                }, function (error) {
                    AppUtil.showError({
                        text: util.translate("sever_errors." + error.status)
                    });
                });
            };

            //delete forever user & team
            $scope.doDeleteForeverTeam = function () {
                var objUrl = {
                    method: APIName.TEAM_STATUS.method,
                    name: APIName.TEAM_STATUS.name + $scope.team_id + APIName.TEAM_STATUS.surfix + 3
                };

                AppUtil.createRequest(objUrl, {}, function (res) {
                    if (res.status === 200) {
                        $scope.teamData.status = res.data.status;
                        AppUtil.showSuccess({
                            text: util.translate("default_toast.delete_success")
                        });
                        if ($scope.currentUser.role_id === userConfig.COMPANY_ADMIN.role) {
                            $state.go("teamList");
                        } else {
                            $state.go("companyProfile", {id: $stateParams.company_id});
                        }
                    }

                });
            };

            var userPagingSettings = JSON.parse(localStorage.getItem(sortPage.TEAM_USER_LIST));
            if (!userPagingSettings) {
                userPagingSettings = {
                    search_key: "",
                    page_size: app.LIST_PAGE_SIZE,
                    page_number: 1,
                    display_start: 0,
                    sort_key: 4,
                    asc_sort: false
                }
            }

            // Datatable obj
            $scope.table_member = {};
            // $scope.tblPaymentHisOnline = {};
            // $scope.tblPaymentHisOffline = {};

            // Selected items
            $scope.selectedItems = [];
            // Datatable options
            $scope.opts = {
                "order": [
                    userPagingSettings.sort_key,
                    userPagingSettings.asc_sort ? "asc" : "desc"
                ],
                "search": {
                    "search": userPagingSettings.search_key
                },
                pageLength: userPagingSettings.page_size,
                displayStart: userPagingSettings.display_start,
                "ajax": function (data, callback) {
                    $scope.isLocalChange = true;

                    var storeParams = {
                        search_key: "",
                        page_size: data.length,
                        display_start: 0,
                        sort_key: data.order[0].column,
                        page_number: data.start / data.length + 1,
                        asc_sort: data.order[0].dir === "asc"
                    };

                    var params = {
                        team_id: $scope.team_id,
                        search_key: data.search.value.trim(),
                        page_size: data.length,
                        page_number: data.start / data.length + 1,
                        sort_field: data.columns[data.order[0].column].data,
                        asc_sort: data.order[0].dir === 'asc'
                    };

                    AppUtil.createRequest(APIName.USER_LIST, params, function (res) {
                        var json = {
                            "recordsTotal": res.data.total_elements,
                            "recordsFiltered": res.data.total_elements,
                            "data": []
                        };

                        localStorage.setItem(sortPage.TEAM_USER_LIST, JSON.stringify(storeParams));

                        if (res.data.total_elements > 0) {
                            
                            $.each(res.data.content, function (key, value) {
                                var roleName = "";
                                if (value.role_id === 1) {
                                    roleName = util.translate("label.user.system_role.admin");
                                }
                                if (value.role_id === 2) {
                                    roleName = util.translate("label.user.system_role.manager");
                                }
                                if (value.role_id === 3) {
                                    roleName = util.translate("label.user.system_role.user");
                                }
                                if (value.role_id === 4) {
                                    roleName = util.translate("label.user.system_role.guest");
                                }
                                json.data.push({
                                    userId: value.user_id,
                                    firstName: value.first_name,
                                    lastName: value.last_name,
                                    mailAddress: value.mail_address,
                                    createdDate: value.signup_date,
                                    role: roleName,
                                    roleId: value.role_id
                                });
                            });
                        }
                        console.log('DTest json.data', json.data);
                        callback(json);

                        $scope.isLocalChange = false;
                    });
                },
                "rowCallback": function (row, data) {
                    if (data.roleId === 1) {
                        $("td:eq(0)", row).addClass("text-center").html("<span></span>");
                    } else {
                        $("td:eq(0)", row).addClass("text-center").html("<input icheck-table type='checkbox' class='icheckbox' role='child-checkbox' id='" + data.userId + "'>");
                    }

                    var hasLink = $scope.teamData.company_id && $scope.team_id && data.userId;
                    if ($scope.isJapaneseLanguage) {
                        if (hasLink) {
                            $("td:eq(1)", row).html(
                                '<a href="#" class="name member-link"><div class="ellipsis" mytip="' + data.lastName + '" mytip-placement="top-left" mytip-show-when="200">' + data.lastName + '</div></a>'
                            );
                        } else {
                            $("td:eq(1)", row).html('<span>-</span>');
                        }
                        $("td:eq(2)", row).addClass("hidden-sm-phone hidden-xs hidden-sm").html('<div class="ellipsis"  mytip="' + data.firstName + '" mytip-placement="top-left" mytip-show-when="200">' + data.firstName + '</div>');
                    } else {
                        if (hasLink) {
                            $("td:eq(1)", row).html(
                                '<a href="#" class="name member-link"><div class="ellipsis"  mytip="' + data.firstName + '" mytip-placement="top-left" mytip-show-when="200"><span>' + data.firstName + '</span></div></a>'
                            );
                        } else {
                            $("td:eq(1)", row).html('<span>-</span>');
                        }
                        $("td:eq(2)", row).addClass("hidden-sm-phone hidden-xs hidden-sm").html('<div class="ellipsis"  mytip="' + data.lastName + '" mytip-placement="top-left" mytip-show-when="200">' + data.lastName + '</div>');
                    }

                    $("td:eq(3)", row).html("<div class='ellipsis'>" + data.mailAddress + "</div>");

                    $("td:eq(4)", row).addClass("hidden-sm-phone hidden-xs hidden-sm").html("<div>" + util.formatDateBasedOnDiff(data.createdDate, "", session.getCurrentLanguage(), session.getUser().time_zone) + "</div>");

                    if (data.roleId === 1) {
                        $("td:eq(5)", row).html("<span class='label label-success'>" + data.role + "</span>");
                    } else if (data.roleId === 2) {
                        $("td:eq(5)", row).html("<span class='label label-primary'>" + data.role + "<span>");
                    } else {
                        $("td:eq(5)", row).html("<span class='label label-default'>" + data.role + "<span>");
                    }

                    if (hasLink) {
                        $(row).find('.member-link').on('click', function(e) {
                            e.preventDefault();
                            $state.go('memberProfile', {
                                company_id: $scope.teamData.company_id,
                                team_id: $scope.team_id,
                                id: data.userId
                            });
                            $scope.$apply();
                        });
                    }
                },
                "drawCallback": function (s) {
                    checkbox.bindCheck(s.nTable, function (array) {
                        $scope.selectedItems = array;
                        $scope.$digest();
                    });
                    $compile(s.nTBody)($scope);
                },
                "columns": [
                    {"data": null}, // Checkbox
                    {"data": "firstName"},
                    {"data": "lastName"},
                    {"data": "mailAddress"},
                    {"data": "createdDate"},
                    {"data": "role"}
                ],
                "columnDefs": [
                    {'orderable': false, 'targets': [0]}
                ],
                destroy: true
            };

            // Show confirm remove
            $scope.confirmDelete = function () {

                // Show modal
                AppUtil.confirm({
                    title: util.translate("message.member.title"),
                    message: util.translate("message.member.content"),
                    buttons: [{
                        label: util.translate("button.cancel"),
                        cssClass: 'btn btn-warning',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: util.translate("button.ok"),
                        cssClass: 'btn btn-primary',
                        action: function (dialog) {
                            // Do delete
                            doDeleteUser();
                            dialog.close();
                        }
                    }]
                });
            };

            // Do delete
            function doDeleteUser() {

                var items = $scope.selectedItems;
                if (items.length === 0)
                    return;
                var reqs = [];
                items.forEach(function (item) {
                    var params = {
                        user_id: item,
                        team_id: $stateParams.id
                    };

                    reqs.push(AppUtil.createRequest(APIName.DELETE_USER, params, function (res) {
                        if (res.status === 200) {
                            AppUtil.createToast({
                                text: util.translate("default_toast.delete_success"),
                                'type': 'success'
                            });
                            $scope.table_member.draw();
                        } else {
                            AppUtil.showError({text: util.translate("sever_errors." + res.status)});
                        }

                        // Reset selectedItems
                        $scope.selectedItems = [];
                        checkbox.cleanUp();
                    }, function (err) {
                        AppUtil.showError({text: util.translate("sever_errors." + err.status)});
                        // Close toast
                        AppUtil.closeToast();
                        // Create error
                        // Clean
                        $scope.selectedItems = [];
                        checkbox.cleanUp();
                    }));
                });

            }

            /*****************
             * For billing tab
             *****************/
            $scope.pattern_card_number = app.CREDIT_CARD;

            function makePaymentParam(data, paymentType) {
                return {
                    // team_id: $scope.team_id,
                    payment_type: paymentType,
                    page_size: data.length,
                    page_number: data.start / data.length + 1,
                    sort_field: data.columns[data.order[0].column].data,
                    asc_sort: data.order[0].dir === "asc"
                };
            }

            // online payment history table opts
            $scope.paymentHisOnlineOpts = {
                "order": [1, "desc"],
                "searching": false,
                "ajax": function (data, callback) {
                    AppUtil.createRequest({
                        url: APIName.GET_PAYMENT_INFO.name + $stateParams.id + APIName.GET_PAYMENT_INFO.suffix,
                        method: APIName.GET_PAYMENT_INFO.method
                    }, makePaymentParam(data, 0), function (dataCallback) {
                        var json = {
                            "draw": data.draw,
                            "recordsTotal": dataCallback.data.total_elements,
                            "recordsFiltered": dataCallback.data.total_elements,
                            "data": []
                        };

                        $.each(dataCallback.data.content, function (index, payment) {
                            var totalPrice = 0;
                            var description = '';
                            var currency;

                            if (payment.user_price) {
                                totalPrice += payment.user_price.price;
                                description += payment.user_price.description;
                                currency = payment.user_price.currency;
                            }

                            if (payment.storage_price) {
                                totalPrice += payment.storage_price.price;
                                description += ', ' + payment.storage_price.description;
                                currency = payment.storage_price.currency;
                            }

                            var paymentInfo = {
                                // transmission_id: payment.transmission_id,
                                createdDate: payment.create_date,
                                totalPrice: totalPrice,
                                description: description,
                                paymentType: payment.card_info,
                                payment_info_id: payment.payment_info_id,
                                currency: currency
                            };

                            json.data.push(paymentInfo);
                        });


                        // Insert value
                        callback(json);
                    });
                },
                "rowCallback": function (row, data) {
                    // $("td:eq(0)", row).html("<div>" + data.transmission_id + "</div>");
                    $("td:eq(0)", row).addClass("text-center").html("<div>" + util.formatDateBasedOnDiff(data.createdDate, "", session.getCurrentLanguage(), session.getUser().time_zone) + "</div>");
                    if (data.currency === 'VND') {
                        $("td:eq(1)", row).addClass("text-right").html("<div style='padding-right: 20px'>" + data.totalPrice + " Đồng</div>");
                    } else if (data.currency === 'YEN') {
                        $("td:eq(1)", row).addClass("text-right").html("<div style='padding-right: 20px'>¥ " + data.totalPrice + "</div>");
                    } else {
                        $("td:eq(1)", row).addClass("text-right").html("<div style='padding-right: 20px'>$ " + data.totalPrice + "</div>");
                    }
                    $("td:eq(2)", row).addClass("text-center").html("<h4><span class='label label-success'>" + data.paymentType + "</span></h4>");
                    var html = $compile("<a href='#payment" + data.payment_info_id + "' ng-click='downloadReceipt($event, " + data.payment_info_id + ")'><span class='fa fa-download'></span></a>")($scope);
                    $("td:eq(3)", row).addClass("text-center").html(html);
                },
                // "stateSave": true,
                "columns": [
                    // {"data": "transmission_id"},
                    {"data": "createdDate"},
                    {"data": "totalPrice"},
                    {"data": "paymentType"},
                    {"data": "payment_info_id"}
                ],
                "columnDefs": [
                    {'orderable': false, 'targets': [2, 3]}
                ]
            };
            // offline payment history table opts
            var paymentHisOfflinePagingSettings = JSON.parse(localStorage.getItem(sortPage.PAYMENT_HISTORY));

            if (!paymentHisOfflinePagingSettings) {
                paymentHisOfflinePagingSettings = {
                    page_size: app.LIST_PAGE_SIZE,
                    page_number: 1,
                    display_start: 0,
                    sort_key: 0,
                    asc_sort: false
                }
            }

            $scope.paymentHisOfflineOpts = {

                "order": [
                    paymentHisOfflinePagingSettings.sort_key,
                    paymentHisOfflinePagingSettings.asc_sort ? "asc" : "desc"
                ],
                "searching": false,
                pageLength: paymentHisOfflinePagingSettings.page_size,
                displayStart: paymentHisOfflinePagingSettings.display_start,
                "ajax": function (data, callback) {

                    var objUrl = {
                        url: APIName.GET_PAYMENT_INFO.name + $stateParams.id + APIName.GET_PAYMENT_INFO.suffix,
                        method: APIName.GET_PAYMENT_INFO.method
                    };

                    var storeParams = {
                        payment_type: 1,
                        page_size: data.length,
                        display_start: 0,
                        sort_key: data.order[0].column,
                        page_number: data.start / data.length + 1,
                        sort_field: data.columns[data.order[0].column].data,
                        asc_sort: data.order[0].dir === "asc"
                    };

                    var params = {
                        payment_type: 1,
                        page_size: data.length,
                        page_number: data.start / data.length + 1,
                        sort_field: data.columns[data.order[0].column].data,
                        asc_sort: data.order[0].dir === "asc"
                    };
                    AppUtil.createRequest(objUrl, params, function (dataCallback) {
                        var json = {
                            "draw": data.draw,
                            "recordsTotal": dataCallback.data.total_elements,
                            "recordsFiltered": dataCallback.data.total_elements,
                            "data": []
                        };
                        localStorage.setItem(sortPage.PAYMENT_HISTORY, JSON.stringify(storeParams));

                        $.each(dataCallback.data.content, function (index, payment) {
                            var paymentInfo = {
                                createdDate: payment.create_date,
                                totalPrice: payment.total_price,
                                description: '',
                                user_price: payment.user_price,
                                storage_price: payment.storage_price,
                                currency: payment.storage_price.currency,
                                payment_info_id: payment.payment_info_id
                            };

                            json.data.push(paymentInfo);
                        });

                        // Insert value
                        callback(json);
                    });
                },
                "rowCallback": function (row, data) {
                    $("td:eq(0)", row).addClass("text-center").html("<div>" + util.formatDateBasedOnDiff(data.createdDate, "", session.getCurrentLanguage(), session.getUser().time_zone) + "</div>");

                    if (data.currency === 'VND') {
                        $("td:eq(1)", row).addClass("text-right").html("<div style='padding-right: 20px'>{{" +
                            data.totalPrice + " | currency : ''}}&nbsp;" + "<span ng-i18next='label.currency_unit.vnd'/></div>");
                    } else if (data.currency === 'YEN') {
                        $("td:eq(1)", row).addClass("text-right").html("<div style='padding-right: 20px'>" +
                            "<span ng-i18next='label.currency_unit.yen'/>&nbsp;{{" + data.totalPrice + " | currency : ''}}</div>");

                    } else {
                        $("td:eq(1)", row).addClass("text-right").html("<div style='padding-right: 20px'>" +
                            "<span ng-i18next='label.currency_unit.usd'/>&nbsp;{{" + data.totalPrice + " | currency : ''}}</div>");

                    }

                    var html = $compile("<a href='#payment" + data.payment_info_id + "' ng-click='downloadReceipt($event, " + data.payment_info_id + ")'><span class='fa fa-download'></span></a>")($scope);
                    $("td:eq(2)", row).addClass("text-center").html(html);
                },
                "drawCallback": function (t) {
                    // Using compile service
                    $compile(t.nTBody)($scope);
                },
                // "stateSave": true,
                "columns": [
                    {"data": "createdDate"},
                    {"data": "totalPrice"},
                    {"data": "payment_info_id"}
                ],
                "columnDefs": [
                    {'orderable': false, 'targets': [2]}
                ]
            };

            $scope.downloadReceipt = function (event, paymentInfoId) {
                event.preventDefault();
                Download.downloadReceipt(Auth.getToken(), paymentInfoId, $scope.company_id, $scope.team_id);
            };

            $scope.loadPaymentHistory = function() {
                if ($scope.paymentHistoryTable) {
                    $scope.paymentHistoryTable.draw();
                }
            };

            $scope.getPaymentHistoryData = function() {
                $scope.loading = true;
                $scope.errorMessage = '';
                var objUrl = {
                    url: APIName.GET_PAYMENT_HISTORY.name + $stateParams.id + APIName.GET_PAYMENT_HISTORY.suffix,
                    method: APIName.GET_PAYMENT_HISTORY.method
                };
                AppUtil.createRequest(objUrl, $scope.historyParams, function(response) {
                    if (response.status === 200 && response.data) {
                        $scope.historyData = response.data.content || [];
                        $scope.totalRecords = response.data.total_elements || 0;
                    } else {
                        $scope.historyData = [];
                        $scope.totalRecords = 0;
                    }
                    $scope.loading = false;
                }, function(error) {
                    console.error('Error loading payment history:', error);
                    $scope.historyData = [];
                    $scope.totalRecords = 0;
                    $scope.errorMessage = error.message || util.translate('errors.load_payment_history_failed');
                    $scope.loading = false;
                });
            };

            $scope.viewReceipt = function(data) {
                $scope.receiptData = {
                    teamName: $scope.teamData.name || '',
                    chargedDate: $scope.formatISODate(data.createdDate),
                    expiryDate: $scope.formatISODate($scope.teamPaymentInfo?.expiry_date),
                    planName: (data.pricingPackage && data.pricingPackage.name) ? data.pricingPackage.name.toUpperCase() : '-',
                    pricePerUser: (data.pricingPackage && data.pricingPackage.price) ? $scope.formatCurrency(data.pricingPackage.price, data.pricingPackage.currency) : '-',
                    currency: (data.pricingPackage && data.pricingPackage.currency) ? data.pricingPackage.currency : '-',
                    billingCycle: (data.pricingPackage && data.pricingPackage.billing_cycle) ? data.pricingPackage.billing_cycle.toUpperCase() : '-',
                    userCount: data.numberUser || 0,
                    totalPayment: (data.totalPayment !== undefined) ? $scope.formatCurrency(data.totalPayment, (data.pricingPackage && data.pricingPackage.currency) ? data.pricingPackage.currency : 'USD') : '-',
                    totalPrice: (data.totalPrice !== undefined) ? $scope.formatCurrency(data.totalPrice, (data.pricingPackage && data.pricingPackage.currency) ? data.pricingPackage.currency : 'USD') : '-',
                    creditApplied: (data.creditApplied !== undefined) ? $scope.formatCurrency(data.creditApplied, (data.pricingPackage && data.pricingPackage.currency) ? data.pricingPackage.currency : 'USD') : '-',
                    type: data.pricingPackage.type === 'SECURE_MAIL' ? 'SecureMail' : 'SecureDrive',
                    logoUrl: '/img/689Cloud_large.png'
                };
                $('#receiptModal').modal('show');
            };

            $scope.formatCurrency = function(amount, currency) {
                let num = parseFloat(amount);
                if (isNaN(num)) num = 0;
                const formattedAmount = num.toFixed(2);
                switch (currency) {
                    case 'YEN':
                        return util.translate('label.currency_unit.yen') + ' ' + formattedAmount;
                    case 'USD':
                    default:
                        return util.translate('label.currency_unit.usd') + ' ' + formattedAmount;
                }
            };

            $scope.formatISODate = function(dateString) {
                if (!dateString) return '';
                try {
                    const dateObj = new Date(dateString);
                    if (isNaN(dateObj.getTime())) return '';
                    const dayOfWeek = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][dateObj.getUTCDay()];
                    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                    const month = months[dateObj.getUTCMonth()];
                    const day = dateObj.getUTCDate();
                    const year = dateObj.getUTCFullYear();
                    const hours = dateObj.getUTCHours().toString().padStart(2, '0');
                    const minutes = dateObj.getUTCMinutes().toString().padStart(2, '0');
                    const seconds = dateObj.getUTCSeconds().toString().padStart(2, '0');
                    const time = `${hours}:${minutes}:${seconds}`;
                    return `${dayOfWeek} ${month} ${day} ${time} UTC ${year}`;
                } catch (error) {
                    console.error('Error formatting date:', error);
                    return '';
                }
            };

            $scope.getCurrencySymbol = function(currency) {
                switch (currency) {
                    case 'YEN':
                        return '¥';
                    case 'USD':
                    default:
                        return '$';
                }
            };
        }
    ]);
