import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AlertService } from 'src/app/services/alert.service';
import { Formaservice} from './Forma.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 { Formacardvariable } from './Forma_cardvariable';
import { UserInfoService } from 'src/app/services/user-info.service';
declare var JsBarcode: any; 
@Component({
  selector: 'app-Forma',
  templateUrl: './Forma.component.html',
  styleUrls: ['./Forma.component.scss']
})
export class FormaComponent implements OnInit {
  cardButton = Formacardvariable.cardButton;
  cardmodeldata = Formacardvariable.cardmodeldata;
  public dashboardArray: DashboardContentModel2[];
  isCardview = Formacardvariable.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 = 'Forma_formCode'
tableName = 'Forma';  checkFormCode; selected: any[] = []; constructor(
    private extensionService: ExtensionService,
private userInfoService:UserInfoService,
    private mainService:Formaservice,
    private alertService: AlertService,
    private toastr: ToastrService,
    private _fb: FormBuilder,
  ) { }
  private editInterval: any;
// 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({
namess : [null],

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

phone_number: ['+91'],

paragraph_field : [null],

password_field : [null],
confirmpassword_field : [null],

textarea : [null],

date_field : [null],

datetime_field : [null],

email_field : [null],

toggle_switch : [true],

url_field : [null],

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

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

recaptcha : ['', [Validators.required,this.checkrecaptcha.bind(this)]],

documentsequence : [null],



select_stat : [null],

select_mul : [null],

select_dya : [null],

select_dyamu : [null],

select_auto : [null],

select_automul : [null],


 







    }, {
        validator: Confirmedpassword_fieldValidator('password_field', 'confirmpassword_field')



































  }); // 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 === "Forma_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.generaterecaptcha()









this.getallselect_dya();



    if (this.select_dyadefault) {
    // Listen for product changes to auto-fill description


 
    this.entryForm.get('select_dya')?.valueChanges.subscribe(name => {
      if (name && this.selectselect_dya) {

        const found = this.selectselect_dya.find(p => p.name === name);
 


        console.log('found is ', found);

        // Auto-fill price when product is selected
        if (found && found.default_field) {
          this.entryForm.patchValue({ default_field: found.default_field_link });
        } else {
          this.entryForm.patchValue({ default_field: null });
        }

      }
    });
}

this.getallselect_dyamu();

this.getallselect_auto();

this.getallselect_automul();


  }
 ngOnDestroy(): void {
    if (this.editInterval) {
      clearInterval(this.editInterval);
    }
  }











































 error; 
  getData() {
    this.mainService.getAll().subscribe((data) => {
      console.log(data);
      this.product = data;
this.product = [...this.product].reverse(); 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.nodeEditPropertiesselect_mul.editselectedAttributesselect_mul = JSON.parse(this.rowSelected.select_mul );



this.nodeEditPropertiesselect_dyamu.editselectedAttributesselect_dyamu = JSON.parse(this.rowSelected.select_dyamu );



this.nodeEditPropertiesselect_automul.editselectedAttributesselect_automul = JSON.parse(this.rowSelected.select_automul );


    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;


































this.rowSelected.select_mul  = JSON.stringify(this.nodeEditPropertiesselect_mul.editselectedAttributesselect_mul  );



this.rowSelected.select_dyamu  = JSON.stringify(this.nodeEditPropertiesselect_dyamu.editselectedAttributesselect_dyamu  );



this.rowSelected.select_automul  = JSON.stringify(this.nodeEditPropertiesselect_automul.editselectedAttributesselect_automul  );

    //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.entryForm.value.select_mul  = JSON.stringify(this.nodeEditPropertiesselect_mul.addselectedAttributesselect_mul );



this.entryForm.value.select_dyamu  = JSON.stringify(this.nodeEditPropertiesselect_dyamu.addselectedAttributesselect_dyamu );



this.entryForm.value.select_automul  = JSON.stringify(this.nodeEditPropertiesselect_automul.addselectedAttributesselect_automul );

  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;





































this.nodeEditPropertiesselect_dyamu.addselectedAttributesselect_dyamu = ""



this.nodeEditPropertiesselect_automul.addselectedAttributesselect_automul = ""


  }
 submitted = false;
onSubmit() {
  console.log(this.entryForm.value);
 this.submitted = true;
  if (this.entryForm.invalid) {
    return;
  }this.onCreate();

} 




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

rsModalparagraph_field = false;  
 goToReplaceStringparagraph_field (row){
						    this.rowSelected = row;     this.rsModalparagraph_field  =true;   }

newpHidepassword_field: boolean = true;
 newIconpassword_field: string = "eye"; 
newShapeChangerpassword_field() {
this.newpHidepassword_field = !this.newpHidepassword_field;  
 if(this.newpHidepassword_field){
this.newIconpassword_field = 'eye'   } else {     this.newIconpassword_field = 'eye-hide'   }
} 

 newaddpHidepassword_field: boolean = true;
 newaddIconpassword_field: string = "eye";
newaddChangerpassword_field() {   this.newaddpHidepassword_field = !this.newaddpHidepassword_field;
 if(this.newaddpHidepassword_field){     this.newaddIconpassword_field = 'eye'   } else {
  this.newaddIconpassword_field = 'eye-hide'   } }

rsModaltextarea = false;   
goToReplaceStringtextarea(row){
this.rowSelected = row;     this.rsModaltextarea  =true;   }





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



isValidurl_field(url: string): boolean {
						    return  /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/.test(url);   } 
						goTourl_fieldUrl(val){     window.open(val)   }





recaptchaCode = '';  
generaterecaptcha (): void {
  const possibleCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const codeLength = 6; // Change to desired length

  let recaptcha= '';
  for (let i = 0; i < codeLength; i++) {
    const randomIndex = Math.floor(Math.random() * possibleCharacters.length);
    recaptcha += possibleCharacters.charAt(randomIndex);
  }
  this.recaptchaCode = recaptcha;
}

checkrecaptcha(control: AbstractControl): ValidationErrors | null {
  if (control.value !== this.recaptchaCode) {
    return { recaptchaMismatch: true };
  }
  return null;
}  

recaptchaMismatch = false;  

checkrecaptchaEdit(): void {
	  if (this.rowSelected.recaptcha  !== this. recaptchaCode) {
	  this. recaptchaMismatch = true;    } else {      this.recaptchaMismatch = false;    }  } 







nodeEditPropertiesselect_mul  = {   addselectedAttributesselect_mul :"",   editselectedAttributesselect_mul :"" }
							 selectselect_mul =[
								
 
								'a',
								 

 
								'b',
								 

 
								'c',
								 

							];

select_dyadefault=false
selectselect_dya ;     
getallselect_dya() {
 this.mainService.getAllselect_dya().subscribe(data=>{
this.selectselect_dya = data;       
console.log(data);
},(error) => {       console.log(error);     });   }		



  // ================== ORDER SUMMARY LOGIC START ==================
  /**
   * Order Summary Array and Methods for Add to Order functionality
   */
  select_dyaSummary: any[] = [];
  select_dyatotal;
isselect_dyaorder =false;
  /**
   * Add selected product to order summary
   */
  addselect_dyaOrder() {
    const formValue = this.entryForm.value;
    if (!formValue.select_dya ) {
      this.toastr.error('Please select select dya');
      return;
    }
    // Get description from master (selectselect_dya)


   

    if (this.selectselect_dya && Array.isArray(this.selectselect_dya)) {

 
      const found = this.selectselect_dya.find(p => p.name === formValue.select_dya);
 

    

    }
    const line = this.select_dyaSummary.length + 1;
    const orderItem = {
      line: line,

      // unitPrice: Number(formValue.price),
      // quantity: Number(formValue.quantity),
      // total: Number(formValue.price) * Number(formValue.quantity)
    };
    this.select_dyaSummary.push(orderItem);
    
    this.select_dyatotal = '';
  }

  /**
   * Remove item from order summary by index
   */
  removeselect_dyaOrder(index: number) {
    this.select_dyaSummary.splice(index, 1);
    // Recalculate line numbers
    this.select_dyaSummary.forEach((item, i) => {
      item.line = i + 1;
    });
  }

  /**
   * Calculate subtotal of all order items
   */
  getselect_dyaSubtotal(): number {
    return this.select_dyaSummary.reduce((sum, item) => sum + item.total, 0);
  }

  /**
   * Calculate GST (18%)
   */
  getselect_dyaGST(): number {
    return this.getselect_dyaSubtotal() * 0.18;
  }

  /**
   * Calculate grand total (subtotal + GST)
   */
  getselect_dyaGrandTotal(): number {
    return this.getselect_dyaSubtotal() + this.getselect_dyaGST();

  }
  // ================== ORDER SUMMARY LOGIC END ==================


selectselect_dyamu;    
 getallselect_dyamu () {
		this.mainService.getAllselect_dyamu().subscribe(data=>{
							      this.selectselect_dyamu = data;     
  console.log(data);
 },(error) => {       console.log(error);     });   } 
 nodeEditPropertiesselect_dyamu  = {     addselectedAttributesselect_dyamu:"",  editselectedAttributesselect_dyamu :""   }

selectselect_auto ;    
 getallselect_auto () {
							    this.mainService.getAllselect_auto().subscribe(data=>{
							      this.selectselect_auto = data;       console.log(data);
							    },(error) => {       console.log(error);     });   }

selectselect_automul;    
 getallselect_automul () {
		this.mainService.getAllselect_automul().subscribe(data=>{
							      this.selectselect_automul = data;     
  console.log(data);
 },(error) => {       console.log(error);     });   } 
 nodeEditPropertiesselect_automul  = {     addselectedAttributesselect_automul:"",  editselectedAttributesselect_automul :""   }

// updateaction
}







export function Confirmedpassword_fieldValidator(controlName: string, matchingControlName: string){
  return (formGroup: FormGroup) => {
      const control = formGroup.controls[controlName];
      const matchingControl = formGroup.controls[matchingControlName];
      if (matchingControl.errors && !matchingControl.errors.confirmedpassword_fieldValidator) {
          return;
      }
      if (control.value !== matchingControl.value) {
          matchingControl.setErrors({ confirmedpassword_fieldValidator: true });
      } else {
          matchingControl.setErrors(null);
      }
  }
}




































