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-onetimepayment',
  templateUrl: './onetimepayment.component.html',
  styleUrls: ['./onetimepayment.component.scss']
})
export class OnetimepaymentComponent implements OnInit {
  @ViewChild(StripeCardComponent) card: StripeCardComponent;

  CardHolderName: any;
  Email: any;
  Address: any;
  Country: any;
  City: any;
  State: any;
  Zip: any;

  SelectedPlan = 1;
  Amount = 25 * 100;
  ButtonText = "Pay";
  Materials = [];
  Subscriptions = [];
  CohortName: any;
  UserId: any;
  PaymentSuccess: boolean = false;
  WelcomeLink = "";
  PlanType = "";
  Productid = "";
  SubscriptionPriceID = "";
  SubscriptionId: any;
  plan_description: any;
  access_duration: any;
  listUserStirpeId: any;
  RetirveCustmer: any;
  CustmerCardDetails: any;
  public PayForm: FormGroup;
  email: any;
  password: any;
  ChangePasswordPlaceHolder: string = "Create Password"
  isCreatePassword: boolean = false;
  isEnterPassword: boolean = false;
  CreatePassword: any;
  EnterPassword: any;
  isPasswordError: boolean = false;

  public LoginForm: FormGroup;
  msgBoxShow: boolean = false;;
  cardOptions: StripeCardElementOptions = {
    style: {
      base: {
        iconColor: '#b89cc7',
        color: '#b89cc7',
        '::placeholder': {
          color: '#b89cc7'
        }
      }
    },
    hidePostalCode: true,
  };
  elementsOptions: StripeElementsOptions = {
    locale: 'en'
  };
  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.Productid = "prod_JyE5TYUIWdTKse";
        this.PlanType = data.PaymentType;
        this.SubscriptionPriceID = "price_1JKHdTSDoKn6aBzEiy9lDPs3";
        this.SubscriptionId = data.SubscriptionId;
        await this.getOneTimeMembershipDetails(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: ['', Validators.required],
      Country: ['', Validators.required],
      City: ['', Validators.required],
      State: ['', Validators.required],
      Zip: ['', Validators.required],
    });

    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 getOneTimeMembershipDetails(SubscriptionId, SelectedPlan) {
    this.spinner.show();
    await this.service.getOneTimeMembershipDetail(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.OneTime;
        if (this.Subscriptions.length > 0) {
          this.ButtonText = "Pay $" + (this.Subscriptions[0].price ? this.Subscriptions[0].price : 0);
          this.Amount = this.Subscriptions[0].price ? parseFloat(this.Subscriptions[0].price.substr(1, this.Subscriptions[0].price.length)) * 100 : 0;
          this.plan_description = this.Subscriptions[0].description;
          this.access_duration = this.Subscriptions[0].access_duration;
        }
        this.spinner.hide();
      }

    })
  }

  async payOneTime() {
    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.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.CreateCharge(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,
                        source: res.token.id,
                        payment_method: null,
                        card: res.token.card.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.CreateCharge(res, CustRespose, paymethod, my_link)
                        }
                        else {
                          this.spinner.hide();
                        }
                      })
                    })
                  }
                })
              }
            })
          }
        }
      })
    }
  }

  async CreateCharge(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.oneTimePayment(TokenRespose.token.id, this.Amount, this.Email, CustRespose).then(async (res) => {
      let onetime = JSON.parse(res[0].json);

      if (res[0].status == 200) {
        let message = `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office" lang="en"><head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1" name="viewport"> <meta name="x-apple-disable-message-reformatting"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="telephone=no" name="format-detection"> <title>Activation Code</title></head><body style="width:100%;font-family:arial, 'helvetica neue', helvetica, sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;padding:0;Margin:0; background-color:#F4F4F4;"> <span style="display:none !important;visibility:hidden;mso-hide:all;font-size:1px;line-height:1px;max-height:0px;max-width:0px;opacity:0;overflow:hidden;">Thank you! Here is your receipt</span> <span style="display:none !important;visibility:hidden;mso-hide:all;font-size:1px;line-height:1px;max-height:0px;max-width:0px;opacity:0;overflow:hidden;"> ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ </span> <div class="es-wrapper-color" style="background-color:#F4F4F4"> <table class="es-wrapper" width="100%" cellspacing="0" cellpadding="0" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;padding:0;Margin:0;width:100%;height:100%;background-repeat:repeat;background-position:center top"> <tr> <td valign="top" style="padding:0;Margin:0"> <table class="es-header" cellspacing="0" cellpadding="0" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;table-layout:fixed !important;width:100%;background-color:transparent;background-repeat:repeat;background-position:center top"> <tr> <td align="center" bgcolor="#f4f4f4" style="padding:0;Margin:0;background-color:#f4f4f4"> <table class="es-header-body" cellspacing="0" cellpadding="0" bgcolor="#f4f4f4" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;background-color:#f4f4f4;width:600px"> <tr> <td align="left" style="padding:0;Margin:0"> <table width="100%" cellspacing="0" cellpadding="0" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> <tr> <td valign="top" align="center" style="padding:0;Margin:0;width:600px"> <table width="100%" cellspacing="0" cellpadding="0" bgcolor="#151458" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;background-color:#151458"> <tr> <td align="center" style="padding:0;Margin:0;font-size:0px"><a target="_blank" href="https://my.destcert.com/" style="-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;text-decoration:underline;color:#1376C8;font-size:14px"><img class="adapt-img" src="https://welcomeemailtemplate.s3.us-east-2.amazonaws.com/modified_0-2.png" alt="Destination Certification" style="display:block;border:0;outline:none;text-decoration:none;-ms-interpolation-mode:bicubic" width="600" title="Destination Certification" height="121"></a></td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> <table class="es-content" cellspacing="0" cellpadding="0" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;table-layout:fixed !important;width:100%"> <tr> <td align="center" bgcolor="#f4f4f4" style="padding:0;Margin:0;background-color:#f4f4f4"> <table class="es-content-body" cellspacing="0" cellpadding="0" bgcolor="#f4f4f4" align="center" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px;background-color:#f4f4f4;width:600px"> <tr> <td class="es-m-p20r es-m-p20l" align="left" bgcolor="#151458" style="padding:0;Margin:0;padding-left:30px;padding-right:30px;background-color:#151458"> <table cellspacing="0" cellpadding="0" width="100%" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> <tr> <td align="left" style="padding:0;Margin:0;width:540px"> <table width="100%" cellspacing="0" cellpadding="0" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> <tr> <td align="left" style="padding:0;Margin:0;padding-top:10px"> <h1 style="Margin:0;line-height:31px;mso-line-height-rule:exactly;font-family:arial, 'helvetica neue', helvetica, sans-serif;font-size:26px;font-style:normal;font-weight:normal;color:#ADA1FF"> Receipt from Destination Certification Inc.</h1> <p style="margin: 0px;color: #ffffffb5;font-size: 12px;font-family: arial, 'helvetica neue', helvetica, sans-serif;margin-top:2px;"> Receipt {Receipt#}</p> </td> </tr> <tr> <td> <table style="width: 100%;text-align:left;margin-top: 15px;"> <tbody><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> </tbody></table> </td> </tr> <tr> <td> <table style="width: 100%;text-align:left;margin-top: 15px;"> <tbody><tr style="font-size: 11px;color: #ffffffb5;"> <th>PURCHASED</th> </tr> <tr style="font-size: 15px;color:#fff;font-weight: 600;"> <td>{Purchased}</td></tr> </tbody></table> </td> </tr> <tr> <td> <table style="width: 100%;text-align:left;margin-top: 15px;"> <tbody><tr style="font-size: 11px;color: #ffffffb5;"> <th>ACCESS</th> </tr> <tr style="font-size: 15px;color:#fff;font-weight: 600;"> <td>{AccessDate}</td></tr> </tbody></table> <p style="font-size: 12px;color:#ac9ffc;font-weight: 600; margin: 10px 0 0 10px;">*Your Membership will not auto-renew </p> </td> </tr> <tr> <td align="left" style="padding:0;Margin:0;padding-top:20px;padding-bottom:20px"> <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:20px; "> Your Journey Begins! We're excited to your guide</h2> </td> </tr> <tr> <td> <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-bottom: 35px;font-weight: 600;text-decoration: none;" href="{access_link}">Let's Go!</a> </td> </tr> </table> </td> </tr> </table> </td> </tr> <tr> <td class="es-m-p20r es-m-p20l" align="left" bgcolor="#151458" style="Margin:0;padding-top:10px;padding-bottom:30px;padding-left:30px;padding-right:30px;background-color:#151458"> <table cellpadding="0" cellspacing="0" width="100%" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> <tr> <td align="center" valign="top" style="padding:0;Margin:0;width:540px"> <table cellpadding="0" cellspacing="0" width="100%" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:separate;border-spacing:0px;border-radius:10px" role="presentation"> <tr> <td align="center" Margin:0"> <p style="color: #b5b6bf;font-size: 15px;margin: 0;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> </td> </tr> <tr> <td align="center" style="padding:0;Margin:0;padding-top:30px;padding-bottom:30px;font-size:0"> <table border="0" width="100%" height="100%" cellpadding="0" cellspacing="0" style="mso-table-lspace:0pt;mso-table-rspace:0pt;border-collapse:collapse;border-spacing:0px"> <tr> <td style="padding:0;Margin:0;border-bottom:dashed 2px #ada1ff3b;background:none;height:1px;width:100%;margin:0px"> </td> </tr> </table> </td> </tr> <tr> <td align="left" style="padding:0;Margin:0;padding-bottom:20px"> <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; "> Destination Certification Inc. Victoria, BC, CA </p> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </div> <grammarly-desktop-integration data-grammarly-shadow-root="true"></grammarly-desktop-integration></body></html>`;

        message = message.replace("{Receipt#}", onetime.id);
        message = message.replace("{AmountPaid}", "$" + (parseFloat(onetime.amount) / 100).toString());
        message = message.replace("{DatePaid}", new Date(1000 * onetime.created).toLocaleString('default', { month: 'short' }) + " " + new Date(1000 * onetime.created).getDate() + ", " + new Date(1000 * onetime.created).getFullYear());
        message = message.replace("{PaymentMethod}", onetime.source.brand + "-" + onetime.source.last4);
        message = message.replace("{Purchased}", this.CohortName);
        message = message.replace("{AccessDate}", new Date(1000 * onetime.created).toLocaleString('default', { month: 'short' }) + " " + new Date(1000 * onetime.created).getDate() + ", " + new Date(1000 * onetime.created).getFullYear() + " to " + new Date(1000 * onetime.created).toLocaleString('default', { month: 'short' }) + " " + new Date(1000 * onetime.created).getDate() + ", " + (new Date(1000 * onetime.created).getFullYear() + 1));
        message = message.replace("{access_link}", my_link);
        var datas = {
          to: this.Email,
          text: message,
          subject: "Receipt from Destination Certification Inc.",
        }
        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: onetime.source.last4,
          card_type: onetime.source.brand,
          expire_month: onetime.payment_method_details.card.exp_month,
          expire_year: onetime.payment_method_details.card.exp_year,
          payment_type: "onetime",
          plan_id: this.SubscriptionId,
          plan_description: this.plan_description,
          access_duration: this.access_duration,
          amount: (parseFloat(onetime.amount) / 100),
          payment_receipt: onetime.id,
          certi_id: this.Subscriptions[0].certi_id,
          cohort_id: this.Subscriptions[0].cohort_id
        };
        await this.service.savePaymentTransaction(save_transaction).then(trn => {

        })
        let certi_id = this.Subscriptions[0].certi_id;

        await this.service.addStudentToSelfCohort(this.Subscriptions[0].cohort_id, this.UserId.toString()).then(async (trn) => {
          //add student to self cohort
          var addstd = JSON.parse(<string>trn[0].json);
          if (trn[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 one-time payment")
            await this.LoginflowService.add_onboarding_flow(save_onbording);
          }
        });
        await this.auth.sendmail(datas).then(async (result) => {
          if (result[0].StatusCode == 1) {
            this.service.ShowSuccess("Payment Successful");
            this.PaymentSuccess = true;

          }
        })
        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.CreateCharge(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;
  }
}
