import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AlertService } from 'src/app/services/alert.service';
import { Visa_applicationservice } from './Visa_application.service';
import { AbstractControl, FormArray, FormBuilder, FormGroup, Validators, ValidationErrors } from '@angular/forms';
import { ExtensionService } from 'src/app/services/fnd/extension.service';
import { DashboardContentModel2 } from 'src/app/models/builder/dashboard';
import { Visa_applicationcardvariable } from './Visa_application_cardvariable';
import { UserInfoService } from 'src/app/services/user-info.service';
import { ActivatedRoute, Router } from '@angular/router';
declare var JsBarcode: any;
@Component({
  selector: 'app-Visa_application',
  templateUrl: './Visa_application.component.html',
  styleUrls: ['./Visa_application.component.scss']
})
export class Visa_applicationComponent implements OnInit {
  cardButton = Visa_applicationcardvariable.cardButton;
  cardmodeldata = Visa_applicationcardvariable.cardmodeldata;
  public dashboardArray: DashboardContentModel2[];
  isCardview = Visa_applicationcardvariable.cardButton;
  cardmodal;

  changeView() {
    this.isCardview = !this.isCardview;
  }
  beforeText(fieldtext: string): string { // Extract the text before the first '<'
    const index = fieldtext.indexOf('<');
    return index !== -1 ? fieldtext.substring(0, index) : fieldtext;
  }
  afterText(fieldtext: string): string { // Extract the text after the last '>'
    const index = fieldtext.lastIndexOf('>');
    return index !== -1 ? fieldtext.substring(index + 1) : '';
  }
  transform(fieldtext: string): string {
    const match = fieldtext.match(/<([^>]*)>/);
    return match ? match[1] : ''; // Extract the text between '<' and '>'
  }
  userrole;
  rowSelected: any = {};
  modaldelete = false;
  modalEdit = false;
  modalAdd = false;
  public entryForm: FormGroup;
  loading = false;
  product;
  modalOpenedforNewLine = false;
  newLine: any;
  additionalFieldsFromBackend: any[] = [];
  formcode = 'Visa_application_formCode'
  tableName = 'Visa_application'; checkFormCode; selected: any[] = []; constructor(
    private extensionService: ExtensionService,
    private userInfoService: UserInfoService,
    private mainService: Visa_applicationservice,
    private alertService: AlertService,
    private toastr: ToastrService,
    private _fb: FormBuilder,
    private router: Router,
    private route: ActivatedRoute,


  ) { }
  // component button 
  ngOnInit(): void {
    if (this.cardmodeldata !== '') {
      this.cardmodal = JSON.parse(this.cardmodeldata);
      this.dashboardArray = this.cardmodal.dashboard.slice();
      console.log(this.dashboardArray)
    }
    this.userrole = this.userInfoService.getRoles();
    this.getData();
    this.entryForm = this._fb.group({
      name: [null],

      description: [null],

      active: [false],

      visa_entry_type: [null],

      visa_duration: [null],

      visa_processing: [null],

      travel_start_date: [null],

      travel_end_date: [null],

      passport_number: [null, [Validators.required]],

      passport_issue_date: [null],

      passport_expiry_date: [null],

      email: [null],

      phone_number: ['+91'],

      birth_place: [null],

      date_of_birth: [null],

      gender: [null],

      profession: [null],

      visa_cost: [null, { updateOn: 'blur' }],

      referrer: [null],

      nationality: [null],

      supplier: [null],

      agent: [null],



    }); // component_button200
    // form code start
    this.extensionService.getJsonObjectsByFormCodeList(this.formcode).subscribe(data => {
      console.log(data);
      const jsonArray = data.map((str) => JSON.parse(str));
      this.additionalFieldsFromBackend = jsonArray;
      this.checkFormCode = this.additionalFieldsFromBackend.some(field => field.formCode === "Visa_application_formCode");
      console.log(this.checkFormCode);
      console.log(this.additionalFieldsFromBackend);
      if (this.additionalFieldsFromBackend && this.additionalFieldsFromBackend.length > 0) {
        this.additionalFieldsFromBackend.forEach(field => {
          if (field.formCode === this.formcode) {
            if (!this.entryForm.contains(field.extValue)) {
              // Add the control only if it doesn't exist in the form
              this.entryForm.addControl(field.extValue, this._fb.control(field.fieldValue));
            }
          }
        });
      }
    });
    console.log(this.entryForm.value);
    // form code end 


    this.getallvisa_entry_type();

    this.getallvisa_duration();

    this.getallvisa_processing();

    this.getallgender();

    this.getallreferrer();

    this.getallnationality();

    this.getallsupplier();

    this.getallagent();


  }

  error;
  getData() {
    this.mainService.getAll().subscribe((data) => {
      console.log(data);
      this.product = data;
      if (this.product.length == 0) {
        this.error = "No Data Available"
      }
    }, (error) => {
      console.log(error);
      if (error) {
        this.error = "Server Error";
      }
    });
  }
  onEdit(row) {
    this.rowSelected = row;


    this.modalEdit = true;
  }
  onDelete(row) {
    this.rowSelected = row;
    this.modaldelete = true;
  }
  delete(id) {
    this.modaldelete = false;
    console.log("in delete  " + id);
    this.mainService.delete(id).subscribe(
      (data) => {
        console.log(data);
        this.ngOnInit();
        if (data) { this.toastr.success('Deleted successfully'); }
      });
  }
  onUpdate(id) {
    this.modalEdit = false;

    //console.log("in update");
    console.log("id  " + id);
    console.log(this.rowSelected);
    //console.log("out update");
    this.mainService.update(id, this.rowSelected).subscribe(
      (data) => {
        console.log(data);
        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Update Successfully");
        }
        setTimeout(() => {
          this.ngOnInit();
        }, 500);


      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("update Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Updated");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Updated");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }
  onCreate() {
    this.modalAdd = false;



    this.mainService.create(this.entryForm.value).subscribe(
      (data) => {
        console.log(data);
        if (data || data.status >= 200 && data.status <= 299) {
          this.toastr.success("Added Successfully");
        }
        setTimeout(() => {
          this.ngOnInit();
        }, 500);



      }, (error) => {
        console.log(error);
        if (error.status >= 200 && error.status <= 299) {
          // this.toastr.success("Added Succesfully");
        }
        if (error.status >= 400 && error.status <= 499) {
          this.toastr.error("Not Added");
        }
        if (error.status >= 500 && error.status <= 599) {
          this.toastr.error("Not Added");
        }
      });
    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }
  // goToAdd(row) {
  //   this.modalAdd = true; this.submitted = false;
  // }

  goToAdd() {
    this.router.navigate(["../stepper"], { relativeTo: this.route });
  }
  submitted = false;
  onSubmit() {
    console.log(this.entryForm.value);
    this.submitted = true;
    if (this.entryForm.invalid) {
      return;
    } this.onCreate();

  }


  rsModaldescription = false;
  goToReplaceStringdescription(row) {
    this.rowSelected = row; this.rsModaldescription = true;
  }



  selectvisa_entry_type;
  getallvisa_entry_type() {
    this.mainService.getAllvisa_entry_type().subscribe(data => {
      this.selectvisa_entry_type = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }

  selectvisa_duration;
  getallvisa_duration() {
    this.mainService.getAllvisa_duration().subscribe(data => {
      this.selectvisa_duration = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }

  selectvisa_processing;
  getallvisa_processing() {
    this.mainService.getAllvisa_processing().subscribe(data => {
      this.selectvisa_processing = data;
      console.log('visa processing ', data);
    }, (error) => { console.log(error); });
  }

  isValidemail(email: string): boolean {
    const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return emailPattern.test(email);
  }

  isValidPhone_number(phone: string): boolean {
    const phonePattern = /^(\+[1-9][0-9]{0,2})?[1-9][0-9]{9}$/;
    return phonePattern.test(phone);
  }





  selectgender;
  getallgender() {
    this.mainService.getAllgender().subscribe(data => {
      this.selectgender = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }



  //currency  field start
  formatCurrencyvisa_cost() {
    // Format the currency with two decimal places    
    this.rowSelected.visa_cost = Number(this.rowSelected.visa_cost).toFixed(2);
    // Remove commas from the formatted currency   
    this.rowSelected.visa_cost = this.rowSelected.visa_cost?.replace(/,/g, '');
  }
  //currency  field end

  selectreferrer;
  getallreferrer() {
    this.mainService.getAllreferrer().subscribe(data => {
      this.selectreferrer = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }

  selectnationality;
  getallnationality() {
    this.mainService.getAllnationality().subscribe(data => {
      this.selectnationality = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }

  selectsupplier;
  getallsupplier() {
    this.mainService.getAllsupplier().subscribe(data => {
      this.selectsupplier = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }

  selectagent;
  getallagent() {
    this.mainService.getAllagent().subscribe(data => {
      this.selectagent = data;
      console.log(data);
    }, (error) => { console.log(error); });
  }

  // updateaction


}











































