import { Component, OnInit } from '@angular/core';


import { ToastrService } from 'ngx-toastr';
import { ActivatedRoute, Router } from '@angular/router';
import { College } from 'src/app/models/fnd/play';
import { student } from 'src/app/models/fnd/Studentadd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { ValidationError } from 'src/app/models/fnd/ValidationError';
import { test_vps_steperservice } from './test_vps_steper.service';
@Component({
  selector: 'app-editstepper',
  templateUrl: './test_vps_steper.component.html',
  styleUrls: ['./test_vps_steper.component.scss']
})
export class test_vps_steperComponent implements OnInit {
  updated = false;
  stringJson: any;
  customerId: string = '';
  selectedFile!: File;
  fileName = '';

  id: number;
  errorFields: ValidationError[] = [];
  appToUpdate: College = null;
  trained = false;

  json: string = "";
  luisApp =
    {
      name: '',
      created: 1,
      trained: 1,
      tested: 1,
      updated: 1,
      published: 1,

    };
  // Layout direction changing
  layout = {
    direction: "vertical",
    block1: "clr-col-lg-3 clr-col-12 ",
    block2: "clr-col-lg-9 clr-col-12 ",
  };

  timelineStyle = { 
 step0: { state: "current", open: true, failed: false }, 
    step1: { state: "not-started", open: false, failed: false },
    step2: { state: "not-started", open: false, failed: false },
};
public Customer_informationentryForm: FormGroup;
public Document_uploadentryForm: FormGroup;
  submitted = false;
  rowSelected: any = {};
  modalcomplete = false;

  constructor( 
private mainService: test_vps_steperservice,

private Customer_information_fb: FormBuilder, 
private Document_upload_fb: FormBuilder, 
private router: Router,
 private route: ActivatedRoute,
    private toastr: ToastrService,
  ) { }

  ngOnInit(): void {
    this.id = this.route.snapshot.params["id"];
    console.log("update with id = ", this.id);


 this.Customer_informationentryForm = this.Customer_information_fb.group({ 
name : [null],

description : [null],

active : [true],

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_field : [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],


  });












































 this.Document_uploadentryForm = this.Document_upload_fb.group({ 





  });




















































 const stepId = this.id; // or from route/query/etc
 
    this.getResolvedDataFromStepper(stepId).subscribe(res => {
      console.log('response get ', res);

      if (res === null) {
        this.showEmptyForm();
      } else {
 if (res['Customer_information']) {
 
 this.prefillCustomer_informationForm(res['Customer_information']);
        }

 if (res['Document_upload']) {
 
 this.prefillDocument_uploadForm(res['Document_upload']);
        }
}
    });

  }
showEmptyForm(): void {
    console.log('No config found. Showing empty form.');
    // You can choose to show one or both based on some logic

 this.Customer_informationentryForm.reset();

 this.Document_uploadentryForm.reset();
  }  prefillCustomer_informationForm(data: any): void {

    console.log(' Customer_information data ', data)
    this.Customer_informationentryForm.patchValue({
      id: data.id || '',
name: data.name || '',

description: data.description || '',

active: data.active || '',

visa_entry_type: data.visa_entry_type || '',

visa_duration: data.visa_duration || '',

visa_processing: data.visa_processing || '',

travel_start_date: data.travel_start_date || '',

travel_end_date: data.travel_end_date || '',

passport_number: data.passport_number || '',

passport_issue_date: data.passport_issue_date || '',

passport_expiry_date: data.passport_expiry_date || '',

email_field: data.email_field || '',

phone_number: data.phone_number || '',

birth_place: data.birth_place || '',

date_of_birth: data.date_of_birth || '',

gender: data.gender || '',

profession: data.profession || '',

visa_cost: data.visa_cost || '',

referrer: data.referrer || '',

nationality: data.nationality || '',

supplier: data.supplier || '',

agent: data.agent || '',

    });
  }  prefillDocument_uploadForm(data: any): void {

    console.log(' Document_upload data ', data)
    this.Document_uploadentryForm.patchValue({
      id: data.id || '',
imageupload_field: data.imageupload_field || '',

fileupload_field: data.fileupload_field || '',

    });
  }
 getResolvedDataFromStepper(id: number): Observable<any> {
    console.log('get step config');

    return new Observable(observer => {
      this.mainService.gettabledata(id).subscribe(configList => {
        if (!configList || configList.length === 0) {
          console.log('empty config');
          observer.next(null);
          observer.complete();
          return;
        }

        const results: { [key: string]: any } = {};
        let processed = 0;

        configList.forEach(config => {
          const { table_name, table_id } = config;

          this.getByTableNameAndId(table_name, table_id).subscribe(data => {

            console.log('data is ', data);
            results[table_name] = data;

            processed++;
            if (processed === configList.length) {
              observer.next(results);  // emit combined data
              observer.complete();
            }

          }, error => {
            console.error(`Error loading data for table ${table_name}`, error);
            processed++;
            if (processed === configList.length) {
              observer.next(results);  // continue with what we have
              observer.complete();
            }
          });
        });

      }, error => {
        console.error("Error loading stepper config", error);
        observer.error(error);
      });
    });
  }



  getByTableNameAndId(tableName: string, id: number): Observable<any> {

    switch (tableName) {
   case 'Customer_information':
        return this.mainService.getCustomer_informationById(id); case 'Document_upload':
        return this.mainService.getDocument_uploadById(id);// aur bhi cases agar naye table add ho to
      default:
        throw new Error(`Unknown table name: ${tableName}`);
    }
  }
  // Change to Horizontal Layout
  changeToHorizonTal() {
    this.layout = {
      direction: "horizontal",
      block1: "clr-col-lg-12 clr-col-12 height container",
      block2: "clr-col-lg-12 clr-col-12 container",
    }
  }
  // Change to Vertical Layout
  changeToVertical() {
    this.layout = {
      direction: "vertical",
      block1: "clr-col-lg-3 clr-col-12 ",
      block2: "clr-col-lg-9 clr-col-12 ",
    }
  }



  onCustomer_informationSave() {
    console.log('Form Submitted:', this.Customer_informationentryForm.value);
    this.submitted = true;
    if (this.Customer_informationentryForm.invalid) {

      console.log('invalid form ..');
      // Log all form errors
      Object.keys(this.Customer_informationentryForm.controls).forEach(field => {
        const control = this.Customer_informationentryForm.get(field);
        if (control && control.invalid) {
          console.log(`Error in field: ${field}`, control.errors);
        }
      }
      );
      return;
    }
    this.onCustomer_informationCreate();
  }

  onCustomer_informationCreate() {












































    this.mainService.createCustomer_information(this.Customer_informationentryForm.value).subscribe(
      (data) => {
        console.log('adding data ', data);
        this.customerId = data.id;

        console.log('id is  ', this.customerId);


 const tableId = data.id;
        const tableName = 'Customer_information';
        const stepperId = this.id;

        // Save stepper config
        this.mainService.saveStepperConfig(stepperId, tableId, tableName).subscribe(() => {
          this.toastr.success("Stepper Config Saved");
        });        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");
        }
      });
    this.rowSelected = this.Customer_informationentryForm.value;

    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }


  onDocument_uploadSave() {
    console.log('Form Submitted:', this.Document_uploadentryForm.value);
    this.submitted = true;
    if (this.Document_uploadentryForm.invalid) {

      console.log('invalid form ..');
      // Log all form errors
      Object.keys(this.Document_uploadentryForm.controls).forEach(field => {
        const control = this.Document_uploadentryForm.get(field);
        if (control && control.invalid) {
          console.log(`Error in field: ${field}`, control.errors);
        }
      }
      );
      return;
    }
    this.onDocument_uploadCreate();
  }

  onDocument_uploadCreate() {




    this.mainService.createDocument_upload(this.Document_uploadentryForm.value).subscribe(
      (data) => {
        console.log('adding data ', data);
        this.customerId = data.id;

        console.log('id is  ', this.customerId);


 const tableId = data.id;
        const tableName = 'Document_upload';
        const stepperId = this.id;

        // Save stepper config
        this.mainService.saveStepperConfig(stepperId, tableId, tableName).subscribe(() => {
          this.toastr.success("Stepper Config Saved");
        });        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,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,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");
        }
      });
    this.rowSelected = this.Document_uploadentryForm.value;

    setTimeout(() => {
      this.ngOnInit();
    }, 500);
  }


  onnext() {
    this.router.navigate(["../../main/workflow"], { relativeTo: this.route });
  }
  reset() {
    this.json = "";
    this.luisApp =
    {
      name: '',
      trained: 1,
      tested: 1,
      updated: 1,
      published: 1,
      created: 1,

    };

    this.timelineStyle = {
      step0: { state: "current", open: true, failed: false },
      step1: { state: "not-started", open: false, failed: false },
      step2: { state: "not-started", open: false, failed: false },
 };
  }
  current() {
    console.log(this.timelineStyle)
    this.stringJson = JSON.stringify(this.timelineStyle);
    console.log("String json object :", this.stringJson);

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













































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



// updateaction
}















































