import { Component, OnInit, ViewChild } from '@angular/core';
import { StripePaymentService } from '../services/stripe/stripe-payment.service';
import {
  StripeCardElementOptions,
  StripeElementsOptions,
} from '@stripe/stripe-js';
import { ServicesService } from '../services.service';
import { StripeCardComponent, StripeService } from 'ngx-stripe';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthserviceService } from '../authservice.service';
import { NgxSpinnerService } from 'ngx-spinner';
import {
  FormArray,
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';
import { LoginflowService } from '../data/loginflow.service';
import { environment } from 'src/environments/environment';
@Component({
  selector: 'app-membership',
  templateUrl: './membership.component.html',
  styleUrls: ['./membership.component.scss']
})
export class MembershipComponent implements OnInit {
  @ViewChild(StripeCardComponent) card: StripeCardComponent;

  CardHolderName: any;
  Email: any;
  Address: any;
  Country: any;
  City: any;
  State: any;
  Zip: any;
  SelectedPlan = [];
  Amount = 25 * 100;
  ButtonText = "Pay $0 / Months";
  Materials = [];
  Subscriptions = [];
  SubscriptionPlan = [];
  CohortName: any;
  UserId: any;
  PaymentSuccess: boolean = false;
  UserSelection: boolean = false;
  WelcomeLink = "";
  SubscriptionPriceID = "";
  SubscriptionId: any;
  plan_description: any;
  access_duration: any;
  listUserStirpeId: any;
  RetirveCustmer: any;
  CustmerCardDetails: any;
  public PayForm: FormGroup;
  email: any;
  password: any;
  public LoginForm: FormGroup;
  msgBoxShow: Boolean = false;
  ChangePasswordPlaceHolder: string = "Create Password"
  cardOptions: StripeCardElementOptions = {
    style: {
      base: {
        iconColor: '#b89cc7',
        color: '#b89cc7',
        '::placeholder': {
          color: '#b89cc7'
        }
      }
    },
    hidePostalCode: true,
  };
  elementsOptions: StripeElementsOptions = {
    locale: 'en'
  };
  isCreatePassword: boolean = false;
  isEnterPassword: boolean = false;
  CreatePassword: any;
  EnterPassword: any;
  isPasswordError: boolean = false;
  constructor(private stripePaymentService: StripePaymentService,
    private service: ServicesService, private auth: AuthserviceService,
    private stripeService: StripeService, public ActiveRoute: ActivatedRoute,
    private router: Router, private spinner: NgxSpinnerService, public LoginflowService: LoginflowService,
    private fb: FormBuilder) {
    this.ActiveRoute.params.subscribe(async (params) => {
      try {
        let data = JSON.parse(atob(decodeURIComponent(params['data'])));
        this.CohortName = data.CohortName;
        this.SubscriptionId = data.SubscriptionId;
        await this.getMembershipDetails(data.SubscriptionId, data.SelectedPlan);
      } catch (error) {
      }
    });
  }

  async ngOnInit() {
    this.PayForm = this.fb.group({
      CardHolderName: ['', Validators.required],
      Email: ['', [Validators.required, Validators.email, Validators.pattern('^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*((\\.[A-Za-z]{2,4})$)')]],
      CreatePassword: new FormControl(),
      EnterPassword: new FormControl(),
      Address: new FormControl(),
      Country: new FormControl(),
      City: new FormControl(),
      State: new FormControl(),
      Zip: new FormControl(),
    });

    this.LoginForm = this.fb.group({
      email: [
        '',
        Validators.compose([
          Validators.required,
          Validators.pattern(
            '^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*((\\.[A-Za-z]{2,4})$)'
          ),
        ]),
      ],
      password: ['', Validators.required],
    });
    this.msgBoxShow = false;
  }
  markFormTouched(group: FormGroup | FormArray) {
    Object.keys(group.controls).forEach((key: string) => {
      const control = group.controls[key];
      if (control instanceof FormGroup || control instanceof FormArray) { control.markAsTouched(); this.markFormTouched(control); }
      else { control.markAsTouched(); };
    });
  };
  async checkEmailExist() {
    this.spinner.show()
    await this.LoginflowService.versions_getUserByEmail(this.Email).then(async (data) => {
      this.spinner.hide();
      var list = JSON.parse(<string>data[0].json);

      if (list.data.length <= 0) {
        this.isCreatePassword = true;
        this.isEnterPassword = false;
        this.ChangePasswordPlaceHolder = "Create Password";
        this.PayForm.get('EnterPassword').setErrors(null);
        this.PayForm.get('CreatePassword').setValidators(Validators.required);

      } else {
        this.isCreatePassword = false;
        this.isEnterPassword = true;
        this.ChangePasswordPlaceHolder = "Enter Your Password";
        this.PayForm.get('CreatePassword').setErrors(null);
        this.PayForm.get('EnterPassword').setValidators(Validators.required)
      }
    })

  }
  async PasswordCheck() {
    this.spinner.show()

    await this.auth.FlashCardUserLogin(this.Email, this.EnterPassword).then(
      async (data) => {
        if (data[0].StatusCode == 1) {
          await this.LoginflowService.versions_getUserByEmail(
            this.Email
          ).then(async (StirpeId) => {
            if (StirpeId[0].status == 200) {
              this.isPasswordError = false;
              this.spinner.hide();
            }
          });
        } else {
          if (data[0].message == 'User is not confirmed.') {
            await this.spinner.hide();
          } else if (data[0].message == 'User does not exist.') {
            await this.spinner.hide();
          } else {
            this.isPasswordError = true;
            await this.spinner.hide();
          }
        }
      },
      (err) => {
        this.spinner.hide();

        this.service.ShowError('Encountered server error!');
      }
    );
  }
  async getMembershipDetails(SubscriptionId, SelectedPlan) {
    this.spinner.show();
    await this.service.getMemberhipDetail(SubscriptionId).then((data) => {
      if (data[0].status == 200) {
        var list = JSON.parse(<string>data[0].json);
        this.Materials = list.data.Materials;
        this.Subscriptions = list.data.Subscription;
        if (this.Subscriptions.length > 0) {
          this.SubscriptionPlan = this.Subscriptions[0].subscriptions ? JSON.parse(this.Subscriptions[0].subscriptions) : [];
          if (SelectedPlan == "UserSelection") {
            this.UserSelection = true;
          } else {
            this.SubscriptionPlan.forEach(element => {
              if (element.price == SelectedPlan) {
                this.SelectedPlan = element;
                element['active'] = true;
                this.Amount = element.price * 100;
                this.ButtonText = "Pay $" + element.price + " " + element.description;
                this.plan_description = this.SelectedPlan['description'];
                this.access_duration = this.SelectedPlan['access_duration'];
                this.SubscriptionPriceID = element.price_id
              }
            });
          }

        }
        this.spinner.hide();
      }
    })
  }
  selectPlan(plan) {
    this.SelectedPlan = plan;
    this.SubscriptionPlan.forEach(element => {
      element['active'] = false;
      if (element.price == plan.price) {
        element['active'] = true;
        this.Amount = element.price * 100;
        this.ButtonText = "Pay $" + element.price + " " + element.description;
        this.plan_description = element.description;
        this.access_duration = element.access_duration;
        this.SubscriptionPriceID = element.price_id
      }
    });
  }
  async buy() {
    if (this.SelectedPlan.length <= 0) {
      this.service.ShowError("Please choose plan")
    } else {
      this.markFormTouched(this.PayForm);
      if (this.PayForm.valid) {
        this.spinner.show();
        await this.LoginflowService.versions_getUserByEmail(
          this.Email
        ).then(async (StirpeId) => {
          if (StirpeId[0].status == 200) {
            this.listUserStirpeId = JSON.parse(<string>StirpeId[0].json);

            if (this.listUserStirpeId.data.length > 0) {
              await this.stripePaymentService.RetirveCustmer(this.listUserStirpeId.data[0].stripe_customer_id).then(async (resRetirveCustmer) => {
                this.RetirveCustmer = JSON.parse(<string>resRetirveCustmer[0].json);

                this.UserId = this.listUserStirpeId.data[0].id;
                const monthNames = ["January", "February", "March", "April", "May", "June",
                  "July", "August", "September", "October", "November", "December"
                ];
                let usr = {
                  "user_id": this.listUserStirpeId.data[0].id,
                  "cohort": this.Subscriptions[0].cohort_id,
                  "date": monthNames[new Date().getMonth()] + " " + this.getOrdinal(new Date().getDate())
                }
                let user_id = btoa(JSON.stringify(usr));
                user_id = encodeURIComponent(user_id);
                let my_link = "/";
                this.WelcomeLink = environment.SITE_URL;
                let name = this.CardHolderName
                let stripeCustomerid = this.listUserStirpeId.data[0].stripe_customer_id;
                await this.stripeService.createToken(this.card.element, { name }).subscribe(async (resCreateToken) => {
                  if (resCreateToken.error) {
                    this.spinner.hide();
                    this.service.ShowError(resCreateToken.error.message);
                  } else {
                    if (this.listUserStirpeId.data[0].stripe_customer_id == null) {
                      let Cust = {
                        description: this.CohortName,
                        name: this.CardHolderName,
                        email: this.Email,
                        source: resCreateToken.token.id,
                        payment_method: null,
                        card: resCreateToken.token.card.id,
                        address: {
                          line1: this.Address,
                          postal_code: this.Zip,
                          city: this.City,
                          state: this.State,
                          country: this.Country
                        }
                      }
                      if (this.listUserStirpeId.data[0].stripe_customer_id == null) {
                        await this.stripePaymentService.CreateCustomer(Cust).then(async (CreateCustomerres) => {
                          var CustRespose = JSON.parse(<string>CreateCustomerres[0].json);
                          stripeCustomerid = CustRespose.id;
                        })
                      }
                    }
                    let UpdateCustomer = {
                      custmer: stripeCustomerid,
                      source: resCreateToken.token.id
                    }

                    await this.stripePaymentService.UpdateCustomer(UpdateCustomer).then(async (resUpdateCustmer) => {
                      await this.stripePaymentService.RetirveCustmer(stripeCustomerid).then(async (resRetirveCustmer) => {
                        this.RetirveCustmer = JSON.parse(<string>resRetirveCustmer[0].json);
                      })
                    })
                    let paymentMethod = {
                      type: 'card',
                      card: this.card.element
                    }
                    await this.stripeService.createPaymentMethod(paymentMethod).subscribe(async (resPaymethod) => {
                      this.stripePaymentService.AttachPaymentMethodToCustomer(resPaymethod.paymentMethod.id, stripeCustomerid).then(async (resRetirveCustmer) => {
                        this.ChargeCreate(resCreateToken, this.RetirveCustmer, resPaymethod, my_link)
                      })
                    });
                  }
                })
              })
            }
            else {
              var createPass = this.CreatePassword ? this.CreatePassword : "REWerew889##";
              await this.service.addUsertemp(this.CardHolderName, this.Email, 3, createPass, 0, "1234567890", "1").then(async (data) => {
                if (data[0].status == 200) {
                  var list = JSON.parse(<string>data[0].json);

                  this.UserId = list.data.id;
                  const monthNames = ["January", "February", "March", "April", "May", "June",
                    "July", "August", "September", "October", "November", "December"
                  ];
                  let usr = {
                    "user_id": list.data.id,
                    "cohort": this.Subscriptions[0].cohort_id,
                    "date": monthNames[new Date().getMonth()] + " " + this.getOrdinal(new Date().getDate())
                  }
                  let user_id = btoa(JSON.stringify(usr));
                  user_id = encodeURIComponent(user_id);
                  let my_link = "welcomertemp/" + user_id;
                  this.WelcomeLink = environment.SITE_URL + "/CL0/welcomertemp%2F" + user_id + "/1/010f017b110dd24a-022bf205-ec23-4cc4-ab6c-9d02ad5e16d9-000000/T1sENXdGWsJsn3icsoQqokSKTuu0X-WNMxWB5p6HcnM=14";
                  let name = this.CardHolderName

                  let paymentMethod = {
                    type: 'card',
                    card: this.card.element
                  }

                  await this.stripeService.createToken(this.card.element, { name }).subscribe(async (res) => {
                    if (res.error) {
                      this.spinner.hide();
                      this.service.ShowError(res.error.message);
                    } else {
                      this.stripeService.createPaymentMethod(paymentMethod).subscribe(async (paymethod) => {
                        let Cust = {
                          description: this.CohortName,
                          name: this.CardHolderName,
                          email: this.Email,
                          payment_method: paymethod.paymentMethod.id,
                          address: {
                            line1: this.Address,
                            postal_code: this.Zip,
                            city: this.City,
                            state: this.State,
                            country: this.Country

                          }
                        }
                        await this.stripePaymentService.CreateCustomer(Cust).then(async (CreateCustomerres) => {
                          var CustRespose = JSON.parse(<string>CreateCustomerres[0].json);
                          if (CreateCustomerres[0].status == 200) {
                            this.ChargeCreate(res, CustRespose, paymethod, my_link)
                          }
                          else {
                            this.spinner.hide();
                          }
                        })
                      })
                    }
                  })
                }
              })
            }
          }
        });
      }
    }
  }
  async ChargeCreate(TokenRespose, CustRespose, paymethodRes, my_link) {
    if (this.UserId == 'undefined' || this.UserId == undefined) {
      await this.LoginflowService.versions_getUserByEmail(
        this.Email
      ).then(async (GetUserID) => {
        this.listUserStirpeId = JSON.parse(<string>GetUserID[0].json);
        this.UserId = this.listUserStirpeId.data[0].id;
      })
    }
    await this.stripePaymentService.GetPlanRetrive(this.SubscriptionPriceID).then(async (planRes) => {
      var GetPlanRetruve = JSON.parse(<string>planRes[0].json)
      if (planRes[0].status == 200) {
        let Subscri = {
          customer: CustRespose.id,
          item: GetPlanRetruve.id
        }
        await this.stripePaymentService.CreateSubscriptionPlan(Subscri).then(async (result) => {
          if (result[0].status == 200) {
            var Subscription = JSON.parse(<string>result[0].json)
            let save_transaction = {
              user_id: this.UserId,
              name: this.CardHolderName,
              email: this.Email,
              address: this.Address,
              country: this.Country,
              city: this.City,
              state: this.State,
              zip: this.Zip,
              card_last4: paymethodRes.paymentMethod.card.last4,
              card_type: paymethodRes.paymentMethod.card.brand,
              expire_month: TokenRespose.token.card.exp_month,
              expire_year: TokenRespose.token.card.exp_year,
              payment_type: "subscription",
              plan_id: this.SubscriptionId,
              plan_description: this.plan_description,
              access_duration: this.access_duration,
              amount: (parseFloat(Subscription.plan.amount) / 100),
              payment_receipt: Subscription.latest_invoice,
              certi_id: this.Subscriptions[0].certi_id,
              cohort_id: this.Subscriptions[0].cohort_id
            };

            let access_dur = {
              user_id: this.UserId,
              cohort_id: this.Subscriptions[0].cohort_id,
              plan_id: this.SubscriptionId,
              plan_type: "subscription",
              access_duration: this.access_duration,
            }
            await this.service.addUserAccessDuration(access_dur).then(trn => {
              //here add record in access duration table
            });
            await this.service.savePaymentTransaction(save_transaction).then(trn => {
              //save transaction
            });
            let certi_id = 11;

            await this.service.addStudentToSelfCohort(this.Subscriptions[0].cohort_id, this.UserId.toString()).then(async (trn) => {
              //add student to self cohort
              if (result[0].status == 200) {
                var cohort_data = JSON.parse(<string>trn[0].json);

                certi_id = cohort_data.data.certi_id;
                let updateUser = {
                  course_id: this.Subscriptions[0].cohort_id,
                  email: this.Email,
                  stripe_customer_id: CustRespose.id
                }
                await this.service.updateUserSelfAndCustomer(updateUser).then(trn => {
                  //update user
                })
                let save_onbording = {
                  user_id: this.UserId,
                  cohort_id: this.Subscriptions[0].cohort_id,
                  is_selfpaced: 1
                }
                await this.service.addActivityTracker(this.UserId, this.Email, this.Subscriptions[0].cohort_id, "Payment", "Successfully self-paced subscription payment")
                await this.LoginflowService.add_onboarding_flow(save_onbording);
              }
            });

            let message = `<div class="introduce-mail" style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;width: 740px;margin: 56px auto;"> <div class="introduce-mail__wrapper" style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;position: relative;"> <div class="introduce-mail__container" style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;height: fit-content;background-image: linear-gradient(#151458, #151458);margin: auto;border-radius: 8px;overflow: hidden;float: left;width: 100%;"> <div class="introduce-mail__hero" style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;display: block;height: 115px;justify-content: space-between;padding: 0 40px 8px 54px;background-image: url(https://welcomeemailtemplate.s3.us-east-2.amazonaws.com/hero-bg.png);background-size: cover; float: left;width: 100%;"> <div class="introduce-mail__hero__logo" style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;display: block;float: right;padding-top: 14px; width: 120px;height: 120px;background: white;border-radius: 50%;margin-top: 25px; text-align: center;"> <img src="https://welcomeemailtemplate.s3.us-east-2.amazonaws.com/logo.png" style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;width: 100px; height: 50px;"> <div class="introduce-mail__hero__logo__txt" style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;font-weight: bold;text-transform: uppercase;font-size: 13px;color:#000;"> Destination</div> <div class="introduce-mail__hero__logo__subtxt" style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;text-transform: uppercase;font-size: 9px;color:#000;"> Certification</div> </div> </div> <div class="introduce-mail__main" style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;display: block;height: calc(100% - 115px);padding: 36px 55px 18px 55px;"> <div class="introduce-mail__main__overview-section section-margin" style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;display: block;flex-direction: column;margin-bottom: 34px;margin: 130px 0 30px 0;"> <h2 class="normal" style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;font-size: 26px;line-height: 29px;font-weight: normal;font-style:normal;margin: 0;color: #ADA1FF;"> Receipt from Destination Certification Inc.</h2> <p style="margin: 0px;color: #ffffffb5;font-size: 12px;font-family: arial, 'helvetica neue', helvetica, sans-serif;margin-top:2px;"> Receipt {Receipt#}</p> <table style="width: 100%;text-align:left;margin-top: 15px;"> <tr style="font-size: 11px;color: #ffffffb5;"> <th>AMOUNT PAID</th> <th>DATE PAID</th> <th>PAYMENT METHOD</th> </tr> <tr style="font-size: 15px;color:#fff;font-weight: 600;"> <td>{AmountPaid}</td> <td>{DatePaid}</td> <td>{PaymentMethod}</td> </tr> </table> <p style="font-size: 11px;color: #ffffffb5;margin: 15px 0px 0px 0px;">PURCHASED</p> <p style="font-size: 15px;color:#fff;font-weight: 600; margin: 10px 0 0 0;">{Purchased}</p> <p style="font-size: 11px;color: #ffffffb5;margin: 15px 0px 0px 0px;">ACCESS</p> <p style="font-size: 15px;color:#fff;font-weight: 600; margin: 10px 0 0 0;">{AccessDate}</p> <p style="font-size: 12px;color:#ac9ffc;font-weight: 600; margin: 10px 0 0 10px;">*Your Memebership will auto-renew monthly starting {NextAccessDate}</p> <h2 class="normal" style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;font-size: 18px;line-height: 29px;font-weight: normal;font-style:normal;margin: 0;color: #f473b9;margin-top:40px; "> Your Journey Begins! We're excited to your guide</h2> <div> <a style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;width: 160px;height: 40px;display: block; padding:10px; text-align:center;align-items: center;justify-content: center;background-color: #f33ea0;border-radius: 20px;font-size: 15px;line-height: 17px;letter-spacing: 0.5;color: white;cursor: pointer;margin-top: 23px;margin-bottom: 35px;font-weight: 600;text-decoration: none;" href="{access_link}">Let's Go!</a> </div> <p style="color: #b5b6bf;font-size: 15px;margin: 1em;background-color: #1C2069;padding: 10px;border-radius: 6px;">If you have any questions, please contact us at <a style="color: #f473b9;" href="mailto:support@flexxon.com">support@flexxon.com</a> </p> <p style="font-family: arial, 'helvetica neue', helvetica, sans-serif;box-sizing: border-box;font-size: 13px;line-height: 20px;letter-spacing: 0.54;color: #ffffffb5; border-top: dashed 2px #ada1ff3b;margin-top: 30px;padding-top: 30px; "> Destination Certification Inc. Victoria, BC, CA </p> </div> </div> </div> </div></div>`;
            message = message.replace("{Receipt#}", Subscription.latest_invoice);
            message = message.replace("{AmountPaid}", "$" + (parseFloat(Subscription.plan.amount) / 100).toString());
            message = message.replace("{DatePaid}", new Date(1000 * Subscription.plan.created).toLocaleString('default', { month: 'short' }) + " " + new Date(1000 * Subscription.plan.created).getDate() + ", " + new Date(1000 * Subscription.plan.created).getFullYear());
            message = message.replace("{PaymentMethod}", paymethodRes.paymentMethod.card.brand + "-" + paymethodRes.paymentMethod.card.last4);
            message = message.replace("{Purchased}", this.CohortName);

            message = message.replace("{AccessDate}", new Date(1000 * Subscription.current_period_start).toLocaleString('default', { month: 'short' }) + " " + new Date(1000 * Subscription.current_period_start).getDate() + ", " + new Date(1000 * Subscription.current_period_start).getFullYear() + " - " + new Date(1000 * Subscription.current_period_end).toLocaleString('default', { month: 'short' }) + " " + new Date(1000 * Subscription.current_period_end).getDate() + ", " + (new Date(1000 * Subscription.current_period_end).getFullYear()));
            message = message.replace("{access_link}", my_link);
            message = message.replace("{NextAccessDate}", new Date(1000 * Subscription.current_period_end).toLocaleString('default', { month: 'short' }) + " " + (new Date(1000 * Subscription.current_period_end).getDate() + 1) + ", " + (new Date(1000 * Subscription.current_period_end).getFullYear()));
            var datas = {
              to: this.Email,
              text: message,
              subject: "Welcome Mail From Destination Certification",
            }
            await this.auth.sendmail(datas).then(async (result) => {
              if (result[0].StatusCode == 1) {
                this.service.ShowSuccess("Payment Successful");
                this.PaymentSuccess = true;
                this.spinner.hide();
              }
            })

          }
          else {
            this.spinner.hide();
          }
        });

      }
      else {
        this.spinner.hide();
      }
    });
  }
  getOrdinal(n) {
    let ord = [, 'st', 'nd', 'rd'];
    let exceptions = [11, 12, 13];
    let nth = ((ord[n % 100] == undefined) || (exceptions.includes(n % 100))) ? 'th' : ord[n % 100];
    return n + nth;
  }

  async login() {
    if (this.LoginForm.valid) {
      if (this.email == '' || this.email == null || this.email == undefined) {
        this.service.ShowError('Email is required');
      } else if (
        this.password == '' ||
        this.password == null ||
        this.password == undefined
      ) {
        this.service.ShowError('Password is required');
      } else {
        try {
          await this.spinner.show();
          await this.LoginflowService.versions_getUserByEmail(this.email).then(
            async (data) => {
              if (data[0].status == 200) {
                var list = JSON.parse(<string>data[0].json);
                if (list.data.length > 0) {
                  this.email = list.data[0].email;
                  await this.auth.signIn(this.email, this.password).then(
                    async (data) => {

                      if (data[0].StatusCode == 1) {
                        this.Email = this.email;
                        this.msgBoxShow = false;
                        await this.LoginflowService.versions_getUserByEmail(
                          this.Email
                        ).then(async (StirpeId) => {
                          if (StirpeId[0].status == 200) {
                            this.listUserStirpeId = JSON.parse(<string>StirpeId[0].json);
                            await this.stripePaymentService.RetirveCustmer(this.listUserStirpeId.data[0].stripe_customer_id).then(async (resRetirveCustmer) => {
                              this.RetirveCustmer = JSON.parse(<string>resRetirveCustmer[0].json);

                              this.UserId = this.listUserStirpeId.data[0].id;
                              const monthNames = ["January", "February", "March", "April", "May", "June",
                                "July", "August", "September", "October", "November", "December"
                              ];
                              let usr = {
                                "user_id": this.listUserStirpeId.data[0].id,
                                "cohort": this.Subscriptions[0].cohort_id,
                                "date": monthNames[new Date().getMonth()] + " " + this.getOrdinal(new Date().getDate())
                              }
                              let user_id = btoa(JSON.stringify(usr));
                              user_id = encodeURIComponent(user_id);
                              let my_link = "welcomertemp/" + user_id;
                              this.WelcomeLink = environment.SITE_URL;
                              let name = this.CardHolderName
                              let stripeCustomerid = this.listUserStirpeId.data[0].stripe_customer_id;
                              await this.spinner.show();
                              await this.stripeService.createToken(this.card.element, { name }).subscribe(async (resCreateToken) => {
                                if (resCreateToken.error) {
                                  this.spinner.hide();
                                  this.service.ShowError(resCreateToken.error.message);
                                } else {
                                  if (this.listUserStirpeId.data[0].stripe_customer_id == null) {
                                    let Cust = {
                                      description: this.CohortName,
                                      name: this.CardHolderName,
                                      email: this.Email,
                                      source: resCreateToken.token.id,
                                      payment_method: null,
                                      card: resCreateToken.token.card.id,
                                      address: {
                                        line1: this.Address,
                                        postal_code: this.Zip,
                                        city: this.City,
                                        state: this.State,
                                        country: this.Country
                                      }
                                    }
                                    if (this.listUserStirpeId.data[0].stripe_customer_id == null) {
                                      await this.stripePaymentService.CreateCustomer(Cust).then(async (CreateCustomerres) => {
                                        var CustRespose = JSON.parse(<string>CreateCustomerres[0].json);
                                        stripeCustomerid = CustRespose.id;
                                      })
                                    }
                                  }
                                  let UpdateCustomer = {
                                    custmer: stripeCustomerid,
                                    source: resCreateToken.token.id
                                  }

                                  await this.stripePaymentService.UpdateCustomer(UpdateCustomer).then(async (resUpdateCustmer) => {
                                    await this.stripePaymentService.RetirveCustmer(stripeCustomerid).then(async (resRetirveCustmer) => {
                                      this.RetirveCustmer = JSON.parse(<string>resRetirveCustmer[0].json);
                                    })
                                  })
                                  let paymentMethod = {
                                    type: 'card',
                                    card: this.card.element
                                  }
                                  await this.stripeService.createPaymentMethod(paymentMethod).subscribe(async (resPaymethod) => {
                                    this.stripePaymentService.AttachPaymentMethodToCustomer(resPaymethod.paymentMethod.id, stripeCustomerid).then(async (resRetirveCustmer) => {
                                      this.ChargeCreate(resCreateToken, this.RetirveCustmer, resPaymethod, my_link)
                                    })

                                  });
                                }
                              })
                            })
                          }
                        });
                      } else {
                        if (data[0].message == 'User is not confirmed.') {
                          await this.spinner.hide();
                          var email = btoa(JSON.stringify(this.email));
                          email = encodeURIComponent(email);
                          this.router.navigate([`/authentication/${email}`]);
                        } else if (data[0].message == 'User does not exist.') {
                          await this.spinner.hide();
                          this.service.ShowError("You haven’t set up your account yet. Please check for a welcome email from system@destcert.com. Contained within the email is a link to the onboarding process.");
                        } else {
                          this.service.ShowError(data[0].message);
                          await this.spinner.hide();
                        }
                      }
                    },
                    (err) => {
                      this.spinner.hide();

                      this.service.ShowError('Encountered server error!');
                    }
                  );
                }
                else {
                  this.service.ShowError("User not found");
                  await this.spinner.hide();

                }
              }
              else {
                this.service.ShowError(data[0].message);
                await this.spinner.hide();

              }
            })
        } catch {
          this.spinner.hide();

          this.service.ShowError('Encountered server error!');
        }
      }
    } else {
      this.service.ShowError('username or password entered is incorrect');
    }
  }
  Cancel() {
    if (this.msgBoxShow)
      this.msgBoxShow = false;
  }
}
