'use strict';

angular.module('upgrade', []).controller('UpgradeAccountCtrl', [
  '$scope',
  'configServer',
  'Util',
  'session',
  '$uibModal',
  'exchangeRate',
  'currencyUnit',
  '$state',
  'AppConfig',
  'packageUpgrade',
  '$rootScope',
  'Patterns',
  'currencyInfo',
  'BILLING_CYCLE',
  'PACKAGE_NAME',
  'CONSOLE_TYPE',
  function (
    $scope,
    configServer,
    Util,
    session,
    $uibModal,
    exchangeRate,
    currencyUnit,
    $state,
    AppConfig,
    packageUpgrade,
    $rootScope,
    Patterns,
    currencyInfo,
    BILLING_CYCLE,
    PACKAGE_NAME,
    CONSOLE_TYPE
  ) {
    //get currency of team
    $scope.currentUser = session.getUser();
    $scope.packageFree = AppConfig.FREE_PACKAGE;
    $scope.script_pattern = Patterns.SCRIPT_PATTERN;
    $scope.userPriceIdFree = configServer.USER_PRICE_ID_FREE;
    $scope.storagePriceIdFree = configServer.STORAGE_PRICE_ID_FREE;
    $scope.userPriceIdFreeJa = configServer.USER_PRICE_ID_FREE_JA;
    $scope.storagePriceIdFreeJa = configServer.STORAGE_PRICE_ID_FREE_JA;

    $scope.packageType = '';
    $scope.billingCycle = '';
    $scope.currency = '';
    $scope.teamId = '';

    $scope.getTeamInfo = function () {
      Util.createRequest(
        configServer.API_URL + '/teams/' + $scope.currentUser.team_id,
        'GET',
        {},
        function (response) {
          var status = response.status;
          if (status === 200) {
            $scope.teamStatus = response.data.status;
            $scope.loadCompanyPlan(
              response.data.user_price_id,
              response.data.storage_price_id,
              response.data.currency
            );
          } else {
            Util.createToast({ className: 'danger', content: 'SERVER_ERROR.' + status });
          }
        },
        function (error) {
          if (error.status !== 401) {
            Util.createToast({ className: 'danger', content: 'SERVER_ERROR.' + error.status });
          } else {
            $cookies.remove(AppConfig.TOKEN_COOKIE_NAME);
            localStorage.removeItem(AppConfig.TOKEN_COOKIE_NAME);
          }
        }
      );
    };

    $scope.getTeamInfo();
    console.log('$scope.currentUser', $scope.currentUser);
    //get user price and storage price
    $scope.loadCompanyPlan = function (currentUserPriceId, currentStoragePriceId, currency) {
      Util.createRequest(
        configServer.API_URL + '/usage_package/packages',
        'GET',
        { currency: currency },
        function (response) {
          var status = response.status;
          if (status === 200) {
            $scope.items = response.data;
            $scope.results = {
              free: {},
              standard: {},
              pro: {},
            };

            $scope.resultPackage = [];

            var currentStoragePriceId = $scope.currentUser.package_object.storage_price_id;
            var currentUserPriceId = $scope.currentUser.package_object.user_price_id;

            var billingCycle =
              $scope.currentUser.team_settings.billing_cycle &&
              $scope.currentUser.team_settings.billing_cycle;
            var storagePrices =
              $scope.items.storage_prices && $scope.items.storage_prices.length > 0
                ? $scope.items.storage_prices
                : [];
            var userPrices =
              $scope.items.user_prices && $scope.items.user_prices.length > 0
                ? $scope.items.user_prices
                : [];

            var storagePricesList = [];
            var userPricesList = [];
            var targetPackages = ['Personal', 'Team', 'Business'];

            // First determine if billing cycle is monthly or yearly
            var isBillingCycleMonthly = billingCycle === 30;
            // For each target package name, find the matching package by name and billing cycle
            targetPackages.forEach(function (packageName) {
              var matchingPackage = storagePrices.find(function (item) {
                if (item.name && item.name !== packageName) return false;
                if (item.console_type && item.console_type !== CONSOLE_TYPE.SECURE_MAIL) {
                  return false;
                }

                var descriptionLower = item.description.toLowerCase();
                var isMonthly = descriptionLower.includes('month');
                var isYearly = descriptionLower.includes('year');

                return (isBillingCycleMonthly && isMonthly) || (!isBillingCycleMonthly && isYearly);
              });

              // If a matching package is found, add it to our list
              if (matchingPackage) {
                storagePricesList.push(matchingPackage);
              }
            });
            targetPackages.forEach(function (packageName) {
              var matchingPackage = userPrices.find(function (item) {
                if (item.name && item.name !== packageName) return false;
                if (item.console_type && item.console_type !== CONSOLE_TYPE.SECURE_MAIL) {
                  return false;
                }
                var descriptionLower = item.description.toLowerCase();
                var isMonthly = descriptionLower.includes('month');
                var isYearly = descriptionLower.includes('year');

                return (isBillingCycleMonthly && isMonthly) || (!isBillingCycleMonthly && isYearly);
              });
              // If a matching package is found, add it to our list
              if (matchingPackage) {
                userPricesList.push(matchingPackage);
              }
            });

            // Create the combined array
            var combinedPackages = [];
            // For each target package, find matching user and storage prices
            targetPackages.forEach(function (packageName) {
              var matchingStoragePrice = storagePricesList.find(function (item) {
                return item.name === packageName;
              });

              var matchingUserPrice = userPricesList.find(function (item) {
                return item.name === packageName;
              });
              // Only add to combined list if both user and storage prices are found
              if (matchingStoragePrice && matchingUserPrice) {
                // console.log('matchingStoragePrice', matchingStoragePrice);
                // console.log('matchingUserPrice', matchingUserPrice);

                var packageItem = {
                  name: packageName,
                  console_type: matchingUserPrice.console_type || '',
                  storage_price: matchingStoragePrice,
                  user_price: matchingUserPrice,
                  totalPrice: (matchingStoragePrice.price || 0) + (matchingUserPrice.price || 0),
                  currency: matchingUserPrice.currency || matchingStoragePrice.currency,
                  billing_cycle: isBillingCycleMonthly
                    ? BILLING_CYCLE.MONTHLY
                    : BILLING_CYCLE.ANNUALLY,
                };

                if (packageItem.currency === 'VND') {
                  packageItem.currencyInfo = currencyUnit.VND;
                } else if (packageItem.currency === 'YEN') {
                  packageItem.currencyInfo = currencyUnit.YEN;
                } else {
                  packageItem.currencyInfo = currencyUnit.USD;
                }
                combinedPackages.push(packageItem);
              }
            });

            $scope.resultPackage = combinedPackages;
            // $scope.items.storage_prices.forEach(function (item) {
            //     if (currency === currencyInfo.YEN) {
            //         if (item.storage_price_id === configServer.STORAGE_PRICE_ID_FREE_JA) {
            //             $scope.results.free.storage_price = item;
            //         }
            //         if (item.storage_price_id === configServer.STORAGE_PRICE_ID_PRO_JA) {
            //             $scope.results.pro.storage_price = item;
            //         }
            //     } else {
            //         if (item.storage_price_id === configServer.STORAGE_PRICE_ID_FREE) {
            //             $scope.results.free.storage_price = item;
            //         }
            //         if (item.storage_price_id === configServer.STORAGE_PRICE_ID_PRO) {
            //             $scope.results.pro.storage_price = item;
            //         }
            //     }
            // });

            // $scope.items.user_prices.forEach(function (item) {
            //     if (currency === currencyInfo.YEN) {
            //         if (item.user_price_id === configServer.USER_PRICE_ID_FREE_JA) {
            //             $scope.results.free.user_price = item;
            //         }
            //         if (item.user_price_id === configServer.USER_PRICE_ID_PRO_JA) {
            //             $scope.results.pro.user_price = item;
            //         }
            //     } else {
            //         if (item.user_price_id === configServer.USER_PRICE_ID_FREE) {
            //             $scope.results.free.user_price = item;
            //         }
            //         if (item.user_price_id === configServer.USER_PRICE_ID_PRO) {
            //             $scope.results.pro.user_price = item;
            //         }
            //     }
            // });

            // $scope.listPackage = [];
            // for (var property in $scope.results) {
            //     var object = $scope.results[property];
            //     if (object && object.storage_price && object.user_price) {
            //         // add list
            //         $scope.listPackage.push(object);
            //     }
            // }

            // $scope.resultPackage = [];
            // $scope.listPackage.forEach(function (item) {
            //     var packageInfo = {
            //         totalPrice: 0,
            //         user_price_id: item.user_price.user_price_id,
            //         storage_price_id: item.storage_price.storage_price_id,
            //         currency: item.user_price.currency,
            //         type: "",
            //         description: "",
            //         storage: 0,
            //         user: item.user_price.max_user,
            //         active: item.user_price.user_price_id === currentUserPriceId &&
            //         item.storage_price.storage_price_id === currentStoragePriceId ? 1 : 0
            //     };
            //
            //     packageInfo.type = item.user_price.name.split("-")[1].toUpperCase();
            //     packageInfo.description = Util.replaceTranslate('PACKAGE_DESCRIPTION.' + item.user_price.name.split("-")[1].toUpperCase());
            //     if (item.user_price) {
            //         packageInfo.totalPrice += item.user_price.price || 0;
            //     }
            //     if (item.storage_price) {
            //         packageInfo.totalPrice += item.storage_price.price || 0;
            //     }
            //     if (item.user_price.currency === 'VND') {
            //         packageInfo.currencyInfo = currencyUnit.VND;
            //     } else if (item.user_price.currency === 'YEN') {
            //         packageInfo.currencyInfo = currencyUnit.YEN;
            //     } else {
            //         packageInfo.currencyInfo = currencyUnit.USD;
            //     }
            //
            //     const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
            //
            //     if (item.storage_price.max_storage <= 0) {
            //         packageInfo.storage = 0 + ' ' + 'Bytes';
            //     } else {
            //         const i = Math.floor(Math.log(item.storage_price.max_storage) / Math.log(1024));
            //         packageInfo.storage = (item.storage_price.max_storage / Math.pow(1024, i)) + sizes[i];
            //     }
            //
            //     if (packageInfo.active === 1) {
            //         $scope.currentPackage = packageInfo.type;
            //     }
            //     console.log("packageInfo", packageInfo)
            //
            //     $scope.resultPackage.push(packageInfo);
            // });

            console.log('$scope.resultPackage', $scope.resultPackage);

            //get user and storage for description
            $scope.getUserAndStorage($scope.resultPackage);
          } else {
            Util.createToast({ className: 'danger', content: 'SERVER_ERROR.' + status });
          }
        },
        function (error) {
          Util.createToast({
            className: 'danger',
            content: 'SERVER_ERROR.' + error.status,
          });
        }
      );
    };

    $scope.$on('get_team_info', getInfo);

    function getInfo(event, value) {
      $scope.getTeamInfo();
      $state.go($state.current, {}, { reload: true });
    }

    $scope.isShowLoading = false;
    $scope.$on('is_loading_spinner', isLoadingSpinner);

    function isLoadingSpinner(event, value) {
      $scope.isShowLoading = true;
    }

    $scope.$on('not_loading_spinner', notLoadingSpinner);

    function notLoadingSpinner(event, value) {
      $scope.isShowLoading = false;
    }

    $scope.openModalUpgrade = function (packageName, billingCycle, currency, teamId) {
      $scope.packageType = packageName;
      $scope.billingCycle = billingCycle;
      $scope.currency = currency;
      $scope.teamId = teamId;

      return $uibModal.open({
        backdrop: 'static',
        templateUrl: 'components/modal-template/upgrade_account_modal.html',
        controller: [
          '$scope',
          '$uibModalInstance',
          '$translate',
          '$rootScope',
          'session',
          '$state',
          'Util',
          'configServer',
          function (
            $scope,
            $uibModalInstance,
            $translate,
            $rootScope,
            session,
            $state,
            Util,
            configServer
          ) {
            $translate(['COMMON.BUTTON_CANCEL', 'COMMON.BUTTON_OK']).then(function (translations) {
              // $scope.userPriceIdFree = configServer.USER_PRICE_ID_FREE;
              // $scope.storagePriceIdFree = configServer.STORAGE_PRICE_ID_FREE;
              // $scope.userPriceIdFreeJa = configServer.USER_PRICE_ID_FREE_JA;
              // $scope.storagePriceIdFreeJa = configServer.STORAGE_PRICE_ID_FREE_JA;
              // $scope.upgradeToFree = false;
              // if (userPriceId === $scope.userPriceIdFree && storagePriceId === $scope.storagePriceIdFree ||
              //     userPriceId === $scope.userPriceIdFreeJa && storagePriceId === $scope.storagePriceIdFreeJa) {
              //     $scope.upgradeToFree = true;
              // }
              // $scope.newPackage = newPackage;
              // $scope.oldPackage = currentPackage;
              // $scope.currentLang = session.getUser().lang;

              $scope.upgradeToFree = false;

              $scope.newPackage = packageName;
              $scope.oldPackage = $rootScope.currentUser.package_object.package_name;

              if ($scope.oldPackage.toUpperCase() === PACKAGE_NAME.FREE) {
                $scope.upgradeToFree = true;
              }

              var currentUserPriceId = $rootScope.currentUser.package_object.user_price_id;
              var currentStoragePriceId = $rootScope.currentUser.package_object.storage_price_id;

              $scope.opts = {
                lblAccept: translations['COMMON.BUTTON_OK'],
                lblDismiss: translations['COMMON.BUTTON_CANCEL'],
              };

              $scope.onClose = function () {
                $uibModalInstance.close();
              };

              $scope.onAccept = function () {
                if ($scope.isSubmittingCharge) {
                  return;
                }
                $scope.isSubmittingCharge = true;

                $rootScope.$broadcast('is_loading_spinner');
                var params = {
                  // user_price_id: userPriceId,
                  // storage_price_id: storagePriceId,
                  team_id: teamId,
                  package_type: packageName.toUpperCase(),
                  billing_cycle: billingCycle.toUpperCase(),
                  currency: currency.toUpperCase(),
                  console_type: 'SECURE_MAIL',
                };
                Util.createRequest(
                  configServer.API_URL + '/payments/usage_plan/team/' + session.getUser().team_id,
                  'PUT',
                  params,
                  function (response) {
                    if (response.status === 200) {
                      if (response.data) {
                        session.setAccessToken(
                          response.data.session_id,
                          response.data.expiration_date
                        );
                      }
                      if ($scope.upgradeToFree === true) {
                        Util.createToast({
                          className: 'success',
                          content: 'COMMON.MESSAGE.UPDATE_SUCCESS',
                        });
                      } else {
                        Util.createToast({
                          className: 'success',
                          content: 'COMMON.MESSAGE.CHARGE_MGS',
                        });
                      }
                      $rootScope.$broadcast('not_loading_spinner');
                      $rootScope.$broadcast('get_team_info');
                      $rootScope.$broadcast('load_trial');
                    } else {
                      if (response.status === 2713) {
                        var errCode = response.data.split(' - ');

                        var errorText = Util.replaceTranslateStripError(
                          'STRIPE_ERROR.' + errCode[0],
                          'CARD_INFO.ERROR_CODE.UPGRADE_ACCOUNT_FAIL'
                        );

                        Util.createToast({
                          className: 'danger',
                          content: errorText,
                        });
                        $rootScope.$broadcast('get_team_info');
                      } else if (response.status === 2704) {
                        Util.createToast({
                          className: 'warning',
                          content: 'SERVER_ERROR.' + response.status,
                        });
                        window.scrollTo(0, 0);
                        $rootScope.$broadcast('add_id_package', {
                          add_card: true,
                          charge: false,
                          user_price_id: currentUserPriceId,
                          storage_price_id: currentStoragePriceId,
                        });
                      } else {
                        Util.createToast({
                          className: 'danger',
                          content: 'SERVER_ERROR.' + response.status,
                        });
                        $rootScope.$broadcast('get_team_info');
                      }
                      $rootScope.$broadcast('not_loading_spinner');
                    }
                    $scope.isSubmittingCharge = false;
                  },
                  function (error) {
                    Util.createToast({
                      className: 'danger',
                      content: 'SERVER_ERROR.' + error.status,
                    });
                    $scope.isSubmittingCharge = false;
                  }
                );
                $uibModalInstance.close();
              };
            });
          },
        ],
      });
    };

    $scope.chargeAmount = function () {
      return $uibModal.open({
        backdrop: 'static',
        templateUrl: 'components/modal-template/confirm_delete_modal.html',
        controller: [
          '$scope',
          '$uibModalInstance',
          '$translate',
          '$rootScope',
          'session',
          '$state',
          function ($scope, $uibModalInstance, $translate, $rootScope, session, $state) {
            $translate([
              'COMMON.BUTTON_CANCEL',
              'COMMON.BUTTON_OK',
              'TEAM_PAYMENT.CHARGE',
              'TEAM_PAYMENT.CHARGE_AMOUNT_MGS',
            ]).then(function (translations) {
              $scope.opts = {
                title: translations['TEAM_PAYMENT.CHARGE'],
                message: translations['TEAM_PAYMENT.CHARGE_AMOUNT_MGS'],
                lblAccept: translations['COMMON.BUTTON_OK'],
                lblDismiss: translations['COMMON.BUTTON_CANCEL'],
              };

              $scope.onClose = function () {
                $uibModalInstance.close();
              };

              $scope.onAccept = function () {
                if ($scope.isSubmittingCharge) {
                  return;
                }
                $scope.isSubmittingCharge = true;
                $rootScope.$broadcast('is_loading_spinner');
                Util.createRequest(
                  configServer.API_URL + '/payments/team/' + session.getUser().team_id + '/charge',
                  'POST',
                  {},
                  function (response) {
                    if (response.status === 200) {
                      Util.createToast({
                        className: 'success',
                        content: 'COMMON.MESSAGE.CHARGE_MGS',
                      });
                      $rootScope.$broadcast('not_loading_spinner');
                      $rootScope.$broadcast('get_team_info');
                      $rootScope.$broadcast('load_trial');
                    } else {
                      if (response.status === 2713) {
                        var errCode = response.data.split(' - ');

                        var errorText = Util.replaceTranslateStripError(
                          'STRIPE_ERROR.' + errCode[0],
                          'CARD_INFO.ERROR_CODE.UPGRADE_ACCOUNT_FAIL'
                        );

                        Util.createToast({
                          className: 'danger',
                          content: errorText,
                        });
                        $rootScope.$broadcast('get_team_info');
                      } else if (response.status === 2704) {
                        Util.createToast({
                          className: 'warning',
                          content: 'SERVER_ERROR.' + response.status,
                        });
                        window.scrollTo(0, 0);
                        $rootScope.$broadcast('add_id_package', {
                          add_card: true,
                          charge: true,
                        });
                      } else {
                        Util.createToast({
                          className: 'danger',
                          content: 'SERVER_ERROR.' + response.status,
                        });
                        $rootScope.$broadcast('get_team_info');
                      }
                      $rootScope.$broadcast('not_loading_spinner');
                    }
                    $scope.isSubmittingCharge = false;
                  },
                  function (error) {
                    Util.createToast({
                      className: 'danger',
                      content: 'SERVER_ERROR.' + error.status,
                    });
                    $scope.isSubmittingCharge = false;
                  }
                );
                $uibModalInstance.close();
              };
            });
          },
        ],
      });
    };

    $scope.getUserAndStorage = function (items) {
      items.forEach(function (item) {
        switch (item.name) {
          case 'Personal':
            item.storage = '5GB';
            item.max_file_size = '1GB';
            item.number = '100';
            break;
          case 'Team':
            item.storage = '25GB';
            item.max_file_size = '2GB';
            item.number = '500';
            break;
          case 'Business':
            item.storage = '100GB';
            item.max_file_size = '5GB';
            item.number = '2000';
            break;
          default:
            break;
        }
        // if ((item.user_price_id === configServer.USER_PRICE_ID_PRO && item.storage_price_id === configServer.STORAGE_PRICE_ID_PRO) ||
        //     (item.user_price_id === configServer.USER_PRICE_ID_PRO_JA && item.storage_price_id === configServer.STORAGE_PRICE_ID_PRO_JA)) {
        //     item.transmission = packageUpgrade.TRANSMISSION_PRO;
        //     item.upto = packageUpgrade.UP_TO_PRO;
        //     item.protect_tile = 'TEAM_PAYMENT.UPGRADE.DESCRIPTION_PRO_1';
        //     item.revoke_title = 'TEAM_PAYMENT.UPGRADE.DESCRIPTION_PRO_2';
        //     item.protect_subject_1 = 'TEAM_PAYMENT.UPGRADE.SUBJECT.DESCRIPTION_1';
        //     item.protect_subject_2 = 'TEAM_PAYMENT.UPGRADE.SUBJECT.DESCRIPTION_2';
        //
        // } else if ((item.user_price_id === configServer.USER_PRICE_ID_FREE && item.storage_price_id === configServer.STORAGE_PRICE_ID_FREE) ||
        //     (item.user_price_id === configServer.USER_PRICE_ID_FREE_JA && item.storage_price_id === configServer.STORAGE_PRICE_ID_FREE_JA)) {
        //     item.transmission = packageUpgrade.TRANSMISSION_FREE;
        //     item.upto = packageUpgrade.UP_TO_FREE;
        // }
      });
    };
    // $scope.getUserAndStorage = function (items) {
    //     items.forEach(function (item) {
    //         if ((item.user_price_id === configServer.USER_PRICE_ID_PRO && item.storage_price_id === configServer.STORAGE_PRICE_ID_PRO) ||
    //             (item.user_price_id === configServer.USER_PRICE_ID_PRO_JA && item.storage_price_id === configServer.STORAGE_PRICE_ID_PRO_JA)) {
    //             item.transmission = packageUpgrade.TRANSMISSION_PRO;
    //             item.upto = packageUpgrade.UP_TO_PRO;
    //             item.protect_tile = 'TEAM_PAYMENT.UPGRADE.DESCRIPTION_PRO_1';
    //             item.revoke_title = 'TEAM_PAYMENT.UPGRADE.DESCRIPTION_PRO_2';
    //             item.protect_subject_1 = 'TEAM_PAYMENT.UPGRADE.SUBJECT.DESCRIPTION_1';
    //             item.protect_subject_2 = 'TEAM_PAYMENT.UPGRADE.SUBJECT.DESCRIPTION_2';
    //
    //         } else if ((item.user_price_id === configServer.USER_PRICE_ID_FREE && item.storage_price_id === configServer.STORAGE_PRICE_ID_FREE) ||
    //             (item.user_price_id === configServer.USER_PRICE_ID_FREE_JA && item.storage_price_id === configServer.STORAGE_PRICE_ID_FREE_JA)) {
    //             item.transmission = packageUpgrade.TRANSMISSION_FREE;
    //             item.upto = packageUpgrade.UP_TO_FREE;
    //         }
    //     });
    // };

    // create style input card
    $scope.currentLang = session.getUser().lang;
    $scope.cardInfo = {
      cardholderName: '',
      cardNumber: '',
      cvc: '',
      address1: '',
    };
    // Create a Stripe client.
    var stripe = Stripe(configServer.PUBLIC_KEY_STRIPE);

    // Create an instance of Elements.
    var elements = stripe.elements();

    // Custom styling can be passed to options when creating an Element.
    // (Note that this demo uses a wider set of styles than the guide below.)
    var style = {
      base: {
        color: '#32325d',
        fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
        fontSmoothing: 'antialiased',
        fontSize: '16px',
        '::placeholder': {
          color: '#aab7c4',
        },
      },
      invalid: {
        color: '#fa755a',
        iconColor: '#fa755a',
      },
    };

    // Create an instance of the card Element.
    var card = elements.create('card', { style: style, hidePostalCode: true });

    // Add an instance of the card Element into the `card-element` <div>.
    card.mount('#card-element');

    // Handle real-time validation errors from the card Element.
    card.on('change', function (event) {
      $rootScope.$broadcast('handleInputStripe', event);
      var displayError = document.getElementById('card-errors');
      if (event.error) {
        displayError.textContent = Util.replaceTranslateStripError(
          'CARD_INFO.ERROR_CODE.' + event.error.code.toUpperCase()
        );
      } else {
        displayError.textContent = '';
      }
    });

    $scope.$on('handleInputStripe', checkInput);
    $scope.isComplete = false;

    function checkInput(event, item) {
      $scope.isComplete = item.complete;
      $scope.$apply();
    }

    $scope.$on('handleErrorCreateToken', checkError);

    function checkError(event, item) {
      if (item.error.code !== undefined && item.error.code !== null) {
        $scope.submitting = false;
        $scope.$apply();
      }
    }

    // Handle form submission.
    $scope.submitting = false;
    var form = document.getElementById('payment-card');
    form.addEventListener('click', function (event) {
      $scope.submitting = true;
      event.preventDefault();
      var data = {
        name: $scope.cardInfo.cardholderName,
        address_line1: $scope.cardInfo.address1,
      };
      stripe.createToken(card, data).then(function (result) {
        if (result.error) {
          // Inform the user if there was an error.
          var errorElement = document.getElementById('card-errors');
          errorElement.textContent = Util.replaceTranslateStripError(
            'CARD_INFO.ERROR_CODE.' + result.error.code.toUpperCase()
          );
          $rootScope.$broadcast('handleErrorCreateToken', result);
        } else {
          // Send the token to your server.
          $scope.createCard(result.token.id);
        }
      });
    });

    //add id package
    $scope.$on('add_id_package', addIdPackage);

    function addIdPackage(event, value) {
      console.log('value', value);

      $scope.userPriceId = value.user_price_id;
      $scope.storagePriceId = value.storage_price_id;
      $scope.isAddCard = value.add_card;
      $scope.isCharge = value.charge;
      $scope.isShowAddCard = $scope.isAddCard === true ? true : false;
    }

    // show loading spinner
    $scope.createCard = function (tokenId) {
      $scope.isShowLoading = true;
      var param = {
        card_token: tokenId,
      };

      Util.createRequest(
        configServer.API_URL + '/teams/' + session.getUser().team_id,
        'GET',
        {},
        function (response) {
          if (response && response.status === 200) {
            param.storage_price_id = response.data.storage_price_id;
            param.user_price_id = response.data.user_price_id;
            Util.createRequest(
              configServer.API_URL + '/payments/team/' + session.getUser().team_id + '/new_card',
              'POST',
              param,
              function (response) {
                if (response && response.status === 200) {
                  Util.createToast({
                    className: 'success',
                    content: 'COMMON.MESSAGE.ADD_SUCCESS_MESSAGE',
                  });
                  $scope.cancelAddCard();
                  if ($scope.isAddCard && !$scope.isCharge) {
                    // upgrade account
                    console.log('upgrade account');
                    $scope.paymentUpgrade();
                  } else if ($scope.isAddCard && $scope.isCharge) {
                    // charge
                    console.log('charge');
                    $scope.paymentCharge();
                  }
                } else {
                  if (response.status === 2713) {
                    var errCode = response.data.split(' - ');

                    var errorText = Util.replaceTranslateStripError(
                      'STRIPE_ERROR.' + errCode[0],
                      'CARD_INFO.ERROR_CODE.CARD_DECLINED'
                    );

                    Util.createToast({
                      className: 'danger',
                      content: errorText,
                    });
                  } else {
                    Util.createToast({
                      className: 'danger',
                      content: 'SERVER_ERROR.' + response.status,
                    });
                  }
                  $scope.isShowLoading = false;
                  $scope.submitting = false;
                }
              },
              function (error) {
                $scope.submitting = false;
                $scope.isShowLoading = false;
                Util.createToast({
                  className: 'danger',
                  content: 'SERVER_ERROR.' + error.status,
                });
              }
            );
          } else {
            $scope.submitting = false;
            $scope.isShowLoading = false;
            Util.createToast({
              className: 'danger',
              content: 'SERVER_ERROR.' + response.status,
            });
          }
        },
        function (error) {
          $scope.submitting = false;
          $scope.isShowLoading = false;
          Util.createToast({
            className: 'danger',
            content: 'SERVER_ERROR.' + error.status,
          });
        }
      );
    };

    $scope.paymentUpgrade = function () {
      // var params = {
      //     user_price_id: $scope.userPriceId,
      //     storage_price_id: $scope.storagePriceId
      // };

      var params = {
        team_id: $scope.teamId || session.getUser().team_id,
        package_type: $scope.packageType.toUpperCase(),
        billing_cycle: $scope.billingCycle.toUpperCase(),
        currency: $scope.currency.toUpperCase(),
        console_type: CONSOLE_TYPE.SECURE_MAIL,
      };

      Util.createRequest(
        configServer.API_URL + '/payments/usage_plan/team/' + session.getUser().team_id,
        'PUT',
        params,
        function (response) {
          if (response.status === 200) {
            if (response.data) {
              session.setAccessToken(response.data.session_id, response.data.expiration_date);
            }
            Util.createToast({
              className: 'success',
              content: 'COMMON.MESSAGE.CHARGE_MGS',
              timeout: 5000, // 5s
            });
            $rootScope.$broadcast('load_trial');
          } else if (response.status === 2713) {
            var errCode = response.data.split(' - ');
            var errorText = Util.replaceTranslateStripError(
              'STRIPE_ERROR.' + errCode[0],
              'CARD_INFO.ERROR_CODE.UPGRADE_ACCOUNT_FAIL'
            );
            Util.createToast({
              className: 'danger',
              content: errorText,
            });
          } else {
            Util.createToast({
              className: 'danger',
              content: 'SERVER_ERROR.' + response.status,
            });
          }
          $scope.isShowLoading = false;
          $state.go($state.current, {}, { reload: true });
        },
        function (error) {
          $scope.isShowLoading = false;
          Util.createToast({
            className: 'danger',
            content: 'SERVER_ERROR.' + error.status,
          });
        }
      );
    };

    $scope.paymentCharge = function () {
      Util.createRequest(
        configServer.API_URL + '/payments/team/' + session.getUser().team_id + '/charge',
        'POST',
        {},
        function (response) {
          if (response.status === 200) {
            Util.createToast({
              className: 'success',
              content: 'COMMON.MESSAGE.CHARGE_MGS',
            });
            $rootScope.$broadcast('load_trial');
          } else if (response.status === 2713) {
            var errCode = response.data.split(' - ');
            var errorText = Util.replaceTranslateStripError(
              'STRIPE_ERROR.' + errCode[0],
              'CARD_INFO.ERROR_CODE.UPGRADE_ACCOUNT_FAIL'
            );
            Util.createToast({
              className: 'danger',
              content: errorText,
            });
          } else {
            Util.createToast({
              className: 'danger',
              content: 'SERVER_ERROR.' + response.status,
            });
          }
          $scope.isShowLoading = false;
          $state.go($state.current, {}, { reload: true });
        },
        function (error) {
          $scope.isShowLoading = false;
          Util.createToast({
            className: 'danger',
            content: 'SERVER_ERROR.' + error.status,
          });
        }
      );
    };
    $scope.cancelAddCard = function () {
      card.clear();
      $scope.isShowAddCard = false;
    };
  },
]);
