import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { AlertService } from 'src/app/services/alert.service';
import { Testaservice} from './Testa.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 { Testacardvariable } from './Testa_cardvariable';
import { UserInfoService } from 'src/app/services/user-info.service';
declare var JsBarcode: any; 
@Component({
  selector: 'app-Testa',
  templateUrl: './Testa.component.html',
  styleUrls: ['./Testa.component.scss']
})
export class TestaComponent implements OnInit {
  cardButton = Testacardvariable.cardButton;
  cardmodeldata = Testacardvariable.cardmodeldata;
  public dashboardArray: DashboardContentModel2[];
  isCardview = Testacardvariable.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 = 'Testa_formCode'
tableName = 'Testa';  checkFormCode; selected: any[] = []; constructor(
    private extensionService: ExtensionService,
private userInfoService:UserInfoService,
    private mainService:Testaservice,
    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({
s_name : [null],

text_field : [null],

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





order_summary : [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 === "Testa_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.getallorder_summary();



    if (this.order_summarydefault) {
    // Listen for product changes to auto-fill description
    this.entryForm.get('order_summary')?.valueChanges.subscribe(name => {
      if (name && this.selectorder_summary) {

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

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

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

      }
    });
}


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





FileDataImageupload_field: any[];
  selectedImageupload_field: any[];





 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.selectedimageupload_field = [];
    this.mainService.uploadImageupload_fieldgetById(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDataimageupload_field = uploaddata;
    
    })

    this.selectedfileupload_field = [];
    this.mainService.uploadfilegetByIdfileupload_field(row.id,this.tableName).subscribe(uploaddata =>{
      console.log(uploaddata);
      this.FileDatafileupload_field = uploaddata;
    
    })




    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);






for (let i = 0; i < this.selectedimageupload_field.length; i++){

  this.mainService.uploadImageupload_field(data.id,this.tableName,this.selectedimageupload_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}

for (let i = 0; i < this.selectedfileupload_field.length; i++){

  this.mainService.uploadfilefileupload_field(data.id,this.tableName,this.selectedfileupload_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}



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





for (let i = 0; i < this.selectedimageupload_field.length; i++){

  this.mainService.uploadImageupload_field(data.id,this.tableName,this.selectedimageupload_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}

for (let i = 0; i < this.selectedfileupload_field.length; i++){

  this.mainService.uploadfilefileupload_field(data.id,this.tableName,this.selectedfileupload_field[i]).subscribe(uploaddata =>{
    console.log(uploaddata);
  })
}




      }, (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.FileDataImageupload_field = [];
this.selectedImageupload_field =[];

this.FileDatafileupload_field = [];
this.selectedfileupload_field =[];




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

} 






filePreviewimageupload_field: string | ArrayBuffer | null = null;
FileDataimageupload_field: {uploadedfile_name?:any, filePreview: string | ArrayBuffer | null }[] = []; // Initialize the array
selectedimageupload_field: File[]=[]; 
public onFileChangedimageupload_field(event, index) {
  const files = event.target.files;
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    this.FileDataimageupload_field[index].uploadedfile_name = files[i].name;
    this.selectedimageupload_field.push(files[i]);
    if (file.type.startsWith('image/')) {
      const reader = new FileReader();
      reader.onload = (e) => {
        // Set the file preview source
        const filePreview = e.target?.result as string;
        this.FileDataimageupload_field[index] = {
          ...this.FileDataimageupload_field[index], // Preserve existing properties
          filePreview: filePreview // Update only the filePreview property
        };
      };
      reader.readAsDataURL(file);
    }
  }
}
    onAddLinesimageupload_field(){
      this.FileDataimageupload_field.push({
        uploadedfile_name: "",
        filePreview: "",
        // f3: "",
      });
    }
    deleteRowimageupload_field(index,id) {
      this.FileDataimageupload_field.splice(index, 1);

      if(id){
      this.mainService.uploadImageupload_fielddelete(id).subscribe(data =>{
        console.log(data);
      })
      }
    }

filePreviewfileupload_field: string | ArrayBuffer | null = null;
FileDatafileupload_field: {uploadedfile_name?:any, filePreview: string | ArrayBuffer | null }[] = []; // Initialize the array
selectedfileupload_field: File[]=[]; 
public onFileChangedfileupload_field(event, index) {
  const files = event.target.files;
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    this.FileDatafileupload_field[index].uploadedfile_name = files[i].name;
    this.selectedfileupload_field.push(files[i]);
    if (file.type.startsWith('file/')) {
      const reader = new FileReader();
      reader.onload = (e) => {
        // Set the file preview source
        const filePreview = e.target?.result as string;
        this.FileDatafileupload_field[index] = {
          ...this.FileDatafileupload_field[index], // Preserve existing properties
          filePreview: filePreview // Update only the filePreview property
        };
      };
      reader.readAsDataURL(file);
    }
  }
}
    onAddLinesfileupload_field(){
      this.FileDatafileupload_field.push({
        uploadedfile_name: "",
        filePreview: "",
        // f3: "",
      });
    }
    deleteRowfileupload_field(index,id) {
      this.FileDatafileupload_field.splice(index, 1);

      if(id){
      this.mainService.uploadfiledeletefileupload_field(id).subscribe(data =>{
        console.log(data);
      })
      }
    }

order_summarydefault=true
selectorder_summary ;     
getallorder_summary() {
 this.mainService.getAllorder_summary().subscribe(data=>{
this.selectorder_summary = data;       
console.log(data);
},(error) => {       console.log(error);     });   }		



  // ================== ORDER SUMMARY LOGIC START ==================
  /**
   * Order Summary Array and Methods for Add to Order functionality
   */
  order_summarySummary: any[] = [];
  order_summarytotal;
isorder_summaryorder =true;
  /**
   * Add selected product to order summary
   */
  addorder_summaryOrder() {
    const formValue = this.entryForm.value;
    if (!formValue.order_summary ) {
      this.toastr.error('Please select Order Summary');
      return;
    }
    // Get description from master (selectorder_summary)


 
    let order_summaryname= '';
 

 
    let order_summarydescription= '';
 

   

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

 
      const found = this.selectorder_summary.find(p => p.name === formValue.order_summary);
 

    

 
  if (found && found.name) {
        order_summaryname = found.name;
      }

   

 
  if (found && found.description) {
        order_summarydescription = found.description;
      }

   

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

 
      name: order_summaryname, // always use master description

 

 
      description: order_summarydescription, // always use master description

 

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

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

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

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

  /**
   * Calculate grand total (subtotal + GST)
   */
  getorder_summaryGrandTotal(): number {
    return this.getorder_summarySubtotal() + this.getorder_summaryGST();

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


// updateaction
}











