import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { CommonFunctionService } from '../services/commonfunctions.service';
import { DatePipe } from '@angular/common';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { DataTableDirective } from 'angular-datatables';
import { ViewChild } from '@angular/core'
import { CountryISO, PhoneNumberFormat, SearchCountryField } from 'ngx-intl-tel-input';
import { parsePhoneNumberFromString } from 'libphonenumber-js';

@Component({
  selector: 'dvr-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']

})
export class ContactComponent implements OnInit {

  @ViewChild(DataTableDirective, { static: false })
  dtElement: DataTableDirective;

// Inside your component class
selectedCustomerFilter: string = ''; // Holds the name selected in the new filter dropdown
// ... (Your existing properties: dtElement, dtTrigger, contactList, cust_data)
  public contactForm !: FormGroup;
  
  currentDateData: any = [];
  CountryISO = CountryISO;
  PhoneNumberFormat = PhoneNumberFormat;
  SearchCountryField = SearchCountryField;
  loginData: any = [];
  login_name: any;
  last_login_date: any;
  login_id: any;
  msg: any;
  cust_data: any = [];
  currentURL: any;
  cont_name: any;
  contnav_flag: boolean = false;
  mySelect: any;
  cont_id: any;
  isEditMode: boolean = false;
  selectedContactId: number | null = null;
  checkfirstnm_flag: boolean = false;
  checklastnm_flag: boolean = false;
  checkmobilleno_flag: boolean = false;
  displayStyle = "none";
  error_msg: any;
  success_msg: boolean = false;
  status_msg: any;

  disabled_flag: boolean = false;
  contactList: any = [];
  contactList1: any = [];

  dtOptions = {};
  dtTrigger: Subject<any> = new Subject();

  designations = ["Executive","AM","Manager","Senior Manager","GM","AGM","PMO","DVP","AVP","VP","VP 1","VP 2","SVP","SVP 1","SVP 2","EVP","Head","CTO","CIO","CISO","CFO","President","Director","Managing Director","CEO"];
  functions = ["All", "Infra","Cloud","Devops","Digital Transformation","Applications","Testing","Vendor Management","Procurement","Finance","Audit","Business Systems","Quality Assurance", "Buiness Solutions Group"];
  departments = ["IT","Procurement","Finance","Business"];

  sucess_flag: boolean = false;
  backtodvr_flag: boolean = false;
  check_successflag: boolean = false;

  emailID_flag: boolean = true;
  role: any;


  displayMessage: { [key: string]: string } = {};
  private validationMessage: { [key: string]: { [key: string]: string } }
  rows = [];


  constructor(private commonservice: CommonFunctionService, private router: Router, private fb: FormBuilder) {

 this.dtOptions = {
  stateSave: true,   // 👈 ADD THIS
  stateSaveCallback: function(settings, data) {
    localStorage.setItem('customerTableState', JSON.stringify(data));
  },
  stateLoadCallback: function(settings) {
    return JSON.parse(localStorage.getItem('customerTableState'));
  },
  stateDuration: -1, // 👈 keeps forever (uses localStorage)
  pagingType: 'full_numbers',
  pageLength: 15,
  processing: true,
  order: [],
  lengthMenu: [15, 25, 35],
  ordering: true,
  dom: 'Blfrtip',

initComplete: function(settings: any, json: any) {
  const api = new $.fn.dataTable.Api(settings);

    /* Existing filter relocation */
  const filterContainer = document.querySelector('.dataTables_filter');
  const dropdown = document.getElementById('customer-filter-container');

  if (filterContainer && dropdown) {
    dropdown.style.display = 'inline-block';
    filterContainer.insertBefore(dropdown, filterContainer.firstChild);
  }

  // Add filter row for spacing (optional)
  const tableHeader = $(settings.nTable).find('thead');
  if (!tableHeader.find('.filter-row').length) {
    tableHeader.append('<tr class="filter-row"></tr>');
  }
  const filterRow = tableHeader.find('.filter-row');
  // var skipFilterCols = [2, 3, 4, 5];
  const skipFilterCols = ['First Name', 'Last Name', 'Email ID', 'Mobile Number', 'Alternate Mobile Number'];

  console.log(skipFilterCols);

  api.columns().every(function () {
    const column = this;
    const colIndex = column.index();
    const header = $(column.header());
    const colName = header.text().trim(); // get column name text

    // --- SORT BUTTON (always added) ---
    // const sortBtn = $('<button class="sort-btn"></button>');
    const sortBtn = $('<button class="sort-btn" style="margin-left:4px;border:none;background:none;cursor:pointer;font-size:12px;"></button>');

    let sortState = 0;
    sortBtn.on('click', function () {
      // if (sortState === 0) { api.order([colIndex,'asc']).draw(); sortBtn.text('▲'); sortState = 1; }
      // else if (sortState === 1) { api.order([colIndex,'desc']).draw(); sortBtn.text('▼'); sortState = 2; }
      // else { api.order([]).draw(); sortBtn.text('⬍'); sortState = 0; }
    });
    header.append(sortBtn);

    // --- Skip filter if column is in skip list ---
    // if (skipFilterCols.includes(colIndex) || header.hasClass('no-export')) return;
    // Skip filter if column is in skipFilterCols or has 'no-export' class
    if (skipFilterCols.includes(colName) || header.hasClass('no-export')) return;

    // --- FILTER BUTTON AND DROPDOWN ---
    const filterBtn = $('<button type="button" class="filter-btn">⬇</button>').appendTo(header);
    const dropdown = $('<div style="opacity: 1; background: white; overflow-y: auto; max-height: 400px;" class="floating-filter-dropdown"></div>').appendTo('body').hide();

    // Unique sorted values
    const uniqueValues = column.data()
      .unique()
      .toArray()
      .filter(d => d != null && d !== '')
      .map(d => d.toString())
      .sort((a,b) => a.localeCompare(b));

    // "All" checkbox
    const allCheckbox = $(`
      <div>
        <input type="checkbox" id="all_${colIndex}" value="all" checked>
        <label for="all_${colIndex}">All</label>
      </div>
    `);
    dropdown.append(allCheckbox);

    // Individual checkboxes
    uniqueValues.forEach(val => {
      const id = `filter_${colIndex}_${val.replace(/\s+/g,'_')}`;
      const checkbox = $(`
        <div>
          <input type="checkbox" id="${id}" value="${val}" checked>
          <label for="${id}">${val}</label>
        </div>
      `);
      dropdown.append(checkbox);
    });

    
    
    // Restore saved search
    const savedSearch = column.search();

    if (savedSearch) {
      const values = savedSearch.split('|')
        .map(v => v.replace(/^\^|\$$/g, '')); // remove ^ and $

      dropdown.find('input[type=checkbox]').not('[value="all"]').each(function () {
        const val = $(this).val()?.toString();
        $(this).prop('checked', values.includes(val));
      });

      const total = dropdown.find('input[type=checkbox]').not('[value="all"]').length;
      const checkedCount = dropdown.find('input[type=checkbox]:checked').not('[value="all"]').length;

      allCheckbox.find('input').prop('checked', checkedCount === total);
    }

    // --- Checkbox handling ---
    dropdown.on('change', 'input[type=checkbox]', function () {
      const allChecked = allCheckbox.find('input').prop('checked');

      if ($(this).val() === 'all') {
        const checked = $(this).prop('checked');
        dropdown.find('input[type=checkbox]').prop('checked', checked);
      } else {
        const total = dropdown.find('input[type=checkbox]').not('[value="all"]').length;
        const checkedCount = dropdown.find('input[type=checkbox]:checked').not('[value="all"]').length;
        allCheckbox.find('input').prop('checked', checkedCount === total);
      }

      const selectedValues: string[] = dropdown.find('input[type=checkbox]:checked').not('[value="all"]').map((i, el) => $(el).val()?.toString() || '').get();
      if (selectedValues.length === 0 || allChecked) column.search('').draw();
      else {
        // const regex = selectedValues.map(v => $.fn.dataTable.util.escapeRegex(v)).join('|');
        const regex = selectedValues.map(v => '^' + $.fn.dataTable.util.escapeRegex(v) + '$').join('|');
        column.search(regex, true, false).draw();
      }
    });

    // --- Show/hide dropdown ---
    filterBtn.on('click', function (e) {
      e.stopPropagation();
      const offset = filterBtn.offset();
      dropdown.css({
        top: offset.top + filterBtn.outerHeight() + 2,
        left: offset.left,
        position: 'absolute',
        zIndex: 1000
      }).toggle();
    });

// Prevent clicks inside the dropdown from closing it
dropdown.on('click', function (e) {
  e.stopPropagation(); // stops the document click from firing
});

// Only hide dropdown when clicking outside
$(document).on('click', function () {
  dropdown.hide();
});
  });
}
,
  buttons: [
    {
      extend: 'print',
      title: 'Contact Details Reports',
      exportOptions: {
        columns: ':not(.no-export)'
      }
    },
    {
      extend: 'excelHtml5',
      title: 'Contact Details Reports',
      exportOptions: {
        columns: ':not(.no-export)'
      }
    }
  ]
};

    console.log("in contact");
    console.log(this.router.url);
    var url = this.router.url;
    console.log("url------->", url);
    var myArray = url.split(":");
    //console.log("myArray", myArray);
    this.cont_id = myArray[2];
    var res = myArray[1];
    if (myArray.length > 1) {
      this.disabled_flag = true;
      var myArray1 = res.split("/");
      //console.log("myArray1",myArray1[0]);
      let result = decodeURI(myArray1[0])

      // let result = myArray1[0].replace("%20", " ");

      this.cont_name = result;
      this.commonservice.getAllData(this.commonservice.projectpath + "/getcustcontactdetails?customer_id=" + this.cont_name).subscribe(response => {
        if (response.status == 'tokenfalse') {
          this.router.navigate(['/login'])
        } else {
          console.log("aaaaaaaaaaa", this.contactList);

          this.contactList = response.data[0].conrtactData;
          // console.log("aaaaaaaaaaa", this.contactList);
          this.dtTrigger.next(this.dtOptions)


          // this.dtTrigger.next(this.dtOptions)

          //this.contactList = response.data[0].conrtactData;
          //console.log("check length",response.data[0]);
          if (response.data[0].getdvrDataStatus == '1') {
            //data not found
            console.log("in dataa not found");

          } else {
            console.log("in data");
            // $(document).ready(function () {
            //   $("#TABLE_ID").DataTable();
            //   $(".dataTables_empty").empty();
            //   $(".odd").empty();
            // });

          }

          // this.dtTrigger.next(this.dtOptions)
        }
      });
      //console.log("res", this.cont_name);

    }



  }


  loadData() {
   if (this.cont_name) {
      console.log("in if")
      this.contnav_flag = true;

    } else {
      this.contnav_flag = false;

      this.commonservice.getAllData(this.commonservice.projectpath + "/getcustcontactdetails?customer_id=0&passid=number").subscribe(response => {
        if (response.status == 'tokenfalse') {
          this.router.navigate(['/login'])
        } else {
          this.contactList = response.data[0].conrtactData;
          console.log("aaaaaaaaaaa------------>", this.contactList);
          // this.dtTrigger.next(this.dtOptions);
          this.rerender();

          // 4. 🔥 NEW STEP: Move the filter after a short delay to ensure DataTables is done
        // setTimeout(() => {
        //     // Find the DataTables filter search box wrapper
        //     const dtFilterWrapper = $('.dataTables_filter');
            
        //     // Get the HTML content of the filter dropdown you rendered elsewhere
        //     const filterToMove = $('#filter-to-move').html();

        //     if (dtFilterWrapper.length > 0) {
        //         // Insert the HTML content BEFORE the DataTables search box
        //         dtFilterWrapper.prepend(filterToMove);
                
        //         // Re-bind the Angular function to the newly moved element
        //         // NOTE: This requires you to ensure the (ngModelChange) binding still works 
        //         // on the dynamically moved element, which might need Angular's Renderer2. 
        //         // For quick jQuery fix, you'd need to re-bind the change event manually here.
                
        //         // --- QUICK FIX: Manual Change Event Re-binding ---
        //         $('#CustomerFilter').on('change', (e) => {
        //             this.selectedCustomerFilter = $(e.target).val() as string;
        //             this.filterByCustomerName();
        //         });
        //     }
        // }, 100); // Small delay
        }
      });
    }

    this.commonservice.getAllData(this.commonservice.projectpath + "/getselectionData").subscribe(response => {
      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])
      } else {
        // this.cust_data = response.data[0].customerData;
        this.cust_data = response.data[0].customerData;
        if(this.role === 'users') {
          this.cust_data = this.cust_data.filter(item => item.first_name + " " + item.last_name === this.login_name);
        }
        this.cust_data = Array.from(
        new Map(
          this.cust_data.map(item => [
            `${item.customer_id}-${item.customer_name}`,
            {
              customer_id: item.customer_id,
              customer_name: item.customer_name
            }
          ])
        ).values()
      );
        console.log(this.cust_data);
        console.log("yyyyyyyyyyyyyy");

      }
    });

  }
  
  ngOnInit() {

    this.contactList = [];

    

    this.loginData.push(JSON.parse(localStorage.getItem("loginData")));
    console.log("", this.loginData[0]["user_name"]);
    this.login_name = this.loginData[0]["user_name"];
    this.last_login_date = this.loginData[0]["last_loginDate"];
    this.login_id = this.loginData[0]["user_id"];
    this.role = this.loginData[0]["role"];

    this.contactForm = new FormGroup({
      first_name: new FormControl('', [Validators.required, Validators.pattern(/^[a-zA-Z]+(['-][a-zA-Z]+)*$/)]),
      last_name: new FormControl('', [Validators.required, Validators.pattern(/^[a-zA-Z]+(['-][a-zA-Z]+)*$/)]),
      mobile_number: new FormControl('', [Validators.required]),
      designation: new FormControl(null, Validators.required),
      email_Id: new FormControl('', [Validators.pattern(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/), Validators.required]),
      department: new FormControl('', Validators.required),
      function: new FormControl('', Validators.required),
      mob_no: new FormControl('')
    })

    this.loadData();
  }
  

  contactData(form: FormGroup) {

    console.log(this.isEditMode);
    if (this.isEditMode) {
      console.log("EDITING");
      return;
    }
    this.msg = "";

    console.log("first name", form.value.first_name);
    console.log("last name", form.value.last_name);
    console.log("email_Id", form.value.email_Id);
    var email_Id = form.value.email_Id;

    // if (form.value.first_name !=null && form.value.email_Id != null) {
    //   console.log("check email id validation");
    //   var mailformat = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$";
    //   if (email_Id.match(mailformat)) {
    //     this.emailID_flag = true;

    //   }
    //   else {
    //     this.openPopup();
    //     this.status_msg = "Warning";
    //     this.error_msg = "You have entered an invalid email address!"
    //     this.emailID_flag = false;
    //   }
    // }


    if (this.cont_name) {

      console.log("get from url")
      console.log(this.cont_id);
      const phoneValue = form.value.mobile_number;
      const formattedPhone = typeof phoneValue === 'object' ? phoneValue.e164Number : phoneValue;
      const altPhoneValue = form.value.mob_no;
      const cleanAltMobile = typeof altPhoneValue === 'object' ? altPhoneValue.e164Number : altPhoneValue;
      const contactData = {
        first_name: form.value.first_name,
        last_name: form.value.last_name,
        mobile_no: formattedPhone,
        email_id: form.value.email_Id,
        designation: form.value.designation,
        department: form.value.department,
        function: form.value.function,
        contact_for: this.cont_id,
        created_by: this.login_id,
        mob_no: cleanAltMobile


      }

      if (this.emailID_flag == true) {
        this.commonservice.getData(this.commonservice.projectpath + "/createContactEntry", contactData).subscribe(response => {

          console.log("in create contact response=========>", response);

          if (response.status == 'tokenfalse') {
            this.router.navigate(['/login'])
          } else {
            // console.log("response", response);
            this.msg = response["message"];
            if (response["createStatus"] == '0') {

              //reset form 

              if (response.data.length == 0) {
                //warning 
                console.log("inside if")
                this.openPopup();
                this.status_msg = "Warning";
                this.error_msg = response.error;
              } else if (response.data.length > 0) {
                console.log("inside else condition ")


                this.openPopup();
                this.sucess_flag = true;
                this.status_msg = "Success";
                this.error_msg = response.data[0].message;
                // console.log("response.data.message", response.data[0].exception.errorid);

                if (response.data[0].exception.errorid != '') {
                  this.openPopup();
                  this.status_msg = "Warning";
                  this.error_msg = response.error;
                }
              }
              else {
                this.status_msg = "";
                this.error_msg = "";
              }
            } else {
              if (response.data.length == 0) {
                //warning 
                console.log("inside if")
                this.openPopup();
                this.status_msg = "Warning";
                this.error_msg = response.error;
              }
              else if (response.data.length > 0) {
                console.log("inside if(response.message== '') 99999999999")
                if (response.data[0].createStatus == 1 && response.data[0].exception.errorid == 400) {
                  console.log("duplicate contact");
                   this.openPopup();
                    this.status_msg = "Warning";
                    this.error_msg = response.data[0].exception.errormessage;
                }else{
                  this.backtodvr_flag = true;
                  console.log("response.data[0].lastinsertedData", response.data[0].lastinsertedData);
                  localStorage.setItem('contactlastinsert', response.data[0].lastinsertedData);
                  this.openPopup();
                  this.status_msg = "Success";
                  this.error_msg = response.data[0].message;
                  // console.log("response.data.message", response.data[0].exception.errorid);
                  if (response.data[0].exception.errorid != '') {
                    this.openPopup();
                    this.status_msg = "Warning";
                    this.error_msg = response.error;
                  }
                }
              } else if (response.data[0].createStatus == 1 && response.data[0].exception.errorid == 400) {
                this.openPopup();
                this.status_msg = "Warning";
                this.error_msg = response.error;
              }
              else {
                this.status_msg = "";
                this.error_msg = "";
              }
            }
          }
        });
      }



    } else {
      console.log("getting from dropdown");
      const phoneValue = form.value.mobile_number;
      const formattedPhone = typeof phoneValue === 'object' ? phoneValue.e164Number : phoneValue;
      let cleanAltMobile = null;
      if (form.value.mob_no) {
        const altPhoneValue = form.value.mob_no;
        cleanAltMobile = typeof altPhoneValue === 'object' ? altPhoneValue.e164Number : altPhoneValue;
      }      
      console.log(form.value.mobile_number);
      console.log(formattedPhone);
      const contactData = {
        first_name: form.value.first_name,
        last_name: form.value.last_name,
        mobile_no: formattedPhone,
        email_id: form.value.email_Id,
        designation: form.value.designation,
        department: form.value.department,
        function: form.value.function,
        contact_for: (this.mySelect ? this.mySelect.customer_id : ''),
        created_by: this.login_id,
        mob_no: cleanAltMobile

      }
      console.log("contactData", contactData);
      // console.log("res", this.mySelect);


      if (this.emailID_flag == true) {
        this.commonservice.getData(this.commonservice.projectpath + "/createContactEntry", contactData).subscribe(response => {

          console.log("response", response);

          if (response.status == 'tokenfalse') {
            this.router.navigate(['/login'])
          } else {
            // console.log("response", response);
            this.msg = response["message"];
            if (response["createStatus"] == '0') {

              //reset form 

              if (response.data.length == 0) {
                //warning 
                console.log("inside if")
                this.openPopup();
                this.status_msg = "Warning";
                this.error_msg = response.error;
              } else if (response.data.length > 0) {
                console.log("inside if(response.message== '')6666666666 ")
                this.openPopup();
                this.sucess_flag = true;
                this.status_msg = "Success";
                this.error_msg = response.data[0].message;
                this.checkfirstnm_flag = true;
                this.mySelect = "";
                // this.contactForm = new FormGroup({
                //   first_name: new FormControl('', Validators.required),
                //   last_name: new FormControl('', Validators.required),
                //   mobile_number: new FormControl('', [Validators.required, Validators.maxLength(10)]),
                //   designation: new FormControl(null, Validators.required),
                //   email_Id: new FormControl('', Validators.required),
                //   department: new FormControl('', Validators.required),
                //   function: new FormControl('', Validators.required),
                //   mob_no: new FormControl('', [Validators.required, Validators.maxLength(10)])
                // })
                this.contactForm = new FormGroup({
                first_name: new FormControl('', [Validators.required, Validators.pattern(/^[a-zA-Z]+(['-][a-zA-Z]+)*$/)]),
                last_name: new FormControl('', [Validators.required, Validators.pattern(/^[a-zA-Z]+(['-][a-zA-Z]+)*$/)]),
                mobile_number: new FormControl('', Validators.required),
                designation: new FormControl(null, Validators.required),
                email_Id: new FormControl('', [Validators.pattern(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/), Validators.required]),
                department: new FormControl('', Validators.required),
                function: new FormControl('', Validators.required),
                mob_no: new FormControl('', Validators.pattern(/^[6-9]\d{4}\s?\d{5}$/))
              })
                // console.log("response.data.message", response.data[0].exception.errorid);
                if (response.data[0].exception.errorid != '') {
                  this.openPopup();
                  this.status_msg = "Warning";
                  this.error_msg = response.error;
                }
              }
              else {
                this.status_msg = "";
                this.error_msg = "";
              }
            } else {
              if (response.data.length == 0) {
                //warning 
                console.log("inside if")
                this.openPopup();
                this.status_msg = "Warning";
                this.error_msg = response.error || response.data[0].exception.errormessage;
              }
              else if (response.data.length > 0) {
                console.log("inside if(response.message== '')222222222222 ")
                if (response.data[0].createStatus == 1 && response.data[0].exception.errorid == 400) {
                  console.log("duplicate contact");
                   this.openPopup();
                    this.status_msg = "Warning";
                    this.error_msg = response.data[0].exception.errormessage || response.error;
                } else {
                  this.openPopup();
                  this.status_msg = "Success";
                  this.error_msg = response.data[0].message;
                  this.checkfirstnm_flag = true;
                  this.mySelect = "";
                  // this.contactForm = new FormGroup({
                  //   first_name: new FormControl('', Validators.required),
                  //   last_name: new FormControl('', Validators.required),
                  //   mobile_number: new FormControl('', [Validators.required, Validators.maxLength(10)]),
                  //   designation: new FormControl(null, Validators.required),
                  //   email_Id: new FormControl('', Validators.required),
                  //   department: new FormControl('', Validators.required),
                  //   function: new FormControl('', Validators.required),
                  //   mob_no: new FormControl('', [Validators.required, Validators.maxLength(10)])
                  // })
                  this.contactForm = new FormGroup({
                  first_name: new FormControl('', [Validators.required, Validators.pattern(/^[a-zA-Z]+(['-][a-zA-Z]+)*$/)]),
                  last_name: new FormControl('', [Validators.required, Validators.pattern(/^[a-zA-Z]+(['-][a-zA-Z]+)*$/)]),
                  mobile_number: new FormControl('', Validators.required),
                  designation: new FormControl(null, Validators.required),
                  email_Id: new FormControl('', [Validators.pattern(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/), Validators.required]),
                  department: new FormControl('', Validators.required),
                  function: new FormControl('', Validators.required),
                  mob_no: new FormControl('', Validators.pattern(/^[6-9]\d{4}\s?\d{5}$/))
                })
                  // console.log("response.data.message", response.data[0].exception.errorid);
                  if (response.data[0].exception.errorid != '') {
                    this.openPopup();
                    this.status_msg = "Warning";
                    this.error_msg = response.error || response.data[0].exception.errormessage;
                  }
                }

              }
              else {
                this.status_msg = "";
                this.error_msg = "";
              }
            }
          }
        });
      }




    }

  }

onEditButtonClick() {
    if (this.isEditMode) {
        this.updateContact();
    }
}

updateContact() {

  console.log("Updating");
  console.log(this.contactForm.value);

    if (!this.selectedContactId) return;

    const updatedData = this.contactForm.value;
    updatedData.contact_id = this.selectedContactId;
    updatedData.customer_id = (this.mySelect ? this.mySelect.customer_id : '');
    updatedData.updated_by = this.login_id;
    updatedData.mobile_number = updatedData.mobile_number.e164Number;
    updatedData.mob_no = updatedData.mob_no.e164Number;
    console.log(updatedData);

    this.commonservice.updateContact(this.commonservice.projectpath + "/updateContactDetails", updatedData).subscribe(
      response => {
      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])
      } 
      else if (response.updateContactStatus == 0) {
        console.log("Contact Updated");
        alert("Contact updated successfully!");
        this.isEditMode = false;
        this.selectedContactId = null;
        this.contactForm.reset();
        this.loadData();
      }
      else {
          const msg = response.message || response.error;
            alert("Error updating contact!  " + msg);
        }
    });
}

  editContact(contact: any) {
    this.isEditMode = true;
    this.selectedContactId = contact.contact_id;
    console.log(this.selectedContactId);
    console.log(contact);

      // const phoneValue = contact.mobile_number;
      // const altPhoneValue = contact.mob_no;
    const parsedMobile = this.parsePhoneNumberAuto(contact.mobile_number);
    const parsedAltMobile = this.parsePhoneNumberAuto(contact.mob_no);

    this.contactForm.patchValue({
        first_name: contact.first_name,
        last_name: contact.last_name,
        email_Id: contact.email_id,
        mobile_number: parsedMobile,
        mob_no: parsedAltMobile,
        designation: contact.designation,
        department: contact.department,
        function: contact.function_area
    });

    const nameToSelect = contact.customer_name;
    const selected = this.cust_data.find(c => c.customer_name === nameToSelect);
    console.log(selected);

    if (selected) {
      this.mySelect = selected;
    }

    // Scroll to top where the form is
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

deleteContact(contact_id: any) {
  console.log(contact_id);
  // deleteData.updated_by = this.login_id;
  // deleteData.contact_id = this.selectedContactId;
    if (confirm("Are you sure you want to delete this contact?")) {
      this.commonservice.deleteContact(this.commonservice.projectpath + "/deleteContactDetails", this.login_id, contact_id).subscribe(
      response => {
      if (response.status == 'tokenfalse') {
        this.router.navigate(['/login'])
      } 
      else if (response.deleteContactStatus == 0) {
        console.log("Contact Deleted");
        alert("Contact deleted successfully!");
        this.loadData();
      }
      else {
          const msg = response.message || response.error;
            alert("Error updating contact!  " + msg);
        }
    });
    }
}

  resetForm() {
    this.msg = "";
  }

  onReset() {
  this.contactForm.reset();
  const defaultPhone = this.parsePhoneNumberAuto('');
  console.log(defaultPhone);
  this.contactForm.patchValue({
    mobile_number: defaultPhone,
    mob_no: defaultPhone
  });
  this.isEditMode = false;
}

rerender(): void {
  // 1. Check if the DataTables instance exists
  if (this.dtElement && this.dtElement.dtInstance) { // Added check for dtElement itself
    this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
      // 2. **DESTROY:** Destroy the existing table instance
      dtInstance.destroy();
      window.location.reload();
      
      // 3. **TRIGGER:** Call .next() on the trigger subject 
      //    to re-initialize the table with the new data source.
      // this.dtTrigger.next(null);
    });
  } else {
    // If the table hasn't been rendered yet, just trigger the first render
    this.dtTrigger.next(null);
  }
}

  onBack() {
    console.log("back dvr page");
    this.router.navigate(['/dvrentry'])
  }

  ngOnDestroy(): void {
    // Essential to prevent memory leaks with RxJS Subject
    this.dtTrigger.unsubscribe();
}

  clearForm() {
    // this.form.reset();
  }
  isFieldValid(field: string) {
    // console.log("in field", field)
    return !this.contactForm.get(field).valid && this.contactForm.get(field).touched;
  }
  isFormValid(): boolean {
    // if (!this.contactForm.valid) return false;

    if (this.cont_id || this.mySelect) {
      return this.contactForm.valid;
    }
    return false;
  }
  displayFieldCss(field: string) {
    return {
      'has-error': this.isFieldValid(field),
      'has-feedback': this.isFieldValid(field)
    };

  }
  openPopup() {
    this.displayStyle = "block";
  }

  closePopup() {
    this.displayStyle = "none";
    if (this.backtodvr_flag == true) {
      //  alert("in else ");
      this.router.navigate(['/dvrentry'])
    } else {
      if (this.checkfirstnm_flag == true) {
        window.location.reload();
      }

    }
  }

  ValidateEmail(mail) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail)) {
      return (true)
    }
    this.openPopup();
    this.status_msg = "Warning";
    this.error_msg = "You have entered an invalid email address!";
    // alert("You have entered an invalid email address!")
    return (false)
  }


  // numberOnly(event): boolean {
  //   const charCode = (event.which) ? event.which : event.keyCode;
  //   if (charCode > 31 && (charCode < 48 || charCode > 57)) {
  //     return false;
  //   }
  //   return true;
  // }

//   this.contactForm = this.fb.group({
//   mobile_number: [
//     '',
//     [
//       Validators.required,
//       Validators.pattern(/^[6-9]\d{9}$/) // Indian mobile numbers
//     ]
//   ]
// });

  numberOnly(event: any): boolean {
    const charCode = event.which ? event.which : event.keyCode;
    if (charCode < 48 || charCode > 57) {
      event.preventDefault();
      return false;
    }
    return true;
  }

  getMobileError(field: string) {
    const control = this.contactForm.get(field);

    if (control.hasError('required')) {
      return 'Mobile number is required';
    }

    if (control.hasError('pattern')) {
      return 'Enter a valid 10-digit mobile number';
    }

    // The library sets 'validatePhoneNumber' to false if the number is invalid
    if (control.hasError('validatePhoneNumber')) {
      return 'Enter a valid mobile number for the selected country';
    }

    return '';
  }

  // Inside your component class

// ✅ NEW FUNCTION FOR CLIENT-SIDE FILTERING
filterByCustomerName(): void {
    if (this.dtElement && this.dtElement.dtInstance) {
        this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
            console.log(this.role);
            const filterValue = this.selectedCustomerFilter; 
            const customerNameColumnIndex = this.role === 'admin' ? 1 : 0; // Index 1 is 'Customer Name' based on your template
            
            // Use DataTables API to search the specific column
            dtInstance
                .column(customerNameColumnIndex) 
                .search(filterValue) 
                .draw();
                
            console.log(`Table filtered by Customer Name: ${filterValue}`);
        });
    }
}

// ❌ MODIFIED modo() - REMOVE ALL DATATABLES/API LOGIC
modo(value: any) {
    // Keep only the logic related to the form/flags (e.g., cont_name, contnav_flag)
    
    // Check if the value is being used for other purposes (like form setup)
    if (value && value.customer_id != undefined) {
      console.log("Customer selected for form context.");
    } else {
      console.log("All customers selected for form context.");
    }

    this.mySelect = value;
    console.log(this.mySelect);
    
    // Do NOT call API, destroy table, or call dtTrigger.next() here.
    // The table data is now handled by loadData() once.
}

// modo(value: any) {
//     var id;
//     // Determine the customer ID
//     if (value && value.customer_id != undefined) {
//         id = parseInt(value.customer_id);
//     } else {
//         id = 0; // Assuming '0' is the value for 'All'
//     }

//     // 1. Call the API to get the new, filtered data
//     this.commonservice.getAllData(this.commonservice.projectpath + "/getcustcontactdetails?customer_id=" + id + "&passid=number").subscribe(response => {
//         if (response.status == 'tokenfalse') {
//             this.router.navigate(['/login']);
//         } else {
//             // 2. Assign the new data
//             if (response.data[0].getdvrDataStatus == '1') {
//                 this.contactList = [];
//             } else {
//                 this.contactList = response.data[0].conrtactData;
//             }
            
//             // 3. 🔥 CALL THE ROBUST RERENDER METHOD
//             this.rerender(); // This handles the destroy and re-trigger
//         }
//     });
    
//     // ❌ REMOVE THE DESTROY CALLS OUTSIDE THE SUBSCRIBE
//     // ❌ REMOVE THE dtTrigger.next(this.dtOptions) INSIDE THE SUBSCRIBE
// }


  getContactName(first_name: any, last_name: any) {
    console.log("in contact details", first_name, last_name);
    localStorage.setItem('contactlastinsert', first_name + ' ' + last_name);
    //this.router.navigate(['/dvrentry']);
  }

  parsePhoneNumberAuto(phone: string) {
    if (!phone) return null;

    // 👉 Default fallback country (India)
    let parsed = parsePhoneNumberFromString(phone, 'IN');

    if (!parsed) {
      return {
        number: phone,
        internationalNumber: '',
        nationalNumber: phone,
        e164Number: phone,
        countryCode: 'IN',
        dialCode: '+91'
      };
    }

    return {
      number: parsed.nationalNumber,
      internationalNumber: parsed.formatInternational(),
      nationalNumber: parsed.nationalNumber,
      e164Number: parsed.number, // always E.164
      countryCode: parsed.country, // 🔥 auto-detected
      dialCode: '+' + parsed.countryCallingCode
    };
  }
}

