<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style>
        #arminta-logo {

    display: block; /* Initially visible */
}

        @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap');
   :root {
  --background-color1: #fafaff;
  --background-color2: #ffffff;
  --background-color3: #ededed;
  --background-color4: #cad7fda4;
  --primary-color: #4b49ac;
  --secondary-color: #0c007d;
  --Border-color: #3f0097;
  --one-use-color: #3f0097;
  --two-use-color: #5500cb;
}
  * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Roboto', sans-serif;
        }
   body {
    background-color: #D9D9D9;
    font-size: 1.0rem; /* Decrease the base font size */
    font-family: 'Roboto', sans-serif;
    height: 100vh;
    display: flex;
    flex-direction: column;
}


.header {
    height: 60px;
    width: 100%;
    display: flex;
    align-items: center;
    border-bottom: 1px solid white;
    font-size: 1.0rem;
    background-color: #ACC7D2;
    display: flex;
    justify-content: space-between;
    align-items: center;


}

.search--notification--profile {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: calc(100% - 100px);
    padding: 0 40px;
    margin-left: -10px;
}
.sidebar-link img {
    filter: brightness(0) invert(1);
}

.search {
    background-color: #F1F4F8;
    border-radius: 50px;
    width: 400px;
    padding: 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-left:230px;


}
.search-container {
    display: flex;
    align-items: center;
    border: 1px solid black;
    border-radius: 5px;
    padding: 0 5px;
}
.search input {
    background-color: transparent;
    outline: none;
    border: none;
    text-indent: 15px;
    width: 85%;
}
.search button {
    outline: none;
    border: none;
    border-radius: 50%;
    background-color: #fff;
    padding: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.main {
    position: relative;
    width: 100%;
    height: calc(100vh - 60px);
    overflow-y: auto;
    overflow-x: hidden;
}
.search button i {
    font-size: 1.1rem;
    color: #5073FB;

}

/* Sidebar Styling */
.sidebar {
    position: fixed;
    left: 0;
    height: 100vh;
    width: 263.5px; /* Expanded width */
    background-color: #054560;
    padding: 30px;
    transition: width 0.3s ease-in-out; /* Smooth transition for width change */
    overflow: hidden;
    z-index:1000;
    transition: all 0.5s ease;}

#sidebar.collapsed {
    width: 0; /* Collapsed state */
}

.sidebar.active {
    width: 80px; /* Collapsed width */
}

.sidebar--items {
    list-style: none;
    padding: 0;
}

.sidebar--item {
    display: inline-block;
    margin-left: 15px;
}

.sidebar.active .sidebar--item {
    display: none; /* Hide labels when sidebar is collapsed */
}
.icon {
    display: inline-block;
    width: 30px;
    margin-left: -8px; /* Adjust as needed for better positioning */
    transition: margin-left 0.3s ease; /
}
.sidebar-link {
    text-decoration: none;
    color: white;
    display: flex;
    align-items: center;
    padding: 10px;
    width: 220px; /* Default width */
    transition: width 0.3s ease, transform 0.3s ease, background 0.3s ease;
    position: relative;
}

.sidebar-link:hover {
    width: 280px; /* Expanded width */
    background: #009FC1;
    transform: translateX(-20px); /* Move left by 20px */
    transition: width 0.3s ease, transform 0.3s ease, background 0.3s ease;
}



/* Toggle Menu Icon */
.fa-bars, .fa-ellipsis-vertical {
    cursor: pointer;
    font-size: 30px;
    color: red;
    margin-left:100px;
}

li {
    list-style: none;
}
a {
    text-decoration: none;
}
li a span{

margin-left:-7px;

}

.sidebar--items a,
.sidebar--bottom-items a {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    font-size: 1.0rem;
    color: white;
    padding: 10px;
    border-radius: 10px;

}
.sidebar--items a:hover,
.sidebar--bottom-items a:hover {
    color: #054560;
    background: #ACC7D2;


}
.sidebar--items a.active {
  color: #054560; /* Match hover color for active link */
    font-weight: bold; /* Optional: Bold font for active link */
    background: #ACC7D2;
}


.main::-webkit-scrollbar, .sidebar::-webkit-scrollbar {
    width: 10px;
}

.main::-webkit-scrollbar-track, .sidebar::-webkit-scrollbar-track {
    background: #f1f1f1;
}

.main::-webkit-scrollbar-thumb, .sidebar::-webkit-scrollbar-thumb {
    background: #888;
}

.main::-webkit-scrollbar-thumb:hover, .sidebar::-webkit-scrollbar-thumb:hover {
    background: #555;
}

#clientDetailsContainer{
    body {
            font-family: Arial, sans-serif;
        }
        .container {
            width: 45rem;
            margin: auto;
            padding: 20px;
            border-radius: 10px;

        }
        .two-col {
            display: flex;
            white-space: nowrap;

        }
        .three-col .col1,
        .three-col .col2 {
            flex: 0 0 22%;
        }
        .two-col .form-group {
            margin-bottom: 15px;
        }
        .two-col input,
        .two-col select {
            width: calc(100% - 50px);
            padding: 10px;
            border-radius: 10px;
            border: 1px solid #ccc;
        }
        label.required::after {
            content: "*";
            color: red;
            margin-left: 5px;
        }
        ul {
            list-style-type: none;
            padding: 0;
            margin-bottom: 20px;
            margin-left: 300px;
        }
        li {
            float:left;
            margin-bottom: 20px;
            margin-left: -10px;
        }
        li a {
            display: block;
            color: black;
            text-align: center;
            padding: 1px;
            text-decoration: underline;
            margin-top: 20px;
            margin-left: 60px;
        }
        a:hover {
            color:red;
        }
        .container1 {
            margin-left: 100px;
            width: 900px;
        }
.nav a.active {
    color: red; /* Change the color to your desired color */
    font-weight: bold; /* Make the font bold, if desired */
    /* Add any other styling for the active link */
}
.icon img:hover {
   background:#009FC1
}
.fa-ellipsis-vertical {
    margin-left:-100px;
    color:red;
}
}

    </style>
    <title> Admin Dashboard</title>
</head>
<body>
 <div class="wrapper" >

    <section class="header">
            {% load static %}


<li>
    <a id="menu-icon" class="fa-solid fa-bars" onclick="toggleSidebar()"
       style="cursor: pointer; font-size: 25px; color: black; margin-left:40px; margin-top: -100px;"></a>
      </li>
    <li>
    <img id="arminta-logo" src="{% static 'images/Arminta_Logo_1.svg' %}" alt="Logo"
         style=" margin-left:20px; margin-bottom:15px;">

</li>
        <div class="search--notification--profile">

             <div class="search">
                <input type="text" placeholder="Search">
                <button><i class="ri-search-2-line" style="color:#054560"></i></button>

                  </div>

            <h3 style="margin-left:0px;" >Skyonn Technologies</h3>
            </div>
                  <div class="bell" style="margin-right: 30px; color:#054560">
                  <i class="fa-solid fa-bell"></i>
                  </div>
<div class="profile" style="margin-right: 30px;" >
  <div class="profile-content" style="display: flex;align-items: center;">
    <div class="profile-picture" style="position: relative; width: 60px; height: 60px;">
        {% if picture %}
            <img id="profileImage" src="{{picture.url}}" alt="Profile Picture" class="profile-img" style="width: 50px;
                height: 50px;border-radius: 50%;object-fit: cover;margin-top: 5px;" data-admin-id="{{ admin_id }}">
        {% endif %}
    </div>
  </div>
</div>

<h3 style="margin-right: 40px; color:#054560">{{first_name}}</h3>
<a href="{% url 'admin_logout'  %}" style="margin-right: 50px; color: red; font-size: larger; text-decoration: underline;">LogOut</a>
    </section>
    <section class="main" >
        <div class="sidebar" id="sidebar" >
           <ul class="sidebar--items">

                {% load static %}

              <li>
                     <a href="#" class="sidebar-link" onclick="showClientDetails(); activateSidebarLink(this)">
                            <span class="icon"><img src="{% static 'images/Client Details (3).svg' %}"  ></span>
                            <span class="sidebar--item" style="margin-left:20px">Client Details</span>
                        </a>
                    </li>

                    <li>
                        <a href="#" class="sidebar-link" onclick="activateLink(this); loadPage('/skyonnadmin/Internal_team_details/','{{admin_id}}'); hideClientDetails(); activateSidebarLink(this)">
                            <span class="icon"><img src="{% static 'images/Internal team Details (1).svg' %}" ></span>
                            <span class="sidebar--item" style="margin-left:20px">Internal Team Details</span>
                        </a>
                    </li>

                <li>
                    <a href="#" class="sidebar-link" onclick="loadPage('//');  hideClientDetails(); activateSidebarLink(this)">
                        <span class="icon"><img src="{% static 'images/Messages.svg' %}"></span>
                        <span class="sidebar--item" style="margin-left:20px"> Messages</span>
                    </a>
                </li>
                <li>
                    <a href="#" class="sidebar-link" onclick="loadPage('//');  hideClientDetails(); activateSidebarLink(this)">
                        <span class="icon"><img src="{% static 'images/Pending process.svg' %}"></span>
                        <span class="sidebar--item" style="margin-left:20px"> Pending Process</span>
                    </a>
                </li>
                <li>
                     <a href="#" class="sidebar-link" onclick="loadPage('//');  hideClientDetails(); activateSidebarLink(this)">
                        <span class="icon"><img src="{% static 'images/submited Resumes.svg' %}"></span>
                         <span class="sidebar--item" style="margin-left:20px"> Submitted Resumes</span>
                    </a>
                </li>
                <li>
                   <a href="#" class="sidebar-link" onclick="loadPage('//');  hideClientDetails(); activateSidebarLink(this)">
                        <span class="icon"><img src="{% static 'images/Add A New SPOC.svg' %}"></span>
                       <span class="sidebar--item" style="margin-left:20px"> Add a New SPOC</span>
                    </a>
                </li>
                <li>
                     <a href="#" class="sidebar-link" onclick="loadPage('/new_job_postings/');  hideClientDetails(); activateSidebarLink(this)">
                        <span class="icon"><img src="{% static 'images/Activity Report.svg' %}"></span>
                         <span class="sidebar--item" style="margin-left:20px"> Activity Report</span>
                    </a>
                </li>
            </ul>
        </div>
        <div id="clientDetailsContainer" style="display: none;">

            <ul>
                  <h4 style="margin-left:280px; margin-top:10px; text-decoration:underline; color:#054560;">Client Details</h4>
                <div class="nav" style="margin-left:-60px;" >
                     <li><a href="#" class="btn" onclick="activateLink(this); loadPage('/skyonnadmin/add_client/','{{admin_id}}')">Add New Client</a></li>
                    <li><a href="#" class="btn" onclick="activateLink(this); loadPage('/skyonnadmin/add_subclient/','{{admin_id}}')">Add Sub Clients/Locations</a></li>

                     <li><a href="#" class="btn" onclick="activateLink(this); loadPage('/skyonnadmin/add_new_contact/','{{admin_id}}')">Add New Contact</a></li>
                     <li><a href="#" class="btn" onclick="activateLink(this); loadPage('/skyonnadmin/existing_client/','{{admin_id}}')">Existing Client</a></li>

                </div>
            </ul>
        </div>
        <div id="dynamicContentContainer">

        </div>

      <div id="AdminDetailsModal" class="modal" style="position: fixed;top: 60px;right: 0;width: 30%;height: 80%;border: 1px black;display: none;background-color: white; border:2px solid black; box-shadow: -2px 0px 5px rgba(0,0,0,0.2);z-index:1000;">
  <div class="modal-content" style="padding: 40px;height: 100%;">

       <a href="#" onclick="closeModal()" style="font-size: 24px; margin-left: 360px;  color:red;">
        <i class="fa fa-times"></i>
      </a>

      <div class="profile-picture-container" style="text-align: center; margin-bottom: 40px;">
             <img id="profile_picture" src="{{picture.url}}" alt="Profile Picture" style="width: 150px; margin-top:-50px; height: 150px; border-radius: 50%; object-fit: cover; border: 2px solid #ddd;">
      </div>
     <div class="data" style="margin-left:1px" >
     <p><strong style="color:#054560">FirstName:</strong> <span style="margin-left:50px;" id="first_name"></span></p><br>
     <p><strong style="color:#054560">LastName:</strong> <span style="margin-left:50px;" id="last_name"></span></p><br>
     <p><strong style="color:#054560">PhoneNo1:</strong> <span style="margin-left:50px;" id="phone"></span></p><br>
     <p><strong style="color:#054560">PhoneNo2:</strong> <span  style="margin-left:50px;" id="phone_number_2"></span></p><br>
     <p><strong style="color:#054560">Company Email:</strong> <span style="margin-left:13px;" id="company_email"></span></p><br>
     <p><strong style="color:#054560">Personal Email:</strong> <span style="margin-left:15px;" id="personal_email"></span></p><br>
     <p><strong style="color:#054560">Address:</strong> <span  style="margin-left:65px;" id="address"></span></p><br>
     <p><strong style="color:#054560">Work Location:</strong> <span style="margin-left:22px;" id="work_location"></span></p><br>
     </div>

</div>


      <script>


  function changeGST() {
    var gstInput = document.getElementById("GSTNo");
    var button = document.getElementById("changeButton");

    // If input is disabled, enable it to allow editing
    if (gstInput.disabled) {
      gstInput.disabled = false; // Enable the input
      gstInput.focus(); // Set focus on the input field
      button.textContent = "Save"; // Change the button text to "Save"
    } else {
      // If input is enabled, disable it and save the new value
      gstInput.disabled = true;
      button.textContent = "Change"; // Change the button text back to "Change"

      // Handle saving logic here if needed (e.g., sending the updated value to the server)
      var updatedGST = gstInput.value;
      console.log("Updated GST No:", updatedGST); // You can replace this with actual saving logic
    }
  }


function searchEmployee() {
    var input, filter, table, tr, i, txtValue;
    input = document.getElementById("searchInput");
    filter = input.value.toUpperCase();
    table = document.getElementById("employeeTableBody"); // Use the table body
    tr = table.getElementsByTagName("tr");

    for (i = 0; i < tr.length; i++) {
        var found = false;

        // Check relevant columns (FirstName, LastName, Designation, Department, etc.)
        var tds = tr[i].getElementsByTagName("td");

        // Check all relevant columns (adjust indexes as necessary)
        for (var j = 0; j < tds.length; j++) {
            if (tds[j]) {
                txtValue = tds[j].textContent || tds[j].innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    found = true;
                    break; // No need to check further columns if a match is found
                }
            }
        }

        // Show or hide the row based on search results
        tr[i].style.display = found ? "" : "none";
    }
}


 function closeModal() {
    const modal = document.getElementById('AdminDetailsModal');
    if (modal) {
        modal.style.display = 'none';
        // Clear all modal data fields
        document.getElementById('first_name').innerText = '';
        document.getElementById('last_name').innerText = '';
        document.getElementById('phone').innerText = '';
        document.getElementById('phone_number_2').innerText = '';
        document.getElementById('company_email').innerText = '';
        document.getElementById('personal_email').innerText = '';
        document.getElementById('address').innerText = '';
        document.getElementById('work_location').innerText = '';
    }
}

// Add event listener after DOM content is fully loaded
document.addEventListener('DOMContentLoaded', function() {
    // Handle profile image click to load admin details
    document.addEventListener('click', function(event) {
        if (event.target && event.target.id === 'profileImage') {
            const adminId = event.target.dataset.adminId;
            const popup = document.getElementById('AdminDetailsModal');

            // Toggle popup visibility
            if (popup.style.display === 'block') {
                closeModal();
                return;
            }

            // Fetch admin details via AJAX
            let xhr = new XMLHttpRequest();
            xhr.open('GET', `/skyonnadmin/get_admin_details/?admin_id=${adminId}`, true);
            xhr.onload = function() {
                if (xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    const adminDetails = response.admin_data;
                    showAdminDetails(adminDetails);
                } else {
                    console.error('Request failed. Status: ' + xhr.status);
                }
            };
            xhr.send();
        }
    });

    // Close modal when clicking outside of it or on the close button
    document.addEventListener('click', function(event) {
        const modal = document.getElementById('AdminDetailsModal');
        if (modal && modal.style.display === 'block' && !modal.contains(event.target) && event.target.id !== 'profileImage') {
            closeModal();
        }
    }, true);
});

function showAdminDetails(adminDetails) {
    const popup = document.getElementById('AdminDetailsModal');

    if (popup) {
        document.getElementById('first_name').innerText = adminDetails.first_name;
        document.getElementById('last_name').innerText = adminDetails.last_name;
        document.getElementById('phone').innerText = adminDetails.phone;
        document.getElementById('phone_number_2').innerText = adminDetails.phone_number_2;
        document.getElementById('company_email').innerText = adminDetails.company_email;
        document.getElementById('personal_email').innerText = adminDetails.personal_email;
        document.getElementById('address').innerText = adminDetails.address;
        document.getElementById('work_location').innerText = adminDetails.work_location;

        // Display the popup
        popup.style.display = 'block';
    }
}



function toggleSidebar() {
    var sidebar = document.getElementById('sidebar');
    var menuIcon = document.getElementById('menu-icon');

    if (sidebar && menuIcon) {
        // Toggle the sidebar's active state on click
        sidebar.classList.toggle('active');

        // Toggle between menu bar and cross icons based on sidebar active state
        if (sidebar.classList.contains('active')) {
            // When the sidebar is active (open), show the cross icon
            menuIcon.classList.remove('fa-bars');
            menuIcon.classList.add('fa-times'); // Show cross icon

        } else {
            menuIcon.classList.remove('fa-times');
            menuIcon.classList.add('fa-bars');

        }
    } else {
        console.error("Sidebar or Menu Icon not found");
    }
}

// No automatic mouse enter or leave events for sidebar; menu icon is handled only on click
document.addEventListener('DOMContentLoaded', () => {
    // Sidebar will only be controlled via the menu icon click
});



var sidebarTimeout;
function handleSidebarMouseEvents() {
    var sidebar = document.getElementById('sidebar');
    var body = document.querySelector('body');

    if (sidebar && body) {
        // When mouse enters the sidebar, close it
        sidebar.addEventListener('mouseenter', () => {
            clearTimeout(sidebarTimeout);
            if (sidebar.classList.contains('active')) {
                sidebar.classList.remove('active');
            }
        });
        sidebar.addEventListener('mouseleave', () => {
            clearTimeout(sidebarTimeout);
            sidebarTimeout = setTimeout(() => {
                if (!sidebar.classList.contains('active')) {
                    sidebar.classList.add('active');
                }
            }, 300);
        });
    }
}

// Initialize event listeners on DOM load
document.addEventListener('DOMContentLoaded', () => {
    handleSidebarMouseEvents(); // Set up the mouse enter/leave events
});




<!--   document.addEventListener('click', function (event) {-->
<!--     if(event.target && event.target.id === 'Existing_employeeLink') {-->
<!--       const form = document.getElementById('Existing_employeeLink');-->

<!--       fetch('/skyonnadmin/existing_employee/')-->
<!--            .then(response => response.json())-->
<!--            .then(data => {-->
<!--                const employees = data.employees;-->
<!--                console.log(employees);-->
<!--                const employeeTableBody = document.getElementById('employeeTableBody');-->
<!--                employeeTableBody.innerHTML = ''; // Clear previous data-->

<!--                if(employees.length > 0) {-->
<!--                   employees.forEach(emp => {-->
<!--                      const row = `-->
<!--                         <tr>-->
<!--                                <td>${emp.FirstName}</td>-->
<!--                                <td>${emp.LastName}</td>-->
<!--                                <td>${emp.Designation}</td>-->
<!--                                <td>${emp.Department}</td>-->

<!--                                <td>${emp.PhoneNo1}</td>-->
<!--                                <td>${emp.LandNumber}</td>-->
<!--                                <td>${emp.Email1}</td>-->
<!--                                <td>${emp.Email2}</td>-->
<!--                                <td>${emp.Level}</td>-->
<!--                         </tr>`;-->

<!--                      employeeTableBody.insertAdjacentHTML('beforeend', row);-->
<!--                   });-->
<!--                }-->
<!--            })-->
<!--            .catch(error => {-->
<!--                console.error('Error fetching employee data:', error);-->
<!--            })-->
<!--     }-->
<!--   });-->


document.addEventListener('click', function (event) {
   if(event.target && event.target.id === 'Existing_employeeLink') {
       const form = document.getElementById('Existing_employeeLink');

       fetch('/skyonnadmin/existing_employee/')
            .then(response => response.json())
            .then(data => {
                const employees = data.employees;
                console.log(employees);
                const employeeTableBody = document.getElementById('employeeTableBody');
                employeeTableBody.innerHTML = ''; // Clear previous data

                if(employees.length > 0) {
                   employees.forEach(emp => {
                      const row = `
                         <tr>
                                 <td contentEditable='false' data-key="FirstName" style="color: blue"><a href="#" class="FirstName-link" data-FirstName="${emp.FirstName}">${emp.FirstName}</td>
                                <td contentEditable='false' data-key="LastName" style="color: blue"><a href="#" class="LastName-link" data-LastName="${emp.LastName}">${emp.LastName}</td>
                                <td contentEditable='false' data-key="Designation">${emp.Designation}</td>
                                <td contentEditable='false'  data-key="Department">${emp.Department}</td>
                                <td contentEditable='false' data-key="PhoneNo1">${emp.PhoneNo1}</td>
                                <td contentEditable='false' data-key="LandNumber">${emp.LandNumber}</td>
                                <td contentEditable='false' class='non-editable' data-email="${emp.Email1}">${emp.Email1}</td>
                                <td contentEditable='false' data-key="Email2">${emp.Email2}</td>
                                <td contentEditable='false' data-key="Level">${emp.Level}</td>
                                <td style="width: 150px;">
                                    <button class="edit-internalTeam" style="font-size: 20px; margin-left; -50px;">Edit</button>
                                    <button class="delete-internalTeam" style="font-size: 20px;">Delete</button>
                                    <button class="print-internalTeam" style="font-size: 20px;">Print</button>
                                </td>
                         </tr>`;

                      employeeTableBody.insertAdjacentHTML('beforeend', row);

                   });
                   AddEditDelete();
                }
            })
            .catch(error => {
                console.error('Error fetching employee data:', error);
            })
   }


function enforceMaxLength(event) {
   const cell = event.target
   const maxLengths = {'PhoneNo1':10 , 'LandNumber':20 , 'Pincode':6}

   const field = cell.getAttribute('data-key');
   const maxLength = maxLengths[field]
   if(maxLength && cell.textContent.length > maxLength) {
       cell.textContent = cell.textContent.slice(0,maxLength);

        const range = document.createRange();
        const selection = window.getSelection();
        range.setStart(cell.childNodes[0], cell.textContent.length);        //makes cursor stay at end of text when it reaches max length
        range.collapse(true);
        selection.removeAllRanges();
        selection.addRange(range);
   }
}
const employeeTableBody = document.getElementById('employeeTableBody');
if (!employeeTableBody) return;
employeeTableBody.addEventListener('input',enforceMaxLength);
});


document.addEventListener('DOMContentLoaded', function() {          //to show popup for client details
    document.addEventListener('click', function(event) {
        if (event.target && (event.target.matches('.FirstName-link') ||  event.target.matches('.LastName-link'))) {
            event.preventDefault();
            const firstName = event.target.getAttribute('data-FirstName') || '';
            console.log(firstName);
            const lastName = event.target.getAttribute('data-LastName') || '';
            console.log(lastName);
            const row = event.target.closest('tr');
            const email = row.querySelector('[data-email]').getAttribute('data-email') || '';

            const params = new URLSearchParams();
            if (firstName) params.append('firstName',firstName);
            if (lastName) params.append('lastName',lastName);
            if (email) params.append('Email1',email);

            let xhr = new XMLHttpRequest();
            xhr.open('GET', `/skyonnadmin/get_employee/?${params.toString()}`, true);
            xhr.onload = function() {
                if (xhr.status === 200) {
                    const details = JSON.parse(xhr.responseText);
                    console.log('Details received:', details);
                    showPopup(details);
                } else {
                    console.error('Request failed. Status:', xhr.status);
                }
            };
            xhr.send();
        }
    });

    document.addEventListener('click', function(event) {
       const popup = document.getElementById('detailsModal');
       if (popup && popup.style.display === 'block' && !popup.contains(event.target) && !event.target.matches('.FirstName-link, .LastName-link')) {
           popup.style.display = 'none';
       }
    }, true);
})

   function showPopup(data) {
        const popup = document.getElementById('detailsModal');

        if (popup) {
            // Fill in the popup with data
            document.getElementById('FirstName_1').textContent =  (data.FirstName || '');
            document.getElementById('LastName_1').textContent =  (data.LastName || '');
            document.getElementById('Designation_1').textContent =  (data.Designation || '');
            document.getElementById('Department_1').textContent =  (data.Department || '');
            document.getElementById('Address_1_1').textContent =  (data.Address_1 || '');
            document.getElementById('Address_2_1').textContent =  (data.Address_2 || '');
            document.getElementById('City_1').textContent =  (data.City || '');
            document.getElementById('State_1').textContent =  (data.State || '');
            document.getElementById('Pincode_1').textContent =  (data.Pincode || '');
            document.getElementById('Country_1').textContent =  (data.Country || '');
            document.getElementById('PhoneNo1_1').textContent =  (data.PhoneNo1 || '');
            document.getElementById('LandNumber_1').textContent =  (data.LandNumber || '');
            document.getElementById('Email1_1').textContent =  (data.Email1 || '');
            document.getElementById('Email2_1').textContent =  (data.Email2 || '');
            document.getElementById('Level_1').textContent =  (data.Level || '');

            // Attach the close button event listener each time the popup is shown
            document.getElementById('closePopup').addEventListener('click', function() {
                popup.style.display = 'none';
            });


            // Display the popup
            popup.style.display = 'block';
        } else {
            console.error('Popup element not found');
        }
   }


function AddEditDelete() {
   document.querySelectorAll('.edit-internalTeam').forEach(button => {
       button.addEventListener('click', editInternalTeam);
   });
   document.querySelectorAll('.delete-internalTeam').forEach(button => {
       button.addEventListener('click', deleteInternalTeam);
   });
   document.querySelectorAll('.print-internalTeam').forEach(button => {
       button.addEventListener('click', printInternalTeam);
   });
}

function editInternalTeam(event) {
   event.preventDefault();
   const button = event.target;
   let row = button.closest('tr');
   console.log('editing Internal Team');

   if (button.textContent === 'Edit') {
     Array.from(row.cells).forEach((cell, index) => {
        if (index < row.cells.length - 1) {                               // Exclude the last cell (actions cell)
            const isEditable = cell.getAttribute('data-editable') !== 'true' && !cell.classList.contains('non-editable');
            console.log(isEditable);

            if (isEditable) {
                cell.contentEditable = true;
                cell.style.backgroundColor = '';
                cell.removeEventListener('blur', validateInternalTeam);
                cell.addEventListener('blur', validateInternalTeam);
            } else {
                cell.contentEditable = false;
                cell.style.backgroundColor = '#e0e0e0';                // Set background color for non-editable cells
            }
        }
     });

     button.setAttribute('data-original-firstname', row.cells[0].textContent.trim());
     button.setAttribute('data-original-lastname', row.cells[1].textContent.trim());

     button.textContent = 'Save';
   }


   else if (button.textContent === 'Save') {

        let isValid = true;
         Array.from(row.cells).forEach((cell, index) => {
            if (index < row.cells.length - 1) {
               const isEditable = cell.getAttribute('data-editable') !== 'true' && !cell.classList.contains('non-editable');
               if(isEditable) {
                  if (!validateInternalTeam({ target: cell })) {
                    isValid = false;
                  }
               }
            }
        });

         if (!isValid) {
            alert("Validation failed. Please fill out the required fields.");
            return; // If validation fails, do not proceed to save
         }

        const updatedData = {
            FirstName: row.cells[0].textContent,
            LastName: row.cells[1].textContent,
            Designation: row.cells[2].textContent,
            Department: row.cells[3].textContent,
            PhoneNo1: row.cells[4].textContent,
            LandNumber: row.cells[5].textContent,
            Email1: row.cells[6].textContent,
            Email2: row.cells[7].textContent,
            Level: row.cells[8].textContent
        };

        Array.from(row.cells).forEach((cell, index) => {
            cell.contentEditable = false;
            cell.style.backgroundColor = '';
        });
        button.textContent = 'Edit';

        fetch(`/skyonnadmin/edit_internalTeam/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{csrf_token}}'
            },
            body: JSON.stringify(updatedData)
        })
            .then(response => {
                if (response.ok) {
                    console.log('Data saved successfully.');
                    alert('Data saved successfully!');

                    const originalFirstName = button.getAttribute('data-original-firstname');
                    console.log(originalFirstName);
                    const originalLastName = button.getAttribute('data-original-lastname');
                    console.log(originalLastName);

                    if (updatedData.FirstName !== originalFirstName || updatedData.LastName !== originalLastName) {
                         fetch('/skyonnadmin/existing_employee/')
            .then(response => response.json())
            .then(data => {
                const employees = data.employees;
                console.log(employees);
                const employeeTableBody = document.getElementById('employeeTableBody');
                employeeTableBody.innerHTML = ''; // Clear previous data

                if(employees.length > 0) {
                   employees.forEach(emp => {
                      const row = `
                         <tr>
                                <td contentEditable='false' data-key="FirstName" style="color: blue"><a href="#" class="FirstName-link" data-FirstName="${emp.FirstName}">${emp.FirstName}</td>
                                <td contentEditable='false' data-key="LastName" style="color: blue"><a href="#" class="LastName-link" data-LastName="${emp.LastName}">${emp.LastName}</td>
                                <td contentEditable='false' data-key="Designation">${emp.Designation}</td>
                                <td contentEditable='false' data-key="Department">${emp.Department}</td>

                                <td contentEditable='false' data-key="PhoneNo1">${emp.PhoneNo1}</td>
                                <td contentEditable='false' data-key="LandNumber">${emp.LandNumber}</td>
                                <td contentEditable='false' class='non-editable' data-email="${emp.Email1}">${emp.Email1}</td>
                                <td contentEditable='false' data-key="Email2">${emp.Email2}</td>
                                <td contentEditable='false' data-key="Level">${emp.Level}</td>
                                <td style="width: 150px;">
                                    <button class="edit-internalTeam" style="font-size: 20px; margin-left; -50px;">Edit</button>
                                    <button class="delete-internalTeam" style="font-size: 20px;">Delete</button>
                                    <button class="print-internalTeam" style="font-size: 20px;">Print</button>
                                </td>
                         </tr>`;

                      employeeTableBody.insertAdjacentHTML('beforeend', row);

                   });
                   AddEditDelete();
                }
            })
            .catch(error => {
                console.error('Error fetching employee data:', error);
            })

                    }

                } else {
                    console.error('Failed to save data.');
                    alert('Failed to save data.');
                }
            })
            .catch(error => {
                console.error('Error saving employee data:', error);
            });
   }
}

function validateInternalTeam(event) {
    const cell = event.target;
    const row = cell.closest('tr');
    const field = cell.getAttribute('data-key');
    const emailCell = row.querySelector('[data-email]')
    const email1 = emailCell.getAttribute('data-email');
    let value = cell.textContent.trim();

    let alertShown = cell.getAttribute('data-alert-shown') === 'true';
    let isValid = true;
    let hasEmailError = false;
    let hasPhoneError = false;
    const pincodePattern = /^[1-9][0-9]{5}$/;

    value = cell.textContent.trim(); // Get updated value when the user finishes editing

    if ((field === 'FirstName' || field === 'LastName' || field === 'Designation' || field === 'Department' || field === 'Level')  && value === '') {
        if (!alertShown) {
            alert(`${field} field cannot be empty`);
            cell.setAttribute('data-alert-shown', 'true');
        }
        cell.style.backgroundColor = "#FFCCCC";
        cell.focus();
        isValid = false;
    } else {
        cell.setAttribute('data-alert-shown', 'false');
        cell.style.backgroundColor = ""; // Reset background color
    }

    // Email Validation
    if (field === 'Email2' && value !=='') {
        const emailPattern = /^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/;
        const emailPattern2 = /^[^\s@]{1,64}@([^\s@_]+\.)+[a-zA-Z]{2,}$/;

        if (!value.match(emailPattern) || value.includes('..') || !value.match(emailPattern2)) {
            if (!alertShown) {
                alert('Invalid Email Address format');
                cell.setAttribute('data-alert-shown', 'true');
            }
            cell.style.backgroundColor = "#FFCCCC"; // Highlight error
            isValid = false;
            cell.focus(); // Keep focus on the email field
        } else {
            const emailExists = checkEmailExists(value,email1);
            console.log('emailExists:',emailExists);
            if (emailExists) {
                if (!alertShown) {
                    alert('Email already exists. Please use a different email.');
                    cell.setAttribute('data-alert-shown', 'true'); // Prevent multiple alerts
                }
                cell.style.backgroundColor = "#FFCCCC"; // Highlight error
                isValid = false;
                hasEmailError = true;
                cell.focus();
            } else {
                cell.style.backgroundColor = ""; // Reset background color
                hasEmailError = false; // No email error
                cell.setAttribute('data-alert-shown', 'false'); // Reset alert
            }
        }
    }

    if (field === 'PhoneNo1' && value !== '') {
        const phonePattern = /^[6-9]\d{9}$/;
        if (!value.match(phonePattern)) {
            if (!alertShown) {
                alert('Invalid phone number format');
                cell.setAttribute('data-alert-shown', 'true');
            }
            cell.style.backgroundColor = "#FFCCCC";
            isValid = false;
            cell.focus(); // Keep focus on the phone field
        } else {
            const phoneExists = checkPhoneNumberExists(value,email1);
            console.log('phoneExists:',phoneExists);
            if (phoneExists) {
                if (!alertShown) {
                    alert('phone number already exists. Please use a different number.');
                    cell.setAttribute('data-alert-shown', 'true'); // Prevent multiple alerts
                }
                cell.style.backgroundColor = "#FFCCCC";
                isValid = false;
                hasPhoneError = true;
                cell.focus();
            } else {
                cell.style.backgroundColor = ""; // Reset background color
                hasPhoneError = false; // No phone error
                console.log('hasPhoneError:',hasPhoneError);
                cell.setAttribute('data-alert-shown', 'false'); // Reset alert
            }
        }
    }

    if (field === 'LandNumber' && value !== '') {
        const phonePattern = /^(\+91[-\s]?)?[0]?\d{2,5}[-\s]?\d{3,4}[-\s]?\d{4}$/;
        if (!value.match(phonePattern)) {
            if (!alertShown) {
                alert('Invalid phone number format');
                cell.setAttribute('data-alert-shown', 'true');
            }
            cell.style.backgroundColor = "#FFCCCC";
            isValid = false;
            cell.focus(); // Keep focus on the phone field
        } else {
            const phoneExists = checkPhoneNumberExists(value,email1);
            console.log('phoneExists:',phoneExists);
            if (phoneExists) {
                if (!alertShown) {
                    alert('Landline number already exists. Please use a different number.');
                    cell.setAttribute('data-alert-shown', 'true'); // Prevent multiple alerts
                }
                cell.style.backgroundColor = "#FFCCCC";
                isValid = false;
                hasPhoneError = true;
                cell.focus();
            } else {
                cell.style.backgroundColor = ""; // Reset background color
                hasPhoneError = false; // No phone error
                console.log('hasPhoneError:',hasPhoneError);
                cell.setAttribute('data-alert-shown', 'false'); // Reset alert
            }
        }
    }
 const phoneCell =row.querySelector('[data-key="PhoneNo1"]');
const landNumberCell =row.querySelector('[data-key="LandNumber"]');
const phoneNo1Value = phoneCell ? phoneCell.textContent.trim() : '';
const landNumberValue = landNumberCell ? landNumberCell.textContent.trim() : '';
const focusField = cell.getAttribute('data-key') === 'PhoneNo1' ? landNumberCell : phoneCell;

if (field === 'PhoneNo1'  || field === 'LandNumber' ) {
  if(phoneNo1Value === '' && landNumberValue === '') {
    if (!alertShown) {
        alert(`Both Phonenumber and Landnumber fields cannot be empty.Please fill atleast one`);
        cell.setAttribute('data-alert-shown', 'true');
        if (focusField) {
          focusField.focus();
        }
    }
    isValid = false;
  }
} else {
    cell.setAttribute('data-alert-shown', 'false');
}

   return isValid;
}

function checkEmailExists(email2,email1) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', `/skyonnadmin/validate_existingEmployee/?Email2=${encodeURIComponent(email2)}&Email1=${encodeURIComponent(email1)}`, false); // Synchronous request with email and contact_id
    xhr.send();

    if (xhr.status === 200) {
        const response = JSON.parse(xhr.responseText);
        return response.email_exists;
    } else {
        console.error('Error checking email.');
        return false;
    }
}

function checkPhoneNumberExists(phoneNumber,email1) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', `/skyonnadmin/validate_existingEmployee/?PhoneNo1=${encodeURIComponent(phoneNumber)}&LandNumber=${encodeURIComponent(phoneNumber)}&Email1=${encodeURIComponent(email1)}`, false); // Synchronous request with phone number and contact_id
    xhr.send();

    if (xhr.status === 200) {
        const response = JSON.parse(xhr.responseText);
        return response.phone_exists; // Return true if phone number exists
    } else {
        console.error('Error checking phone number.');
        return false;
    }
}



function deleteInternalTeam(event) {
    event.preventDefault();
    const button = event.target;
    const row = button.closest('tr'); // Get the row to delete
    const emailCell = row.querySelector('[data-email]');
    const email = emailCell.getAttribute('data-email');
    console.log('Deleting row with Email:', email);

    if (confirm(`Are you sure you want to delete data?`)) {

      return fetch(`/skyonnadmin/delete_internalTeam/?Email1=${encodeURIComponent(email)}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token }}'  // Properly include the CSRF token
        }
      })
      .then(response => {
        if (response.ok) {
            row.remove();
            console.log('Data deleted successfully');
            alert('Data deleted successfully');
        } else {
            console.error('Failed to delete Internal Team details');
        }
      })
      .catch(error => {
        console.error('Network error during data deletion:', error);
      });
    }
}

function printInternalTeam(event) {
    event.preventDefault();
    console.log('Print clicked');
    const row = event.target.closest('tr');

    const emailCell = row.querySelector('[data-email]');
    const email = emailCell.getAttribute('data-email');
    console.log(`Email: ${email}`);

    // Make a POST request to the server for fetching additional details
    fetch(`/skyonnadmin/print_internalTeam/?Email1=${encodeURIComponent(email)}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{csrf_token}}',
        },
    })
    .then(response => {
            if (!response.ok) {
                throw new Error('Failed to fetch employee data');
            }
            return response.json(); // Return the parsed JSON
    })
    .then(data => {
            console.log('Data received from server:', data);

            // Create printable content from received data
            const printContent = `
                <h1>Internal Team Details</h1>
                <p><strong>FirstName:</strong> ${data.FirstName}</p>
                <p><strong>LastName:</strong> ${data.LastName}</p>
                <p><strong>Designation:</strong> ${data.Designation}</p>
                <p><strong>Department:</strong> ${data.Department}</p>
                <p><strong>PhoneNo1:</strong> ${data.PhoneNo1}</p>
                <p><strong>LandNumber:</strong> ${data.LandNumber}</p>
                <p><strong>Email1:</strong> ${data.Email1}</p>
                <p><strong>Email2:</strong> ${data.Email2}</p>
                <p><strong>Level:</strong> ${data.Level}</p>
            `;

            // Open a new window and display the printable content
            const printWindow = window.open('');
            printWindow.document.write(`
                <html>
                    <head>
                        <title>Company: Skyonn Technologies</title>
                        <style>
                            body { font-family: Arial, sans-serif; margin: 0;}
                            h1 { text-align: center; }
                            p { margin: 10px 0; }

                        }
                        </style>
                    </head>
                    <body onload="window.print(); window.close();">
                        ${printContent}
                    </body>
                </html>
            `);
            printWindow.document.close();
        })
        .catch(error => {
            console.error('Error fetching employee data:', error);
        });
}





document.addEventListener('DOMContentLoaded', function () {
  window.UploadExcel=function() {
   console.log('file uploaded');
   const excel_file = document.getElementById('excelFile').files[0];

   if (!excel_file) {
       alert("Please select an Excel file.");
       return;
   }

   const formData = new FormData();
   formData.append('excelFile', excel_file);

    // Initial fetch to get the row count from the server
    fetch("/skyonnadmin/get_row_count/", {
      method: "POST",
      body: formData,
      headers: {
        "X-CSRFToken": '{{ csrf_token }}'
      }
    })
      .then(response => response.json())
      .then(data => {
        if (data.error) {
          console.error("Error fetching row count:", data.error);
          alert("An error occurred while processing the file. Please try again.");
          return;
        }

        const rowCount = data.row_count;

   if (confirm(`This Excel file contains ${rowCount} rows. Do you want to upload it?`)) {
      const formData = new FormData();
      formData.append('excelFile',excel_file);

      fetch("/skyonnadmin/load_excel_data/", {
        method: "POST",
        body: formData,
        headers: {
            "X-CSRFToken": '{{ csrf_token}}'
        }
      })
      .then(response => response.json())
      .then(data => {
        console.log('data:',data);
        if (data.error) {
           console.log(data.error);
                                                 // Display error for specific fields, including missing PhoneNo1 and LandNumber
           if (data.empty_fields) {
                console.log(data.empty_fields);
                const errors = [];
              for (const field in data.empty_fields) {
                  if (field === 'Contact') {
                     errors.push(`Empty data in both PhoneNo1 and LandNumber column`);
                  }
                  if (field !== 'PhoneNo1' && field !== 'LandNumber' && field !== 'Contact') {
                     errors.push(`Empty data in column '${field}' in provided excel sheet`);
                  }
              }
              console.log(errors);
              if (errors.length > 0) {
                 alert(errors);
              }
           }
           return;
        }
        console.log(data.data);
        excelRows = data.data;
        console.log('excelRows:',excelRows);

        let currentRowIndex = 0;

        function processRow(rowData) {
          console.log(`processing row is: ${currentRowIndex}`);

          for (const header in rowData) {
             const field = document.getElementById(header);
             const value = rowData[header];
             if (field) {
               if (header === 'Level') {
                 field.value = `Level ${value}`;
               }
               else {
                 field.value = value;
               }
             }
             else {
               console.warn(`No form field found with ID: ${header}`);
             }
          }
        }



window.saveInternal_team_details = async function() {

    const form = document.getElementById('internal-team');
    const orderedFieldIds = [
        'FirstName', 'LastName', 'Designation', 'Department', 'Address_1', 'City', 'State', 'Pincode', 'Country',
        'PhoneNo1','LandNumber','Email1','Email2','Level'
    ];

    const phoneNumberInput1 = document.getElementById('PhoneNo1');
    const phoneNumberInput2 = document.getElementById('LandNumber');

    if(!phoneNumberInput1.value.trim() && !phoneNumberInput2.value.trim()) {
        alert('please fill atleast one phone number: PhoneNo or Landline');
        return;
    }


  const validateField = (field, pattern = null, errorMsg = '') => {
    const fieldValue = field.value.trim();

    if (!fieldValue && (field.id === 'PhoneNo1' || field.id === 'LandNumber')) {
        field.setCustomValidity('');
        return true;                              // Skip validation for these fields if they are empty
    }

    if (!fieldValue) {
        field.setCustomValidity('This field cannot be empty.');
        field.reportValidity();
        return false;
    }

    if (pattern && !pattern.test(fieldValue)) {
        field.setCustomValidity(errorMsg || 'Invalid input format.');
        field.reportValidity();
        return false;
    }
    field.setCustomValidity('');
    return true;
  };

    const getTabIndexFields = () => {
      return orderedFieldIds
        .map(id => {
            const field = document.getElementById(id);
                                                                       // Check if the field exists and log its tabindex
            if (field) {
                const tabindex = parseInt(field.getAttribute('tabindex'), 10) || 0;
<!--                console.log(`Field ID: ${id}, Tabindex: ${tabindex}`);-->
                return { field, tabindex };
            } else {
                console.warn(`Field with ID: ${id} not found`);
                return null;
            }
        })
    };

    const validateFieldInOrder= async () => {
       let isValid =true;
       const fields = getTabIndexFields().sort((a, b) => a.tabindex - b.tabindex);
       for (let { field,tabindex } of fields) {
          let valid;
                     // Specific validations based on field type
          if (field.id === 'PhoneNo1') {
             valid = validateField(field, /^[6-9]\d{9}$/, 'Please enter a valid Phone number.');
          }
          else if (field.id === 'Email1') {
             valid = validateField(field, !field.value.match(/^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/) || field.value.includes('..') || !field.value.match(/^[^\s@]{1,64}@([^\s@_]+\.)+[a-zA-Z]{2,}$/),
             'Please enter a valid Email address.');
          }
          else if (field.id === 'LandNumber') {
             valid = validateField(field, /^(\+91[-\s]?)?[0]?\d{2,5}[-\s]?\d{3,4}[-\s]?\d{4}$/, 'Please enter a valid Landline number.');
          }
          else if (field.id === 'Email2') {
              valid = validateField(field, !field.value.match(/^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/) || field.value.includes('..') || !field.value.match(/^[^\s@]{1,64}@([^\s@_]+\.)+[a-zA-Z]{2,}$/),
             'Please enter a valid Email address.');          }
          else if (field.id === 'Pincode') {
             valid = validateField(field, /^[1-9][0-9]{5}$/, 'Please enter a valid Pincode.');
          }
          else {
             valid = validateField(field); // General non-empty check
          }

          if(!valid) {
              console.log(`Validation error at tabindex: ${tabindex}`);
              isValid = false;
              field.focus();
              break;
          }
          if (field.id === 'PhoneNo1' || field.id === 'LandNumber' || field.id === 'Email1' || field.id === 'Email2') {
            const exists = await checkFieldExists(field.id, field);
            if (!exists) {
              field.focus();
              isValid = false;
              break;
            }
          }
       }
       return isValid;
    };

    const checkFieldExists = (fieldName, field) => {
    return new Promise((resolve) => {
      const value = field.value.trim();
      fetch(`/skyonnadmin/validate_internal_team/?${fieldName}=${value}`)
        .then(response => response.json())
        .then(data => {
          if (data.exists) {
            field.setCustomValidity(`${fieldName} already exists.`);
            field.reportValidity();
            resolve(false);
          } else {
            field.setCustomValidity('');
            resolve(true);
          }
        })
        .catch(error => {
          console.error('Error:', error);
          resolve(false);
        });
      });
    };

    const isValid = await validateFieldInOrder();

    if (!isValid) {
      console.log("Validation failed. Please correct the highlighted errors.");
      return;
    }

    // Proceed with saving if valid
    const formData = new FormData(form);
    const url = form.getAttribute('action');

    try{
       const response = await fetch(url, {
          method: 'POST',
          body: formData,
          headers: {
             'X-CSRFToken': '{{ csrf_token }}',
          },
       })
        if (!response.ok) throw new Error('Failed to save internal team details.');
        const data = await response.json();
        console.log('Row saved:',data);
        form.reset();
        currentRowIndex++;
        if (currentRowIndex < excelRows.length) {
           processRow(excelRows[currentRowIndex]);
        }
        return true;
      } catch (error) {
          console.error('Error saving row:', error);
          return false;
      }
    }

    async function processRowsSequentially() {
                        while (currentRowIndex < excelRows.length) {
                            processRow(excelRows[currentRowIndex]);
                            const saved = await saveInternal_team_details();
                            if (!saved){
                                     console.log("Error at the row", currentRowIndex);
                                     return;
                            }
                            console.log('Row saved successfully:', currentRowIndex);
                        }
                        if (currentRowIndex === excelRows.length) {
                            alert(`All ${excelRows.length} rows have been processed successfully`);
                        }
    }
    processRowsSequentially();
    })
     .catch(error => console.error("Error uploading Excel file:", error));       //load excel data
   }
   else {
     excelFile.value = "";                                                      // get row count
   }
})
}
})


document.addEventListener('DOMContentLoaded', function () {
  document.addEventListener('change', function () {
    const excel_file = document.getElementById('excelFile').files[0];
    if(!excel_file) {

    console.log('main dom');

    const form = document.getElementById('internal-team');

    const phoneNumberInput1 = document.getElementById('PhoneNo1');
    const emailInput1 = document.getElementById('Email1');
    const phoneNumberInput2 = document.getElementById('LandNumber');
    const emailInput2 = document.getElementById('Email2');
    const pincodeInput = document.getElementById('Pincode');

    if(!phoneNumberInput1 || !emailInput1 || !phoneNumberInput2 || !emailInput2) { return;}

    const phonePattern = /^[6-9]\d{9}$/;
    const pincodePattern = /^[1-9][0-9]{5}$/;
    const emailPattern = /^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/;
    const emailPattern2 = /^[^\s@]{1,64}@([^\s@_]+\.)+[a-zA-Z]{2,}$/;

    const validateField = (field) => {
        if (!field.value.trim()) {
            field.style.borderColor = '';
            field.setCustomValidity('Please fill out this field.');
            field.reportValidity();
            return false;
        } else {
            field.style.borderColor = 'black';
            field.setCustomValidity('');
            return true;
        }
    };

    const clearValidation = (field) => {
        field.setCustomValidity('');
        field.style.borderColor = '';
    };

    emailInput1.addEventListener('input', () => {
        clearValidation(emailInput1);
    });

    phoneNumberInput1.addEventListener('input', () => {
        clearValidation(phoneNumberInput1);
    });

    emailInput2.addEventListener('input', () => {
        clearValidation(emailInput2);
    });

    phoneNumberInput2.addEventListener('input', () => {
        clearValidation(phoneNumberInput2);
    });

    pincodeInput.addEventListener('input', () => {
        clearValidation(pincodeInput);
    });

    emailInput1.addEventListener('blur', () => {
        if (emailInput1.value.trim() && (!emailInput1.value.match(/^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/) || emailInput1.value.includes('..') || !emailInput1.value.match(/^[^\s@]{1,64}@([^\s@_]+\.)+[a-zA-Z]{2,}$/))) {
            emailInput1.style.borderColor = '';
            emailInput1.setCustomValidity('Please enter a valid Email address');
            emailInput1.reportValidity();
        } else {
             clearValidation(emailInput1);
             if (emailInput1.value.trim()) {
                checkFieldExists('Email1', emailInput1);
             }
        }
    });

    phoneNumberInput1.addEventListener('blur', () => {
        if (phoneNumberInput1.value.trim() && !phoneNumberInput1.value.match(/^[6-9]\d{9}$/)) {
            phoneNumberInput1.style.borderColor = '';
            phoneNumberInput1.setCustomValidity('Please enter a valid Phonenumber.');
            phoneNumberInput1.reportValidity();
        } else {
            clearValidation(phoneNumberInput1);
            if (phoneNumberInput1.value.trim()) {
                checkFieldExists('PhoneNo1', phoneNumberInput1);
            }
        }
    });

    emailInput2.addEventListener('blur', () => {
        if (emailInput2.value.trim() && (!emailInput2.value.match(/^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/) || emailInput2.value.includes('..') || !emailInput2.value.match(/^[^\s@]{1,64}@([^\s@_]+\.)+[a-zA-Z]{2,}$/))) {
            emailInput2.style.borderColor = '';
            emailInput2.setCustomValidity('Please enter a valid Email address');
            emailInput2.reportValidity();
        } else {
            clearValidation(emailInput2);
            if (emailInput2.value.trim()) {
                checkFieldExists('Email2', emailInput2);
            }
        }
    });

    phoneNumberInput2.addEventListener('blur', () => {
        const normalValue = phoneNumberInput2.value.trim()
        console.log(normalValue);
        if (phoneNumberInput2.value.trim() && !phoneNumberInput2.value.match(/^(\+91[-\s]?)?[0]?\d{2,5}[-\s]?\d{3,4}[-\s]?\d{4}$/)) {
            phoneNumberInput2.style.borderColor = '';
            phoneNumberInput2.setCustomValidity('Please enter a valid Landline number.');
            phoneNumberInput2.reportValidity();
        } else {
            clearValidation(phoneNumberInput2);
            if (normalValue) {
                checkFieldExists('LandNumber', phoneNumberInput2, normalValue);
            }
        }
    });

    pincodeInput.addEventListener('blur', () => {
        if (pincodeInput.value.trim() && !pincodeInput.value.match(/^[1-9][0-9]{5}$/)) {
            pincodeInput.style.borderColor = '';
            pincodeInput.setCustomValidity('Please enter a valid Pincode');
            pincodeInput.reportValidity();
        } else {
            clearValidation(pincodeInput);
        }
    });

    function checkFieldExists(fieldName, field, normalValue=null) {

           const value = normalValue || field.value.trim();
           fetch(`/skyonnadmin/validate_internal_team/?${fieldName}=${value}`)
                .then(response => response.json())
                .then(data => {
                    if (data.exists) {
                        if(fieldName == 'PhoneNo1' || fieldName == 'LandNumber') {
                            field.setCustomValidity('Phone number already exists.');
                        }
                        else {
                             field.setCustomValidity('Email already exists.');
                        }
                        field.style.borderColor = 'red';
                        field.reportValidity();
                        field.focus();
                    } else {
                        clearValidation(field);
                    }
                })
                .catch(error => console.error('Error:', error));
    };
    }
  });
});

  window.saveInternal_team_details= async function() {

        console.log('main window');
        const form = document.getElementById('internal-team');
        const orderedFieldIds = [
            'FirstName', 'LastName', 'Designation', 'Department', 'Address_1', 'City', 'State', 'Pincode', 'Country',
            'PhoneNo1','Email1','Level'
        ];

        const FirstNameInput = document.getElementById('FirstName');
        const phoneNumberInput1 = document.getElementById('PhoneNo1');
        const emailInput1 = document.getElementById('Email1');
        const phoneNumberInput2 = document.getElementById('LandNumber');
        const emailInput2 = document.getElementById('Email2');
        const pincodeInput = document.getElementById('Pincode');

<!--        if(!phoneNumberInput1.value.trim() && !phoneNumberInput2.value.trim()) {-->
<!--            return;-->
<!--        }-->

        let isValid = true;

                                       // Clear any previous custom validation messages and reset border colors
        orderedFieldIds.forEach(id => {
            const field = document.getElementById(id);
            if (field) {
                field.setCustomValidity(''); // Clear previous validation message
                field.style.borderColor = ''; // Reset border color
            }
        });

        // Iterate over each field in the specified order to validate
        for (let id of orderedFieldIds) {
            const field = document.getElementById(id);
            if (field && !field.value.trim()) {
                    isValid = false;
                    field.setCustomValidity('Please fill out this field.');
                    field.reportValidity();
            }
        }

        const validateEmail = (emailInput) => {
            if (emailInput.value.trim() && (!emailInput.value.match(/^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/) || emailInput.value.includes('..') || !emailInput.value.match(/^[^\s@]{1,64}@([^\s@_]+\.)+[a-zA-Z]{2,}$/))) {
               isValid = false;
               emailInput.style.borderColor = '';
               emailInput.setCustomValidity('Please enter a valid Email address');
               emailInput.reportValidity();
            }
            else {
               emailInput.setCustomValidity('');
               emailInput.style.borderColor = 'black';
            }
        }


        const checkValidity = (field,pattern,errorMsg) =>{
           if (field.value.trim() && !field.value.match(pattern)) {
              field.setCustomValidity(errorMsg);
              field.reportValidity();
              isValid=false;
           }
           else {
               field.setCustomValidity('');
               field.style.borderColor = 'black';
           }
        };

        checkValidity(phoneNumberInput1, /^[6-9]\d{9}$/, 'Please enter a valid Phonenumber.');

        validateEmail(emailInput1);

        if (phoneNumberInput2.value.trim()) {
           checkValidity(phoneNumberInput2, /^(\+91[-\s]?)?[0]?\d{2,5}[-\s]?\d{3,4}[-\s]?\d{4}$/, 'Please enter a valid Landline number.');
        }

        if (emailInput2.value.trim()) {
           validateEmail(emailInput2);
        }

        checkValidity(pincodeInput, /^[1-9][0-9]{5}$/, 'Please enter a valid Pincode');

        const checkFieldExists = (fieldName, field, normalValue = null) => {
          return new Promise((resolve, reject) => {
             const value = normalValue || field.value.trim();
             fetch(`/skyonnadmin/validate_internal_team/?${fieldName}=${value}`)
                .then(response => response.json())
                .then(data => {
                    if (data.exists) {
                        if (fieldName === 'PhoneNo1' || fieldName === 'LandNumber') {
                            field.setCustomValidity('Phone number already exists.');
                        } else {
                            field.setCustomValidity('Email already exists.');
                        }
                        field.style.borderColor = 'red';
                        field.reportValidity();
                        resolve(false); // Invalid
                    } else {
                        field.setCustomValidity('');
                        field.style.borderColor = 'black';
                        resolve(true); // Valid
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    reject(error);
                });
          });
        }

        if (isValid) {
            const phoneNo1Valid = await checkFieldExists('PhoneNo1', phoneNumberInput1);
            const email1Valid = await checkFieldExists('Email1', emailInput1);
            const normalValue = phoneNumberInput2.value.trim()
            console.log(normalValue);
            const phoneNo2Valid = await checkFieldExists('PhoneNo2', phoneNumberInput2,normalValue);
            const email2Valid = await checkFieldExists('Email2', emailInput2);

            isValid = phoneNo1Valid && email1Valid && phoneNo2Valid && email2Valid;
        }

        if (!isValid) {
            console.log("Validation failed. Please fill out the required fields.");
            return;
        }

                                     // Proceed with saving data if all fields are valid
    const formData = new FormData(form);
    const url = form.getAttribute('action');

    console.log("Submitting form to:", url);
    console.log("Form data:", [...formData.entries()]); // Log the form data


    fetch(url, {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': '{{ csrf_token }}', // Assuming you have CSRF token available
        },
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Failed to save internal team details.');
        }
        return response.json();
    })
    .then(data => {
            if (data.status === 'error') {
                if (data.field && data.message) {
                    const errorField = form.querySelector(`[name=${data.field}]`);
                    if (errorField) {
                        errorField.style.borderColor = '';
                        errorField.setCustomValidity(data.message);
                        errorField.reportValidity();
                        errorField.focus();
                        errorField.value = '';
                          errorField.addEventListener('input', () => {
                             errorField.style.borderColor = 'black';
                             errorField.setCustomValidity('');
                             errorField.reportValidity();
                          }, { once: true });
                    } else {
                        alert(data.message);
                    }
                } else {
                    alert(data.message || 'Error saving Client.');
                }
            } else {
                alert('Internal Team saved successfully.');
                form.reset();
            }
        })
    .catch(error => {
        console.error('Error:', error);
        alert('Error: ' + error.message);
    })
  }












  document.addEventListener('click',function() {
     if (event.target && event.target.matches('.client-link')) {            //hyperlink to show company details
        event.preventDefault();
        const client = event.target.getAttribute('data-client');

        let xhr= new XMLHttpRequest();
        xhr.open('GET',`/get_client_details/?client=${client}`,true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                const details = JSON.parse(xhr.responseText);
                console.log(details);

            } else {
                console.error('Request failed. Status: ' + xhr.status);
            }
       };
       xhr.send()
     }
  });



function updateButtonStates() {
    const clientDropdown = document.getElementById("ClientDropdown");
    const subClientDropdown = document.getElementById("SubClientDropdown");
    const getCompanyDetailsButton = document.getElementById("getCompanyDetailsButton");
    const getTeamDetailsButton = document.getElementById("getTeamDetailsButton");

    const clientSelected = clientDropdown.value !== "";
    const subClientSelected = subClientDropdown.value !== "";

    if (clientSelected || subClientSelected) {
        getCompanyDetailsButton.classList.remove("disabled-button");
        getCompanyDetailsButton.classList.add("enabled-button");
        getCompanyDetailsButton.disabled = false;

        getTeamDetailsButton.classList.remove("disabled-button");
        getTeamDetailsButton.classList.add("enabled-button");
        getTeamDetailsButton.disabled = false;


    } else {
        getCompanyDetailsButton.classList.remove("enabled-button");
        getCompanyDetailsButton.classList.add("disabled-button");
        getCompanyDetailsButton.disabled = true;

        getTeamDetailsButton.classList.remove("enabled-button");
        getTeamDetailsButton.classList.add("disabled-button");
        getTeamDetailsButton.disabled = true;
    }
}


function initializeEventListeners() {
    const clientDropdown = document.getElementById("ClientDropdown");
    const subClientDropdown = document.getElementById("SubClientDropdown");
    clientDropdown.addEventListener("change", updateButtonStates);
    subClientDropdown.addEventListener("change", updateButtonStates);
    updateButtonStates();
}
const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
        const clientDropdown = document.getElementById("ClientDropdown");
        const subClientDropdown = document.getElementById("SubClientDropdown");

        if (clientDropdown && subClientDropdown) {
            initializeEventListeners();
        }
    });
});

observer.observe(document.body, { childList: true, subtree: true });
document.addEventListener("DOMContentLoaded", function () {
    initializeEventListeners();
});



  document.addEventListener('click', function(event) {

    const clientDropdown = document.getElementById('ClientDropdown');
    const subClientDropdown = document.getElementById('SubClientDropdown');
    const searchKeyword  = document.getElementById('searchKeyword')
      if (!searchKeyword) return;

   function handleSearch() {

      const clientValue = clientDropdown ? clientDropdown.value.trim() : '';
      const subClientValue = subClientDropdown ? subClientDropdown.value.trim() : '';
      const keyword = searchKeyword.value.trim();
      console.log('keyword1:',keyword);

      if (keyword === '') {
          console.log('Making empty');
          let tableContainer = document.getElementById('TableContainer');
          tableContainer.innerHTML = '';
          return;
      }
      performSearch();
   }

  function performSearch() {
     const client = document.getElementById('ClientDropdown').value;
     const subClient = document.getElementById('SubClientDropdown').value;
     const searchKeyword  = document.getElementById('searchKeyword').value;
     console.log('keyword2:',searchKeyword);

     let xhr = new XMLHttpRequest();
     xhr.open('GET', `/skyonnadmin/get_SearchData/?client=${client}&subClient=${subClient}&searchKeyword=${searchKeyword}`, true);
     xhr.onload = function() {
         if (xhr.status === 200) {

             filteredData = JSON.parse(xhr.responseText);
             console.log(filteredData);
             renderNewTables(filteredData);
         } else {
             console.error('Request failed. Status: ' + xhr.status);
         }
     };
     xhr.send();
  }

  searchKeyword.addEventListener('input', handleSearch);

  if (clientDropdown) {
      clientDropdown.addEventListener('change', handleSearch);
  }
  if (subClientDropdown) {
      subClientDropdown.addEventListener('change', handleSearch);
  }
});


function renderNewTables(filteredData) {
  let tableContainer = document.getElementById('TableContainer');
  tableContainer.innerHTML = '';

  let TableHTML = '<div id="TableName"><table border="1">';

  if (filteredData.client_details.length === 0 && filteredData.sub_company_details.length === 0 && filteredData.contacts.length === 0) {
     TableHTML += `<thead style="margin-left:-370px;"><tr><th>No details found</th></tr></thead>`;
     TableHTML += `</table></div>`;
     tableContainer.innerHTML += TableHTML;
     return;
  }

  if (filteredData.client_details.length > 0) {
     renderClientTable(filteredData.client_details, 'Main client');
  }

  if (filteredData.sub_company_details.length > 0) {
    renderClientTable(filteredData.sub_company_details, 'Sub client');
  }

  if (filteredData.contacts.length > 0) {
      renderTeamDetails(filteredData);
  }
  AddActionButtons();
}






<!--document.addEventListener('DOMContentLoaded', function() {-->
<!--   document.addEventListener('change', function(event) {-->
<!--     var target = event.target;-->
<!--     if (target && target.id === 'Client') {-->
<!--        var client = target.value; // Get selected client-->
<!--        let SPOC1 = document.getElementById('SPOC');-->
<!--        if (!SPOC1) return;-->

<!--        let SPOC2 = document.getElementById('SPOC2');-->
<!--        if (!SPOC2) return;-->

<!--        SPOC1.innerHTML = '<option value="">Select SPOC1</option>';-->
<!--        SPOC2.innerHTML = '<option value="">Select SPOC2</option>';-->
<!--                                                                   // Make AJAX request to get filtered data-->
<!--        let xhr = new XMLHttpRequest();-->
<!--        xhr.open('GET', '/skyonnadmin/get_contacts/?Client=' + client, true);-->
<!--        xhr.onload = function() {-->
<!--            if (xhr.status === 200) {-->
<!--                var spocData = JSON.parse(xhr.responseText);-->

<!--                spocData.forEach(function(contact) {-->
<!--                    const option1 = document.createElement('option');-->
<!--                    option1.value = `${contact.FirstName}-${contact.Department}`;-->
<!--                    option1.textContent = `${contact.FirstName}-${contact.Department}`;-->
<!--                    SPOC1.appendChild(option1);-->

<!--                    const option2 = document.createElement('option');-->
<!--                    option2.value = `${contact.FirstName}-${contact.Department}`;-->
<!--                    option2.textContent = `${contact.FirstName}-${contact.Department}`;-->
<!--                    SPOC2.appendChild(option2);-->
<!--                });-->
<!--            } else {-->
<!--                console.error('Request failed. Status: ' + xhr.status);-->
<!--            }-->
<!--        };-->
<!--        xhr.onerror = function() {-->
<!--            console.error('Request failed.');-->
<!--        };-->
<!--        xhr.send();-->
<!--     }-->
<!--   })-->
<!--});-->


document.addEventListener('DOMContentLoaded', function() {
  document.addEventListener('change', function(event) {
      var target = event.target;
      const formId = document.getElementById('Add_new_contact');
      console.log(formId);
      if (target && target.id === 'ClientDropdown' && formId.id === 'Add_new_contact') {
          var parentCompany = target.value; // Get selected client
          var subClientDropdown = target.closest('form').querySelector('#SubClientDropdown');

          subClientDropdown.innerHTML = '';

          if (subClientDropdown.tagName.toLowerCase() === 'input') {
             var element = document.createElement('select');
             element.id = 'SubClientDropdown';
             element.name = 'Sub_Company';
             element.style.marginLeft = '10px';
             element.tabIndex = 2;

             subClientDropdown.parentNode.replaceChild(element,subClientDropdown);
             subClientDropdown = element;
          }

          // Make an AJAX request to fetch sub-clients filtered by selected client
          var xhr = new XMLHttpRequest();
          xhr.open('GET', '/skyonnadmin/get_subclients/?parent_company=' + parentCompany, true);
          xhr.onload = function() {
              if (xhr.status === 200) {

                  // Parse response and add options to SubClient dropdown
                  var subClients = JSON.parse(xhr.responseText);
                  subClients.forEach(function(subClient) {
                      var option = document.createElement('option');
                      option.value = subClient;
                      option.text = subClient;
                      subClientDropdown.appendChild(option);
                  });

                  var parentOption = document.createElement('option');
                  parentOption.value = parentCompany;
                  parentOption.textContent = parentCompany;
                  subClientDropdown.insertBefore(parentOption,subClientDropdown.firstChild);
                  subClientDropdown.value  = parentCompany;
                  subClientDropdown.disabled = false;

                  if (subClientDropdown.options.length === 1) {
                     var inputElement = document.createElement('input');
                     inputElement.type = 'text';
                     inputElement.id = 'SubClientDropdown';
                     inputElement.name = 'Sub_Company';

                     inputElement.disabled = true;
                     inputElement.value = subClientDropdown.options[0].text;

                     subClientDropdown.parentNode.replaceChild(inputElement, subClientDropdown);
                  }
              } else {
                  console.error('Request failed. Status: ' + xhr.status);
              }
          };
          xhr.send();
      }
  });
});

document.addEventListener('DOMContentLoaded', function() {
  document.addEventListener('change', function() {
    const form = document.getElementById('Add_new_contact');
    if (!form) return;

    const emailInput = document.getElementById('Email');
    const phoneNumberInput = document.getElementById('Phone_number');
    const requiredFields = form.querySelectorAll('input[required], select[required]');
    const validateField = (field) => {
        if (!field.value.trim()) {
            field.style.borderColor = '';
            field.setCustomValidity('Please fill out this field.');
            field.reportValidity();
            return false;
        } else {
            field.style.borderColor = 'black';
            field.setCustomValidity('');
            return true;
        }
    };

    const clearValidation = (field) => {
        field.setCustomValidity('');
        field.style.borderColor = '';
    };

    emailInput.addEventListener('input', () => {
        clearValidation(emailInput);
    });

    phoneNumberInput.addEventListener('input', () => {
        clearValidation(phoneNumberInput);
    });

    emailInput.addEventListener('blur', () => {
        if (emailInput.value.trim() && (!emailInput.value.match(/^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/) || emailInput.value.includes('..') || !emailInput.value.match(/^[^\s@]{1,64}@([^\s@_]+\.)+[a-zA-Z]{2,}$/))) {
            emailInput.style.borderColor = '';
            emailInput.setCustomValidity('Invalid email format.');
            emailInput.reportValidity();
        } else {
            clearValidation(emailInput);
            if (emailInput.value.trim()) {
                checkFieldExists('Email', emailInput);
            }
        }
    });

    phoneNumberInput.addEventListener('blur', () => {
        if (phoneNumberInput.value.trim() && !phoneNumberInput.value.match(/^[6-9]\d{9}$/)) {
            phoneNumberInput.style.borderColor = '';
            phoneNumberInput.setCustomValidity('Invalid phone number format.');
            phoneNumberInput.reportValidity();
        } else {
            clearValidation(phoneNumberInput);
            if (phoneNumberInput.value.trim()) {
                checkFieldExists('Phone_number', phoneNumberInput);
            }
        }
    });

    function checkFieldExists(fieldName, field) {
        const value = field.value.trim();

        fetch(`/validate_field/?${fieldName}=${value}`)
                .then(response => response.json())
                .then(data => {
                    if (data.exists) {
                        if (fieldName === 'Phone_number') {
                            field.setCustomValidity('Phone number already exists.');
                        } else {
                            field.setCustomValidity('Email already exists.');
                        }
                        field.style.borderColor = 'red';
                        field.reportValidity();
                    } else {
                        field.setCustomValidity('');
                        field.style.borderColor = 'black';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
    }
  })
});


 window.saveAdd_new_contact = async function () {
    const form = document.getElementById('Add_new_contact');
    const requiredFields = [
        document.getElementById('ClientDropdown'),   // Company
        document.getElementById('FirstName'),
        document.getElementById('Designation'), // Designation
        document.getElementById('Department'), // Department
        document.getElementById('Email'),      // Email
        document.getElementById('Phone_number') // Phone Number
    ];

    let isValid = true;

    // Clear previous validation messages
    requiredFields.forEach(field => {
        field.setCustomValidity('');
        field.style.borderColor = '';
    });

    // Sequential validation of required fields
    for (let field of requiredFields) {
        if (!field.value.trim()) {
            isValid = false;
            field.setCustomValidity('Please fill out this field.');
            field.reportValidity();
            field.focus();
            return; // Stop validation if any field is invalid
        }
    }

    // Email validation
    const emailInput = document.getElementById('Email');
    if (
        emailInput.value.trim() &&
        (!/^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/.test(emailInput.value) || emailInput.value.includes('..'))
    ) {
        isValid = false;
        emailInput.setCustomValidity('Please enter a valid email address.');
        emailInput.reportValidity();
        emailInput.focus();
        return;
    }

    // Phone number validation
    const phoneNumberInput = document.getElementById('Phone_number');
    const phonePattern = /^[6-9]\d{9}$/;
    if (phoneNumberInput.value.trim() && !phonePattern.test(phoneNumberInput.value)) {
        isValid = false;
        phoneNumberInput.setCustomValidity('Invalid phone number format.');
        phoneNumberInput.reportValidity();
        phoneNumberInput.focus();
        return;
    }

    // Asynchronous validation for uniqueness
    const checkFieldExists = (fieldName, input) => {
        return new Promise((resolve, reject) => {
            fetch(`/validate_field/?${fieldName}=${encodeURIComponent(input.value.trim())}`)
                .then(response => response.json())
                .then(data => {
                    if (data.exists) {
                        isValid = false;
                        input.setCustomValidity(`${fieldName.replace('_', ' ')} already exists.`);
                        input.reportValidity();
                        input.focus();
                        resolve(false);
                    } else {
                        input.setCustomValidity('');
                        input.style.borderColor = 'black';
                        resolve(true);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    reject(error);
                });
        });
    };

    const phoneNoValid = await checkFieldExists('Phone_number', phoneNumberInput);
    const emailValid = await checkFieldExists('Email', emailInput);

    isValid = isValid && phoneNoValid && emailValid;

    if (!isValid) {
        console.log('Validation failed. Please fill out the required fields.');
        return;
    }

    // Submit form if all validations pass
    const formData = new FormData(form);
    const url = form.getAttribute('action');

    try {
        const response = await fetch(url, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRFToken': '{{ csrf_token }}', // Adjust according to your CSRF setup
            },
        });

        const data = await response.json();

        if (!response.ok || data.status === 'error') {
            if (data.field && data.message) {
                const errorField = form.querySelector(`[name="${data.field}"]`);
                if (errorField) {
                    errorField.setCustomValidity(data.message);
                    errorField.reportValidity();
                    errorField.focus();
                } else {
                    alert(data.message || 'Error saving contact.');
                }
            } else {
                alert(data.message || 'Error saving contact.');
            }
        } else {
            alert('Contact details saved successfully.');
            form.reset();
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error: Unable to save contact. Please try again later.');
    }
};











<!--document.addEventListener('DOMContentLoaded', function() {-->
<!--  document.addEventListener('change', function() {-->
<!--    const form = document.getElementById('AddSPOCform');-->
<!--    if (!form) return;-->

<!--    const emailInput = document.getElementById('Email');-->
<!--    const phoneNumberInput = document.getElementById('Phone_number');-->
<!--    const requiredFields = form.querySelectorAll('input[required], select[required]');-->

<!--    const validateField = (field) => {-->
<!--        if (!field.value.trim()) {-->
<!--            field.style.borderColor = '';-->
<!--            field.setCustomValidity('Please fill out this field.');-->
<!--            field.reportValidity();-->
<!--            return false;-->
<!--        } else {-->
<!--            field.style.borderColor = 'black';-->
<!--            field.setCustomValidity('');-->
<!--            return true;-->
<!--        }-->
<!--    };-->

<!--    const clearValidation = (field) => {-->
<!--        field.setCustomValidity('');-->
<!--        field.style.borderColor = '';-->
<!--    };-->

<!--    emailInput.addEventListener('input', () => {-->
<!--        clearValidation(emailInput);-->
<!--    });-->

<!--    phoneNumberInput.addEventListener('input', () => {-->
<!--        clearValidation(phoneNumberInput);-->
<!--    });-->

<!--    emailInput.addEventListener('blur', () => {-->
<!--        if (emailInput.value.trim() && (!emailInput.value.match(/^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/) || emailInput.value.includes('..') || !emailInput.value.match(/^[^\s@]{1,64}@([^\s@_]+\.)+[a-zA-Z]{2,}$/))) {-->
<!--            emailInput.style.borderColor = '';-->
<!--            emailInput.setCustomValidity('Invalid email format.');-->
<!--            emailInput.reportValidity();-->
<!--        } else {-->
<!--            clearValidation(emailInput);-->
<!--            if (emailInput.value.trim()) {-->
<!--                checkFieldExists('Email', emailInput.value.trim());-->
<!--            }-->
<!--        }-->
<!--    });-->

<!--    phoneNumberInput.addEventListener('blur', () => {-->
<!--        if (phoneNumberInput.value.trim() && !phoneNumberInput.value.match(/^[6-9]\d{9}$/)) {-->
<!--            phoneNumberInput.style.borderColor = '';-->
<!--            phoneNumberInput.setCustomValidity('Invalid phone number format.');-->
<!--            phoneNumberInput.reportValidity();-->
<!--        } else {-->
<!--            clearValidation(phoneNumberInput);-->
<!--            if (phoneNumberInput.value.trim()) {-->
<!--                checkFieldExists('Phone_number', phoneNumberInput.value.trim());-->
<!--            }-->
<!--        }-->
<!--    });-->

<!--    function checkFieldExists(fieldName, fieldValue) {-->
<!--        const xhr = new XMLHttpRequest();-->
<!--        const url = `/skyonnadmin/validate_field/?${fieldName}=${encodeURIComponent(fieldValue.trim())}`;-->

<!--        xhr.open('GET', url, true);-->
<!--        xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}'); // Ensure CSRF token is included-->
<!--        xhr.onload = function() {-->
<!--            if (xhr.status === 200) {-->
<!--                const response = JSON.parse(xhr.responseText);-->
<!--                if (response.exists) {-->
<!--                    handleValidationResult(fieldName, fieldValue, `${fieldName === 'Email' ? 'Email' : 'Phone number'} already exists.`);-->
<!--                } else {-->
<!--                    handleValidationResult(fieldName, fieldValue, '');-->
<!--                }-->
<!--            } else {-->
<!--                console.error('Request failed. Status: ' + xhr.status);-->
<!--            }-->
<!--        };-->
<!--        xhr.send();-->
<!--    }-->

<!--                                                   // Function to handle validation result-->
<!--    function handleValidationResult(fieldName, fieldValue, errorMessage) {-->
<!--        const inputField = fieldName === 'Email' ? emailInput : phoneNumberInput;-->
<!--        if (errorMessage) {-->
<!--            inputField.setCustomValidity(errorMessage);-->
<!--            inputField.style.borderColor = '';-->
<!--            inputField.reportValidity();-->
<!--            inputField.focus();-->
<!--        } else {-->
<!--            inputField.setCustomValidity('');-->
<!--            inputField.style.borderColor = '';-->
<!--        }-->
<!--    }-->
<!--  })-->
<!--});-->

<!--  window.saveAdd_SPOC = function() {-->

<!--    const form = document.getElementById('AddSPOCform');-->
<!--    const requiredFields = form.querySelectorAll('input[required], select[required]');-->
<!--    const phoneNumberInput = document.getElementById('Phone_number');-->

<!--    let isValid = true;-->
<!--    requiredFields.forEach(field => {-->
<!--        field.setCustomValidity(''); // Clear previous validation message-->
<!--        field.style.borderColor = ''; // Reset border color-->
<!--    });-->

<!--                                  // Iterate over each required field to check if it has value-->
<!--    for (let field of requiredFields) {-->
<!--        if (!field.value.trim()) {-->
<!--            isValid = false;-->
<!--            field.style.borderColor = '';-->
<!--            field.setCustomValidity('Please fill out this field.');-->
<!--            field.reportValidity();-->
<!--            break;-->
<!--        } else {-->
<!--                           // If field is filled, reset border to black-->
<!--            field.style.borderColor = 'black';-->
<!--            field.setCustomValidity('');-->
<!--        }-->
<!--    }-->

<!--            if (phoneNumberInput.value.trim() && !phoneNumberInput.value.match(/^[6-9]\d{9}$/)) {-->
<!--                isValid = false;-->
<!--                phoneNumberInput.style.borderColor = '';-->
<!--                phoneNumberInput.setCustomValidity('Invalid phone number format.');-->
<!--                phoneNumberInput.reportValidity();-->
<!--            }-->

<!--            if (!isValid) {-->
<!--                // Prevent form submission if validation fails-->
<!--                console.log("Validation failed. Please fill out the required fields.");-->
<!--                return;-->
<!--            }-->

<!--                                                       // Final check for email and phone number uniqueness-->
<!--      checkFieldExistsPromise('Phone_number', phoneNumberInput.value.trim()).then(isUnique => {-->
<!--            if (!isUnique) {-->
<!--                console.log("Validation failed. Phone number already exists.");-->
<!--                phoneNumberInput.setCustomValidity('Phone number already exists.');-->
<!--                phoneNumberInput.style.borderColor = '';-->
<!--                phoneNumberInput.reportValidity();-->
<!--                phoneNumberInput.focus();-->
<!--                return;-->
<!--            }-->


<!--                // If all validations pass, submit the form-->
<!--                const formData = new FormData(form);-->
<!--                const url = form.getAttribute('action');-->

<!--                fetch(url, {-->
<!--                    method: 'POST',-->
<!--                    body: formData,-->
<!--                    headers: {-->
<!--                        'X-CSRFToken': '{{ csrf_token }}',-->
<!--                    },-->
<!--                })-->
<!--                .then(response => response.json())-->
<!--                .then(data => {-->
<!--                    if (data.status === 'error') {-->
<!--                        if (data.field && data.message) {-->
<!--                            const errorField = form.querySelector(`[name=${data.field}]`);-->
<!--                            if (errorField) {-->
<!--                                errorField.style.borderColor = '';-->
<!--                                errorField.setCustomValidity(data.message);-->
<!--                                errorField.reportValidity();-->
<!--                                errorField.focus();-->
<!--                            } else {-->
<!--                                alert(data.message);-->
<!--                            }-->
<!--                        } else {-->
<!--                            alert(data.message || 'Error saving Contact.');-->
<!--                        }-->
<!--                    } else {-->
<!--                        alert('Contact saved successfully.');-->
<!--                        form.reset();-->
<!--                        hidePopup(); // Hide the main popup-->
<!--                        showSuccessPopup();-->
<!--                    }-->
<!--                })-->
<!--                .catch(error => {-->
<!--                    console.error('Error:', error);-->
<!--                });-->
<!--            });-->
<!--      };-->

<!--  function checkFieldExistsPromise(fieldName, fieldValue) {-->
<!--            return new Promise((resolve, reject) => {-->
<!--                const xhr = new XMLHttpRequest();-->
<!--                const url = `/skyonnadmin/validate_field/?${fieldName}=${encodeURIComponent(fieldValue.trim())}`;-->

<!--                xhr.open('GET', url, true);-->
<!--                xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}'); // Ensure CSRF token is included-->
<!--                xhr.onload = function() {-->
<!--                    if (xhr.status === 200) {-->
<!--                        const response = JSON.parse(xhr.responseText);-->
<!--                        resolve(!response.exists);-->
<!--                    } else {-->
<!--                        console.error('Request failed. Status: ' + xhr.status);-->
<!--                        reject();-->
<!--                    }-->
<!--                };-->
<!--                xhr.send();-->
<!--            });-->
<!--  }-->

<!--  function refreshSPOCs() {-->
<!--        console.log('refreshing SPOCs');-->
<!--        let client = document.getElementById('Client').value;-->
<!--        let SPOC1 = document.getElementById('SPOC');-->
<!--        if (!SPOC1) return;-->

<!--        let SPOC2 = document.getElementById('SPOC2');-->
<!--        if (!SPOC2) return;-->

<!--        SPOC1.innerHTML = '<option value="">Select SPOC1</option>';-->
<!--        SPOC2.innerHTML = '<option value="">Select SPOC2</option>';-->
<!--                                                                   // Make AJAX request to get filtered data-->
<!--        let xhr = new XMLHttpRequest();-->
<!--        xhr.open('GET', '/skyonnadmin/get_contacts/?Client=' + client, true);-->
<!--        xhr.onload = function() {-->
<!--            if (xhr.status === 200) {-->
<!--                var spocData = JSON.parse(xhr.responseText);-->

<!--                spocData.forEach(function(contact) {-->
<!--                    const option1 = document.createElement('option');-->
<!--                    option1.value = `${contact.FirstName}-${contact.Department}`;-->
<!--                    option1.textContent = `${contact.FirstName}-${contact.Department}`;-->
<!--                    SPOC1.appendChild(option1);-->

<!--                    const option2 = document.createElement('option');-->
<!--                    option2.value = `${contact.FirstName}-${contact.Department}`;-->
<!--                    option2.textContent = `${contact.FirstName}-${contact.Department}`;-->
<!--                    SPOC2.appendChild(option2);-->
<!--                });-->
<!--            } else {-->
<!--                console.error('Request failed. Status: ' + xhr.status);-->
<!--            }-->
<!--        };-->
<!--        xhr.onerror = function() {-->
<!--            console.error('Request failed.');-->
<!--        };-->
<!--        xhr.send();-->
<!--  }-->







document.addEventListener('click', function(event) {
  if (event.target && event.target.id === 'getTeamDetailsButton') {
    let client = document.getElementById('ClientDropdown').value;
    let subClient = document.getElementById('SubClientDropdown').value;               //render team details based on client and subclient selected from add contact database

    // Make AJAX request to get filtered data
    let xhr = new XMLHttpRequest();
    xhr.open('GET', '/skyonnadmin/get_team_details/?client=' + client + '&subClient=' + subClient, true);
    xhr.onload = function() {
        if (xhr.status === 200) {
            // Parse the response and store filtered data

            filteredData = JSON.parse(xhr.responseText);
            console.log(filteredData);
            renderTeamDetails(filteredData);                // Render the filtered data in a table

        } else {
            console.error('Request failed. Status: ' + xhr.status);
        }
    };
    xhr.send();
  }
  function enforceCellMaxLength(event) {
   const cell = event.target
   const maxLengths = {'Phone_number':10, 'Pincode':6}

   const field = cell.getAttribute('data-key');
   const maxLength = maxLengths[field]
   if(maxLength && cell.textContent.length > maxLength) {
       cell.textContent = cell.textContent.slice(0,maxLength);

        const range = document.createRange();
        const selection = window.getSelection();
        range.setStart(cell.childNodes[0], cell.textContent.length);        //makes cursor stay at end of text when it reaches max length
        range.collapse(true);
        selection.removeAllRanges();
        selection.addRange(range);
   }
}
const TableBody = document.getElementById('TableContainer');
  if (!TableBody) return;
TableBody.addEventListener('input',enforceCellMaxLength);
})

 function renderTeamDetails(filteredData) {
   let tableBody = document.getElementById('TableContainer');
<!--   tableBody.innerHTML ='';-->

   const searchKeyword = document.getElementById('searchKeyword').value

   if(!searchKeyword) {
      tableBody.innerHTML = `
      <ul style="margin-left: 400px;">
       <li><a href="#" data-department="Hiring Managers">Talent Acquisition</a></li>
       <li><a href="#" data-department="Account Department">Accounts Department</a></li>
       <li><a href="#" data-department="Human Resources">Human Resources</a></li>
       <li><a href="#" data-department="Administration And Legal">Administration And Legal</a></li>
       <li><a href="#" data-department="Business Development">Business Development</a></li>
      </ul>`;
   }


   let AddContactTableHTML = '<div id="TableName"><table border="1">';

   AddContactTableHTML += '<caption style="margin-left: -10px;"><b>Contact Details</b></caption>';

   if (filteredData.contacts.length === 0) {
       AddContactTableHTML += '<thead><tr><th>No details found</th></tr></thead>';
       AddContactTableHTML += '</table></div>';
       tableBody.innerHTML = AddContactTableHTML;
       return;
   }
   else {
           AddContactTableHTML += '<thead><tr>';
           Object.keys(filteredData.contacts[0]).slice(1).filter(column => column !== 'Contact_id')
               .forEach(function (column) {
                  AddContactTableHTML += `<th>${capitalizeFirstLetter(column)}</th>`;
               });


           AddContactTableHTML += `<th>Action</th>`;
           AddContactTableHTML += '</tr></thead><tbody>';

           filteredData.contacts.forEach(function(item) {              // Populate table rows dynamically
                AddContactTableHTML += `<tr data-contact-id="${item.Contact_id}">`;
               Object.keys(item).slice(1).filter(key => key !== 'Contact_id').forEach(function (key) {
                  AddContactTableHTML += `<td data-key="${key}" ${['FirstName', 'LastName', 'Designation', 'Phone_number', 'Email'].includes(key)? 'data-editable="false"': ''}>${item[key]}</td>`;
               });

                AddContactTableHTML += `
                  <td style="width: 150px;">
                    <button class="edit-button-contact" style="font-size: 15px;">Edit</button>
                    <button class="delete-button-contact"  style="font-size: 15px;">Delete</button>
                  </td>
               `;

               AddContactTableHTML +='</tr>';
           })
   }

   AddContactTableHTML += '</tbody></table></div>';
   tableBody.innerHTML += AddContactTableHTML;
   bindActionButtons();

   document.getElementById('TableContainer').addEventListener('click', function(event) {
            if (event.target && event.target.tagName === 'A') {
                event.preventDefault();
                var department = event.target.getAttribute('data-department');
                let client = document.getElementById('ClientDropdown').value;
                let subClient = document.getElementById('SubClientDropdown').value;
                fetchDepartment(department,client,subClient);
            }
   })
 }

  function fetchDepartment(department,client,subClient) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET','/skyonnadmin/get_department/?client=' + client + '&subClient=' +subClient + '&Department=' + encodeURIComponent(department) , true);
    xhr.onload = function() {
        if (xhr.status === 200) {
            var Data = JSON.parse(xhr.responseText);
            renderDepartment(Data);
        }
        else {
            console.error('Request failed. Status: ' + xhr.status);
        }
    };
    xhr.send();
  }

     function renderDepartment(Data) {
          let tableContainer = document.getElementById('TableContainer');
          tableContainer.innerHTML =`
             <ul style="margin-left: 400px;">
               <li><a href="#" data-department="Hiring Managers">Talent Acquisition</a></li>
              <li><a href="#" data-department="Account Department">Accounts Department</a></li>
              <li><a href="#" data-department="Human Resources">Human Resources</a></li>
              <li><a href="#" data-department="Administration And Legal">Administration And Legal</a></li>
              <li><a href="#" data-department="Business Development">Business Development</a></li>
             </ul>` ;
          let DepartmentTableHTML = '<div id="TableName"><table border="1">';

        if (!Data || Data.length === 0) {
                                        // If Data is empty, create a row indicating no details found
            DepartmentTableHTML += '<thead><tr><th>No details found</th></tr></thead>';
        }
        else {
           DepartmentTableHTML += '<thead><tr>';
           Object.keys(filteredData.contacts[0]).slice(1).filter(column => column !== 'Contact_id')
             .forEach(function (column) {
                DepartmentTableHTML += `<th>${capitalizeFirstLetter(column)}</th>`;
             });


           DepartmentTableHTML += `<th>Action</th>`;
           DepartmentTableHTML += '</tr></thead><tbody>';

           Data.forEach(function(item) {              // Populate table rows dynamically
               DepartmentTableHTML += `<tr data-contact-id="${item.Contact_id}">`;
               Object.keys(item).slice(1).filter(key => key !== 'Contact_id').forEach(function (key) {
                  DepartmentTableHTML += `<td data-key="${key}" ${
                       ['FirstName', 'LastName', 'Designation', 'Phone_number', 'Email'].includes(key)? 'data-editable="false"': ''}>${item[key]}</td>`;
                  });

                DepartmentTableHTML += `
                  <td style="width: 150px;">
                    <button class="edit-button-contact" style="font-size: 15px;">Edit</button>
                    <button class="delete-button-contact"  style="font-size: 15px;">Delete</button>
                  </td>
               `;

               DepartmentTableHTML +='</tr>';
           })
        }
        DepartmentTableHTML += '</tbody></table></div>';
        tableContainer.innerHTML += DepartmentTableHTML;

     }


  function bindActionButtons() {
    const tableContainer = document.getElementById('TableContainer');

    const newContainer = tableContainer.cloneNode(true);
    tableContainer.parentNode.replaceChild(newContainer, tableContainer);

    newContainer.addEventListener('click', function(event) {
        const target = event.target;

        if (target.classList.contains('edit-button-contact')) {
            console.log('binding edit contact');
            const row = target.closest('tr');
            const contactId = row.getAttribute('data-contact-id');
            const contactData = filteredData.contacts.find(contact => contact.Contact_id === contactId);
            console.log('Edit contact:', contactData);
            editTeamDetails(event,row);
        }

        if (target.classList.contains('delete-button-contact')) {
            console.log('binding delete contact');
            const row = target.closest('tr');
            const contactId = row.getAttribute('data-contact-id');
            deleteContact(event,contactId);
        }
    });
  }


function editTeamDetails(event,row) {
    event.preventDefault();
    const button = event.target;

  if (button.textContent === 'Edit') {
    console.log('editing team details');
    Array.from(row.cells).forEach((cell, index) => {
        if (index < row.cells.length - 1) {
            const isEditable = cell.getAttribute('data-editable') !== 'false';
            cell.contentEditable = isEditable;

            if (!isEditable) {
                cell.contentEditable = true;
                cell.style.backgroundColor = '';
                cell.removeEventListener('blur', validateTeamDetails);
                cell.addEventListener('blur', validateTeamDetails);
            } else {
                cell.contentEditable = false;
                cell.style.backgroundColor = '#e0e0e0';
            }
        }
    });
    button.textContent = 'Save';
  }
  else if (button.textContent === 'Save') {

        let isValid = true;
         Array.from(row.cells).forEach((cell, index) => {
            if (index < row.cells.length - 1 && cell.contentEditable === 'true') {
                const isCellValid = validateTeamDetails({ target: cell });
                if (!isCellValid) {
                   isValid = false;
                }
            }
        });

         if (!isValid) {
            alert("Validation failed. Please fill out the required fields.");
            return;
         }

    const contact_id = row.getAttribute('data-contact-id');
    const newData = {
        Contact_id: contact_id,
        Company: row.querySelector('[data-key="Company"]').textContent.trim(),
        Sub_company: row.querySelector('[data-key="Sub_company"]').textContent.trim(),
        FirstName: row.querySelector('[data-key="FirstName"]').textContent.trim(),
        LastName: row.querySelector('[data-key="LastName"]').textContent.trim(),
        Department: row.querySelector('[data-key="Department"]').textContent.trim(),
        Designation: row.querySelector('[data-key="Designation"]').textContent.trim(),
        Phone_number: row.querySelector('[data-key="Phone_number"]').textContent.trim(),
        Email: row.querySelector('[data-key="Email"]').textContent.trim()
    };

        Array.from(row.cells).forEach((cell, index) => {
            cell.contentEditable = false;
            cell.style.backgroundColor = '';
        });
        button.textContent = 'Edit';

        fetch(`/skyonnadmin/edit_teamDetails/?Contact_id=${encodeURIComponent(contact_id)}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': '{{csrf_token}}'
            },
            body: JSON.stringify(newData)
        })
            .then(response => {
                if (response.ok) {
                    console.log('Data saved successfully.');
                    alert('Data saved successfully!');
                } else {
                    console.error('Failed to save data.');
                    alert('Failed to save data.');
                }
            })
            .catch(error => {
                console.error('Error saving employee data:', error);
            });
  }
}


function validateTeamDetails(event) {
    const cell = event.target;
    const field = cell.getAttribute('data-key');
    let value = cell.textContent.trim();

    const row = cell.closest('tr');
    const contactId = row.getAttribute('data-contact-id');
    let alertShown = cell.getAttribute('data-alert-shown') === 'true';
    let isValid = true;
    let hasEmailError = false;
    let hasPhoneError = false;

    value = cell.textContent.trim();

    if ((field === 'FirstName' || field === 'Designation') && value === '') {
        if (!alertShown) {
            alert(`${field} field cannot be empty`);
            cell.setAttribute('data-alert-shown', 'true');
        }
        cell.style.backgroundColor = "#FFCCCC";
        cell.focus();
        isValid = false;
    } else {
        cell.setAttribute('data-alert-shown', 'false');
        cell.style.backgroundColor = ""; // Reset background color
    }

    if (field === 'Email') {
        const emailPattern = /^[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}$/;
        const emailPattern2 = /^[^\s@]{1,64}@([^\s@_]+\.)+[a-zA-Z]{2,}$/;

        if (!value.match(emailPattern) || value.includes('..') || !value.match(emailPattern2)) {
            if (!alertShown) {
                alert('Invalid Email Address format');
                cell.setAttribute('data-alert-shown', 'true'); // Prevent multiple alerts
            }
            cell.style.backgroundColor = "#FFCCCC"; // Highlight error
            isValid = false;
            cell.focus();
        } else {
            const emailExists = checkEmailExistsSync(value,contactId);
            console.log('emailExists:',emailExists);
            if (emailExists) {
                if (!alertShown) {
                    alert('email already exists. Please use a different email.');
                    cell.setAttribute('data-alert-shown', 'true');
                }
                cell.style.backgroundColor = "#FFCCCC"; // Highlight error
                isValid = false;
                hasEmailError = true; // Mark email error
                cell.focus(); // Keep focus on the email field
            } else {
                cell.style.backgroundColor = "";
                hasEmailError = false;
                cell.setAttribute('data-alert-shown', 'false');
            }
        }
    }

   if (field === 'Phone_number') {
        const phonePattern = /^[6-9]\d{9}$/;
        if (!value.match(phonePattern)) {
            if (!alertShown) {
                alert('Invalid phone number format');
                cell.setAttribute('data-alert-shown', 'true');
            }
            cell.style.backgroundColor = "#FFCCCC";
            isValid = false;
            cell.focus();
        } else {
            const phoneExists = checkPhoneNumberExistsSync(value,contactId);
            console.log('phoneExists:',phoneExists);
            if (phoneExists) {
                if (!alertShown) {
                    alert('phone number already exists. Please use a different number.');
                    cell.setAttribute('data-alert-shown', 'true'); // Prevent multiple alerts
                }
                cell.style.backgroundColor = "#FFCCCC"; // Highlight error
                isValid = false;
                hasPhoneError = true; // Mark phone error
                cell.focus(); // Keep focus on the phone field
            } else {
                cell.style.backgroundColor = ""; // Reset background color
                hasPhoneError = false; // No phone error
                console.log('hasPhoneError:',hasPhoneError);
                cell.setAttribute('data-alert-shown', 'false'); // Reset alert
            }
        }
   }

   return isValid;
}

function checkEmailExistsSync(email,contactId) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', `/skyonnadmin/validate_cell_field/?Email=${encodeURIComponent(email)}&Contact_id=${encodeURIComponent(contactId)}`, false); // Synchronous request with email and contact_id
    xhr.send();

    if (xhr.status === 200) {
        const response = JSON.parse(xhr.responseText);
        return response.email_exists;
    } else {
        console.error('Error checking email.');
        return false;
    }
}

function checkPhoneNumberExistsSync(phoneNumber,contactId) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', `/skyonnadmin/validate_cell_field/?Phone_number=${encodeURIComponent(phoneNumber)}&Contact_id=${encodeURIComponent(contactId)}`, false); // Synchronous request with phone number and contact_id
    xhr.send();

    if (xhr.status === 200) {
        const response = JSON.parse(xhr.responseText);
        return response.phone_exists; // Return true if phone number exists
    } else {
        console.error('Error checking phone number.');
        return false;
    }
}



  function deleteContact(event,contactId) {
    event.preventDefault();
    console.log('Deleting contact...');

    const button = event.target;
    const row = button.closest('tr'); // Get the row to delete
    const contact_id = row.getAttribute('data-contact-id');
    console.log('Deleting row with Contact Id:', contact_id);

    if (confirm(`Are you sure you want to delete the details?`)) {
               row.remove();
               deleteTeamDetails(contact_id); // Call function to delete row from database
    }

  }

function deleteTeamDetails(contact_id) {

    return fetch(`/skyonnadmin/delete_teamDetails/?Contact_id=${encodeURIComponent(contact_id)}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token }}'  // Properly include the CSRF token
        }
    })
    .then(response => {
        if (response.ok) {
            console.log(`Contact with id ${contact_id} deleted successfully.`);
<!--            alert(`Contact with id ${contact_id} deleted successfully.`);-->
        } else {
            console.error('Failed to delete contact from server.');
        }
    })
    .catch(error => {
        console.error('Network error during contact deletion:', error);
    });
}




  document.addEventListener('DOMContentLoaded', function() {
     window.refreshClientDropdown=function () {
        const form = document.getElementById('Existing_client');
        const clientDropdown = form.querySelector('#ClientDropdown');
        console.log(clientDropdown);

        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/skyonnadmin/get_parentCompany/', true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                clientDropdown.innerHTML = '<option value="">Select Client</option>';
                var data = JSON.parse(xhr.responseText);
                data.forEach(function(company) {
                    const option = document.createElement('option');
                    option.value = company.parent_company;
                    option.textContent = company.parent_company;
                    clientDropdown.appendChild(option);
                });
                const tableContainer = document.getElementById('TableContainer');
                tableContainer.innerHTML = '';
<!--                const contactTableContainer = document.getElementById('contactContainerId');-->
<!--                contactTableContainer.innerHTML = '';-->
            } else {
                console.error('Request failed. Status: ' + xhr.status);
            }
        };
        xhr.send();
     }
  });


function checkForOtherOption() {
    var departmentSelect = document.getElementById('Department');
    var selectedOption = departmentSelect.value;

    if (selectedOption === 'Other') {
        // Create an input element
        var input = document.createElement('input');
        input.type = 'text';
        input.placeholder = 'Enter department';
        input.style.marginLeft = '22px';
        input.onblur = function() {
            if (input.value.trim() !== "") {
                // Add the new department as an option to the select
                var newOption = document.createElement('option');
                newOption.value = input.value;
                newOption.text = input.value;
                newOption.selected = true;
                departmentSelect.add(newOption, departmentSelect.options.length - 1);
            }
            // Switch back to select element and reset the "Other" option
            departmentSelect.style.display = 'inline-block';
            input.style.display = 'none';
            departmentSelect.value = input.value;
            input.remove();
        };

        // Insert the input element after the select element
        departmentSelect.parentNode.insertBefore(input, departmentSelect.nextSibling);

        // Hide the select element and show the input element
        departmentSelect.style.display = 'none';
        input.style.display = 'inline-block';
        input.focus();
    }
}
         function showTeamDetails(){
             console.log('1')
            var teamDetailsList = document.getElementById('teamDetailsList');
            if (teamDetailsList.style.display === 'none' || teamDetailsList.style.display === '') {
                teamDetailsList.style.display = 'block';
            } else {
                teamDetailsList.style.display = 'none';
            }
        }

    function loadPage(pageName, adminId) {
        var urlWithAdminId = pageName + "?admin_id=" + adminId; // Append admin_id as query parameter
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("dynamicContentContainer").innerHTML = this.responseText;
            }
        };
        xhttp.open("GET", urlWithAdminId, true);
        xhttp.send();
    }

function activateLink(clickedLink) {
    var allLinks = document.querySelectorAll('.nav a');

    // Remove 'active' class from all links
    allLinks.forEach(function(link) {
        link.classList.remove('active');
    });

    // Add 'active' class to the clicked link
    clickedLink.classList.add('active');
}
function activateSidebarLink(clickedLink) {
    // Remove 'active' class from all sidebar links
    var sidebarLinks = document.querySelectorAll('.sidebar-link');
    sidebarLinks.forEach(function(link) {
        link.classList.remove('active');
    });

    // Add 'active' class to the clicked sidebar link
    clickedLink.classList.add('active');
}

    function showClientDetails() {
        var clientDetailsContainer = document.getElementById('clientDetailsContainer');
        clientDetailsContainer.style.display = 'block';
        document.getElementById('dynamicContentContainer').innerHTML = ''; // Clear any existing content
    }


    function saveEmployee(button) {
        var row = button.closest('tr');
        Array.from(row.cells).forEach(cell => cell.contentEditable = false);
        button.textContent = 'Edit';
        button.onclick = function() { editEmployee(this); };
    }

    function deleteEmployee(button) {
        var row = button.closest('tr');
        row.parentNode.removeChild(row);
    }

    function addActionButtons(row) {
        var actionCell = row.insertCell();
        var editButton = createButton('Edit', editEmployee);
        var deleteButton = createButton('Delete', deleteEmployee);
        actionCell.append(editButton, deleteButton);
        var space = document.createElement('span');
        space.innerHTML = '&nbsp;';
        actionCell.append(editButton, space, deleteButton);
    }

    function createButton(text, onclickFunction) {
        var button = document.createElement('button');
        button.textContent = text;
        button.onclick = function() { onclickFunction(this); };
        return button;
    }

    function addRowToOriginalTable(data) {
        var table = document.getElementById('originalEmployeeTable').getElementsByTagName('tbody')[0];
        var row = table.insertRow();
        data.forEach(item => row.insertCell().textContent = item);
        addActionButtons(row);
    }

    var isNewTableAdded = false;

    function addNewTable() {
        if (!isNewTableAdded) {
            var originalTableParent = document.querySelector('.original-table');
            var newTable = document.createElement('table');
            newTable.id = 'newEmployeeTable';
            newTable.style.width = '80%';
            newTable.style.Color = 'white';
            newTable.style.marginLeft = '350px';
            newTable.style.borderCollapse = 'collapse';
            newTable.style.marginBottom = '20px';
            newTable.style.borderBottom = 'none';
            var originalTableHeader = originalTableParent.querySelector('thead').cloneNode(true);
            newTable.appendChild(originalTableHeader);
            var newRow = newTable.insertRow();
            var columns = originalTableHeader.querySelectorAll('th').length;
            for (var i = 0; i < columns - 1; i++) {
                newRow.insertCell().contentEditable = true;
            }
            newRow.insertCell().innerHTML = '<button onclick="saveNewTable()">Save</button>';
            originalTableParent.appendChild(newTable);
            isNewTableAdded = true;
        }
    }

function saveNewTable() {
    var confirmation = confirm("Are you sure you want to save the details?");
    if (confirmation) {
        var originalTable = document.getElementById('originalEmployeeTable');
        var originalTBody = originalTable.getElementsByTagName('tbody')[0];
        var newTable = document.getElementById('newEmployeeTable');
        var newRows = newTable.getElementsByTagName('tr');
        console.log('new rows assigning');
        var addContact= [];
        console.log('adding contact started');

        for (var i = 1; i < newRows.length; i++) {
            var newData = Array.from(newRows[i].cells).slice(0, -1).map(cell => cell.innerText);
            addContact.push({
                name: newData[0],           // Assuming first cell is name, adjust if needed
                designation: newData[1],       // Assuming second cell is designation, adjust if needed
                department: newData[2],     // Assuming third cell is department, adjust if needed
                phone_no: newData[3],       // Assuming fourth cell is phone_no, adjust if needed
                email: newData[4],        // Assuming fifth cell is email, adjust if needed
                location: newData[5]      // Assuming sixth cell is location, adjust if needed
                                           // Add other properties as needed
            });

            console.log(addContact)

        }

        fetch('/skyonnadmin/add_contact/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRFToken': '{{ csrf_token }}'
            },
            body: JSON.stringify(addContact)
        })
        .then(response => {
            if (response.ok) {
                console.log('Data saved successfully.');
                for (var i = 1; i < newRows.length; i++) {
                    var newRow = originalTBody.insertRow();
                    newData.forEach(item => newRow.insertCell().textContent = item);
                    addActionButtons(newRow);
                    console.log('new rows assigned')
                }
                newTable.remove();
                isNewTableAdded = false;
            }
            else {
                console.error('Failed to save data.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });

    }
}




document.addEventListener('click', function(event) {
   if (event.target && event.target.id === 'getCompanyDetailsButton') {
       let client = document.getElementById('ClientDropdown').value;
       let subClient = document.getElementById('SubClientDropdown').value;

       // Make AJAX request to get filtered data
       let xhr = new XMLHttpRequest();
       xhr.open('GET', '/skyonnadmin/get_filtered_data/?client=' + client + '&subClient=' + subClient, true);
       xhr.onload = function() {
           if (xhr.status === 200) {
               // Parse the response and store filtered data

               filteredData = JSON.parse(xhr.responseText);
               console.log(filteredData);
               renderTable(filteredData);                // Render the filtered data in a table
           } else {
               console.error('Request failed. Status: ' + xhr.status);
           }
       };
       xhr.send();
   }
});

   function capitalizeFirstLetter(str) {
      return str.charAt(0).toUpperCase() + str.slice(1);
   }

function renderTable(filteredData) {
   let tableContainer = document.getElementById('TableContainer');
   tableContainer.innerHTML = '';

   const searchKeyword = document.getElementById('searchKeyword').value.trim();
   const searchButton = document.getElementById('searchButton')

   if (filteredData.client_details.length > 0 && filteredData.sub_company_details.length > 0) {
       renderClientTable(filteredData.client_details, 'Main client');
       renderClientTable(filteredData.sub_company_details, 'Sub client');
   } else {
       renderClientTable(filteredData.client_details, 'Main client');
   }
   AddActionButtons();
}

 function renderClientTable(data, caption) {
   let tableHTML = `<div id="TableName"><table border="1">`;
   tableHTML += `<caption><b>${caption}</b></caption>`;
   tableHTML += '<thead><tr>';

   let columns = Object.keys(data[0]).slice(1).filter(column => !['client_id', 'sub_client_id'].includes(column)); // Skip the first column (usually ID)
   columns.forEach(function(column) {
       tableHTML += `<th>${capitalizeFirstLetter(column)}</th>`;
   });

   tableHTML += `<th style="width: 150px;">Action</th>`;
   tableHTML += '</tr></thead><tbody>';

   data.forEach(function(item) {
       let idAttribute = '';
       if (item.client_id) {
           idAttribute = `data-client-id="${item.client_id}" data-parent-company="${item.parent_company}"`;
       } else if (item.sub_client_id) {
           idAttribute = `data-sub-client-id="${item.sub_client_id}" data-original-subcompany="${item.sub_company}" data-parent-company="${item.parent_company}"`;
       }
       tableHTML += `<tr ${idAttribute}>`;
       columns.forEach(function(column) {
                tableHTML += `<td data-key="${column}" ${['parent_company', 'country'].includes(column) ? 'data-editable="false"' : 'data-editable="true"' } style="word-wrap: break-word; max-width: 100px;">${item[column]}</td>`;
       });

       tableHTML += `
           <td style="width: 150px;">
               <button class="edit-button-client" style="font-size: 15px; margin-left; -50px;">Edit</button>
               <button class="delete-button-client" style="font-size: 15px;">Delete</button>
           </td>
       `;
       tableHTML += '</tr>';
   });
   tableHTML += '</tbody></table></div>';
   if (caption === 'Main client') {
        tableHTML += '<div id="error-message1" style="color: red; margin-top: 2px; margin-left: 1270px;"></div>';
        tableHTML += '</div>'; // Close clientTableContainer div
    } else if (caption === 'Sub client') {
        tableHTML += '<div id="error-message2" style="color: red; margin-top: 2px; margin-left: 1280px;"></div>';
        tableHTML += '</div>'; // Close subClientTableContainer div
    }
   document.getElementById('TableContainer').innerHTML += tableHTML;
 }

 function AddActionButtons() {
   document.querySelectorAll('.edit-button-client').forEach(button => {
       button.addEventListener('click', editCompanyDetails);
   });
   document.querySelectorAll('.delete-button-client').forEach(button => {
       button.addEventListener('click', deleteClient);
   });
 }

function editCompanyDetails(event) {
   event.preventDefault();
   const button = event.target;
   let row = button.closest('tr');
   console.log('editing company details');

   Array.from(row.cells).forEach((cell, index) => {
        if (index < row.cells.length - 1) {                               // Exclude the last cell (actions cell)
            const isEditable = cell.getAttribute('data-editable') === 'true';
            console.log(isEditable);
            if (isEditable) {
                cell.contentEditable = true;
                cell.removeEventListener('blur', validateCompanyDetails);
                cell.addEventListener('blur', validateCompanyDetails);
            } else {
                cell.contentEditable = false;
                cell.style.backgroundColor = '#e0e0e0';                // Set background color for non-editable cells
            }
        }
   });

   button.textContent = 'Save';
   button.classList.remove('edit-button-client');
   button.classList.add('save-button-client');
   button.removeEventListener('click', editCompanyDetails);
   button.addEventListener('click', saveCompanyDetails);
}

  function validateCompanyDetails(event) {
    const cell = event.target;
    const value = cell.textContent.trim();
    const field = cell.getAttribute('data-key');
    let isValid = true; // Assume the input is valid by default
    let alertShown = cell.getAttribute('data-alert-shown') === 'true';
    const row = cell.closest('tr');

    // Identify the error container based on client or sub-client
    let errorContainer;
    if (row.getAttribute('data-client-id')) {
        errorContainer = document.getElementById('error-message1');
    } else if (row.getAttribute('data-sub-client-id')) {
        errorContainer = document.getElementById('error-message2');
    }

    // Clear previous error messages
    if (errorContainer) {
        errorContainer.innerHTML = '';
    }

    // Define the fields that require validation
    const fieldsToValidate = ['sub_company','GST_No', 'location_Id', 'location_id', 'address_1', 'City', 'state', 'Pincode'];
    const isPincode = field === 'Pincode';
    const pincodePattern = /^[1-9][0-9]{5}$/;

    // Check if the field is allowed to be empty
    if (fieldsToValidate.includes(field) && value === '') {
        if (!alertShown) {
            alert(`${field} field cannot be empty`);
            cell.setAttribute('data-alert-shown', 'true');
        }
        isValid = false;
    } else {
        cell.setAttribute('data-alert-shown', 'false'); // Reset alert flag for valid input
    }

    // Pincode validation
    if (isPincode) {
        if (!pincodePattern.test(value)) {
            if (!alertShown) {
                alert('Invalid Pincode format');
                cell.setAttribute('data-alert-shown', 'true');
            }
            isValid = false;
        } else {
            cell.setAttribute('data-alert-shown', 'false'); // Reset flag for valid pincode
        }
    }

    // Set styling and validity feedback
    if (!isValid) {
        cell.style.backgroundColor = "#FFCCCC";
        cell.setAttribute('data-valid', 'false');
        cell.focus();
    } else {
        cell.style.backgroundColor = "";
        cell.setAttribute('data-valid', 'true');
    }

    return isValid;
}



 function saveCompanyDetails(event) {
   event.preventDefault();
   const button = event.target;
   const row = button.closest('tr');
   console.log('saving');
   let isValid = true;

   const originalSubcompany = row.getAttribute('data-original-subcompany');
   console.log('originalSubcompany',originalSubcompany);

                                  // Get the error row below the current row
   Array.from(row.cells).forEach((cell, index) => {
        if (index < row.cells.length - 1) { // Exclude the last cell (actions cell)
            if (cell.contentEditable === 'true') {
                validateCompanyDetails({ target: cell });
                if (cell.getAttribute('data-valid') === 'false') {
                    isValid = false;
                }
            }
        }
   });

    if (!isValid) {
        alert('Please fix the validation errors before saving.');
        return;
    }


   const id = row.getAttribute('data-client-id') || row.getAttribute('data-sub-client-id');
   console.log(id);

   let newData = {};
   if (row.getAttribute('data-client-id')) {
     newData = {
           client_id: id,
           parent_company: getDataValue(row, 'parent_company'),
           GST_No: getDataValue(row, 'GST_No'),
           location_Id: getDataValue(row, 'location_Id'),
           address_1: getDataValue(row, 'address_1'),
           address_2: getDataValue(row, 'address_2'),
           City: getDataValue(row, 'City'),
           state: getDataValue(row, 'state'),
           Pincode: getDataValue(row, 'Pincode'),
           country: getDataValue(row, 'country')
       };
   } else if (row.getAttribute('data-sub-client-id')) {
       newData = {
           sub_client_id: id,
           parent_company: getDataValue(row, 'parent_company'),
           sub_company: getDataValue(row, 'sub_company'),
           GST_No: getDataValue(row, 'GST_No'),
           location_id: getDataValue(row, 'location_id'),
           address_1: getDataValue(row, 'address_1'),
           address_2: getDataValue(row, 'address_2'),
           City: getDataValue(row, 'City'),
           State: getDataValue(row, 'State'),
           Pincode: getDataValue(row, 'Pincode'),
           country: getDataValue(row, 'country')
       };
   }

   console.log('New data to save:', newData);
   const updateSubcompany = newData.sub_company
   console.log('updateSubcompany',updateSubcompany);

   // Fetch request to save data
   fetch(`/skyonnadmin/edit_CompanyDetails/`, {
       method: 'POST',
       headers: {
           'Content-Type': 'application/json',
           'X-CSRFToken': '{{ csrf_token }}'
       },
       body: JSON.stringify(newData)
   })
   .then(response => {
       if (response.ok) {
           console.log(`Data with id ${id} saved successfully.`);
           alert(`Data with id ${id} saved successfully.`);
           Array.from(row.cells).forEach((cell, index) => {
                    if (index < row.cells.length - 1) { // Exclude the last cell (actions cell)
                        cell.contentEditable = false;
                        cell.style.backgroundColor = 'white';
                        cell.removeEventListener('blur', validateCompanyDetails);
                    }
           });
           button.textContent = 'Edit';
           button.classList.remove('save-button-client');
           button.classList.add('edit-button-client');
           button.removeEventListener('click', saveCompanyDetails);
           button.addEventListener('click', editCompanyDetails);

           if(originalSubcompany !== updateSubcompany && newData.sub_client_id) {
               refreshClientDropdown();
           }
       } else {
           throw new Error('Failed to save details.');
       }
   })
   .catch(error => {
       console.error('Error saving details:', error);
       // Handle error
   });

   function getDataValue(row, key) {
      const cell = row.querySelector(`[data-key="${key}"]`);
      return cell ? cell.textContent.trim() : '';
   }
 }


 function deleteClient(event) {
   console.log('deleting');
   event.preventDefault();
   const button = event.target;
   const row = button.closest('tr');

   const clientId = row.getAttribute('data-client-id');
   const subClientId = row.getAttribute('data-sub-client-id');
   const parentCompanyId = row.getAttribute('data-parent-company');
   const subCompanyId = row.getAttribute('data-original-subcompany');

<!--   const idToDelete = row.getAttribute('parent_company');-->
   console.log('Deleting row with id:', parentCompanyId);

   const confirmationMessage = clientId
        ? `Are you sure you want to delete the Client,Subclient and Contact data for Parent Company: ${parentCompanyId}?`
        : `Are you sure you want to delete the subclient ${subCompanyId} with client : ${parentCompanyId}?`;

    if (confirm(confirmationMessage)) {
        deleteCompanyDetails({ client_id: clientId, sub_client_id: subClientId, parent_company: parentCompanyId }, row);
    }
 }

 function deleteCompanyDetails(data,row) {

   fetch(`/skyonnadmin/delete_CompanyDetails/` , {
       method: 'DELETE',
       headers: {
           'Content-Type': 'application/json',
           'X-CSRFToken':  '{{ csrf_token }}'            // Include CSRF token if needed
       },
       body: JSON.stringify(data)
   })
   .then(response => {
       if (response.ok) {
           console.log(`Data deleted successfully.`);
           row.remove(); // Remove the row from the table
           refreshClientDropdown();
       } else {
           throw new Error('Failed to delete details.');
       }
   })
   .catch(error => {
       console.error('Error deleting details:', error);
       // Handle error
   });
 }




    function saveForm() {
        event.preventDefault();
        var formData = new FormData(document.getElementById('jobPostingForm'));
        if (!validateForm(formData)) {
            return false;
        }
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'url/to/submit/form', true);
        xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 300) {
                console.log(xhr.responseText);
            } else {
                console.error(xhr.statusText);
            }
        };
        xhr.onerror = function() {
            console.error(xhr.statusText);
        };
        xhr.send(formData);
        return false;
    }

    function validateForm(formData) {
        var requiredFields = ['ParentCompany', 'SubCompany', 'Location', 'Department', 'GSTNo', 'Address', 'FirstName', 'PhoneNo1', 'CompanyEmail', 'Designation', 'LastName', 'Location', 'Designation'];
        for (var i = 0; i < requiredFields.length; i++) {
            var field = requiredFields[i];
            if (!formData.get(field)) {
                alert("Please fill in all the required fields.");
                return false;
            }
        }
        return true;
    }



document.addEventListener('DOMContentLoaded', function() {
  document.addEventListener('change', function() {
    const form = document.getElementById('addClientForm');
    if (!form) return;

    const parentCompanyInput = document.getElementById('ParentCompany');
    let requiredFields = form.querySelectorAll('input[required], select[required]');

    const clearValidation = (field) => {
        field.setCustomValidity('');
        field.style.borderColor = '';
    };

    const validateField = (field) => {
        if (!field.value.trim()) {
            field.style.borderColor = '';
            field.setCustomValidity('Please fill out this field.');
            field.reportValidity();
            field.focus();
            return false;
        } else {
            field.style.borderColor = 'black';
            field.setCustomValidity('');
            return true;
        }
    };

    parentCompanyInput.addEventListener('input', () => clearValidation(parentCompanyInput));

    parentCompanyInput.addEventListener('blur', () => {
        if (validateField(parentCompanyInput)) {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', '/skyonnadmin/check_parent_company/?ParentCompany=' + encodeURIComponent(parentCompanyInput.value), true);
            xhr.onload = () => {
                if (xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    if (response.exists) {
                        parentCompanyInput.style.borderColor = '';
                        parentCompanyInput.setCustomValidity('Parent company already exists.');
                        parentCompanyInput.reportValidity();
                    } else {
                        parentCompanyInput.style.borderColor = 'black';
                    }
                } else {
                    console.error('Request failed. Status: ' + xhr.status);
                }
            };
            xhr.send();
        }
    });
  });
});

    window.saveClient = function() {
        let isValid = true;
        const form = document.getElementById('addClientForm');
        let requiredFields = form.querySelectorAll('input[required], select[required]');
        requiredFields.forEach(field => {
            field.setCustomValidity(''); // Clear previous validation message
            field.style.borderColor = ''; // Reset border color
        });

        // Iterate over each required field to check if it has value
        for (let field of requiredFields) {
            if (!field.value.trim()) {
                isValid = false;
                field.style.borderColor = '';
                field.setCustomValidity('Please fill out this field.');
                field.reportValidity();
                field.focus();
                break;
            } else {
                // If field is filled, reset border to black
                field.style.borderColor = 'black';
                field.setCustomValidity('');
            }
        }

        if (!isValid) {
            // Prevent form submission if validation fails
            console.log("Validation failed. Please fill out the required fields.");
            return;
        }

        const formData = new FormData(form);
        const url = form.getAttribute('action');

        fetch(url, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRFToken': '{{ csrf_token }}',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'error') {
                if (data.field && data.message) {
                    const errorField = form.querySelector(`[name=${data.field}]`);
                    if (errorField) {
                        errorField.style.borderColor = '';
                        errorField.setCustomValidity(data.message);
                        errorField.reportValidity();
                        errorField.focus();
                        errorField.value = '';
                          errorField.addEventListener('input', () => {
                             errorField.style.borderColor = 'black';
                             errorField.setCustomValidity('');
                             errorField.reportValidity();
                          }, { once: true });
                    } else {
                        alert(data.message);
                    }
                } else {
                    alert(data.message || 'Error saving Client.');
                }
            } else {
                alert('Client saved successfully.');
                form.reset();
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error: ' + error.message);
        });
    };



document.addEventListener('DOMContentLoaded', function() {
    window.populateParentCompanyDropdown=function() {
        const form = document.getElementById('subLocationsForm');
        if (!form) return;

        const clientDropdown = form.querySelector('#ParentCompany');
        if (!clientDropdown) return;

        var xhr = new XMLHttpRequest();
        xhr.open('GET', '/skyonnadmin/get_parentCompany/', true);
        xhr.onload = function() {
            if (xhr.status === 200) {
                clientDropdown.innerHTML = '<option value="">Select Client</option>';
                var data = JSON.parse(xhr.responseText);
                data.forEach(function(company) {
                    const option = document.createElement('option');
                    option.value = company.parent_company;
                    option.textContent = company.parent_company;
                    clientDropdown.appendChild(option);
                });
            } else {
                console.error('Request failed. Status: ' + xhr.status);
            }
        };
        xhr.send();
    }
});


  function toggleaddSubLocation() {
        var mainForm = document.getElementById("addClientForm");
        var subForm = document.getElementById("subLocationsForm");
        var addButton = document.getElementById("addSubLocation");

        mainForm.style.display = "none";
        subForm.style.display = "block";
        addButton.style.display = "none";

        // Populate the dropdown when the form is displayed
        populateParentCompanyDropdown();
  }


  function saveSubLocation() {
     const form = document.getElementById('subLocationsForm');
     const requiredFields = form.querySelectorAll('input[required], select[required]');

    let isValid = true;

    // Clear any previous custom validation messages and reset border colors
    requiredFields.forEach(field => {
        field.setCustomValidity(''); // Clear previous validation message
        field.style.borderColor = ''; // Reset border color
    });

    // Iterate over each required field to check if it has value
    for (let field of requiredFields) {
        if (!field.value.trim()) {
            isValid = false;
            field.style.borderColor = '';
            field.setCustomValidity('Please fill out this field.');
            field.reportValidity();
            field.focus();
            break;
        }
    }

    if (!isValid) {
        // Prevent form submission if validation fails
        console.log("Validation failed. Please fill out the required fields.");
        return;
    }

    // Proceed with saving data if all fields are valid
    const formData = new FormData(form);
    const url = form.getAttribute('action');

    console.log("Submitting form to:", url);
    console.log("Form data:", [...formData.entries()]); // Log the form data


    fetch(url, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRFToken': '{{ csrf_token }}', // Assuming you have CSRF token available
            },
        })
        .then(response => {
            return response.json().then(data => {
               if (!response.ok) {
                          // Handle specific error messages
                  if (data.message) {
                     throw new Error(data.message);
                  }
               }
               return data;
            });
        })
        .then(data => {
            console.log('Success:', data);
            alert('Sub_Location saved successfully.');
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error:' + error.message);

        })
        .finally(() => {
                              // Clear all fields in the form whether success or error
             form.reset();
        });
    }




document.addEventListener('DOMContentLoaded', function() {
  document.addEventListener('change', function() {
    const form = document.getElementById('addSubClientForm');
    if (!form) return;

    const ParentCompanyInput = document.getElementById('ParentCompany');
    const SubCompanyInput = document.getElementById('SubCompany');
    const locationInput = document.getElementById('Location_Id');
    const GSTNoInput = document.getElementById('GSTNo');
    console.log('GSTNoInput:',GSTNoInput.disabled);

    const requiredFields = form.querySelectorAll('input[required], select[required]');

    const clearValidation = (field) => {
        field.setCustomValidity('');
        field.style.borderColor = '';
    };

    const validateField = (field) => {
        if (!field.value.trim()) {
            field.style.borderColor = '';
            field.setCustomValidity('Please fill out this field.');
            field.reportValidity();
            field.focus();
            return false;
        } else {
            field.style.borderColor = 'black';
            field.setCustomValidity('');
            return true;
        }
    };

    const fetchGSTNo = () => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', '/skyonnadmin/get_GSTNo/?ParentCompany=' + encodeURIComponent(ParentCompanyInput.value), true);
        xhr.onload = () => {
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                if (response.GST_No) {
                    GSTNoInput.value = response.GST_No;
                }
            } else {
                console.error('Request failed. Status:', xhr.status);
            }
        };
        xhr.send();
    };

    ParentCompanyInput.addEventListener('change', () => {
        if (ParentCompanyInput.value) {
            fetchGSTNo();
        }
    });

    ParentCompanyInput.addEventListener('blur', () => {
        if (ParentCompanyInput.value) {
            fetchGSTNo();
        }
    });

    SubCompanyInput.addEventListener('input', () => clearValidation(SubCompanyInput));

    SubCompanyInput.addEventListener('blur', () => {
        if (validateField(SubCompanyInput) && GSTNoInput.disabled) {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', '/skyonnadmin/check_sub_company/?SubCompany=' + encodeURIComponent(SubCompanyInput.value), true);
            xhr.onload = () => {
                if (xhr.status === 200) {
                    const response = JSON.parse(xhr.responseText);
                    if (response.exists) {
                        SubCompanyInput.style.borderColor = '';
                        SubCompanyInput.setCustomValidity('Sub company already exists.');
                        SubCompanyInput.reportValidity();
                    } else {
                        SubCompanyInput.style.borderColor = '';
                    }
                } else {
                    console.error('Request failed. Status: ' + xhr.status);
                }
            };
            xhr.send();
        }
    });

    if (changeButton.textContent === 'Change') {
      changeButton.addEventListener('click', function (event) {
         event.preventDefault();
         console.log('Change clicked');
         GSTNoInput.disabled = false; // Enable input for editing
         GSTNoInput.focus(); // Focus on the input field
         changeButton.textContent = 'Save';
      })
    } else if (changeButton.textContent === 'Save' && GSTNoInput.value.trim() !== '') {
      changeButton.addEventListener('click', function (event) {
         console.log('Save clicked');

         GSTNoInput.disabled = true; // Disable the input
         changeButton.textContent = 'Change'; // Change the button text back to Change
         console.log('Updated GST No:', updatedGST);
      })
    }
  });
});

    window.saveSubClient = function() {
        let isValid = true;
        const GSTNoInput = document.getElementById('GSTNo');
        const changeButton = document.getElementById("changeButton");
        const form = document.getElementById('addSubClientForm');
        let requiredFields = form.querySelectorAll('input[required], select[required]');

        requiredFields.forEach(field => {
            field.setCustomValidity(''); // Clear previous validation message
            field.style.borderColor = ''; // Reset border color
        });

        // Iterate over each required field to check if it has value
        for (let field of requiredFields) {
            if (!field.value.trim()) {
                isValid = false;
                field.style.borderColor = '';
                field.setCustomValidity('Please fill out this field.');
                field.reportValidity();
                field.focus();
                break;
            } else {
                // If field is filled, reset border to black
                field.style.borderColor = 'black';
                field.setCustomValidity('');
            }
        }

        if (!isValid) {
            // Prevent form submission if validation fails
            console.log("Validation failed. Please fill out the required fields.");
            return;
        }

        const updatedGST = GSTNoInput.value.trim(); // Get the input value
        if (!updatedGST) {
            GSTNoInput.setCustomValidity('GST field cannot be empty');
            GSTNoInput.reportValidity();
            GSTNoInput.focus(); // Refocus the input field if invalid
            return;
        }

        if (changeButton.textContent === 'Save') {
           GSTNoInput.setCustomValidity('click save button');
           GSTNoInput.reportValidity();
           GSTNoInput.focus(); // Refocus the input field if invalid
           return;
        }

        const formData = new FormData(form);
        formData.append('GSTNo',GSTNoInput.value);
        const url = form.getAttribute('action');

        fetch(url, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRFToken': '{{ csrf_token }}',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'error') {
                if (data.field && data.message) {
                    const errorField = form.querySelector(`[name=${data.field}]`);
                    if (errorField) {
                        errorField.style.borderColor = '';
                        errorField.setCustomValidity(data.message);
                        errorField.reportValidity();
                        errorField.focus();
                        errorField.value = '';
                        errorField.addEventListener('input', () => clearValidation(errorField), { once: true });
                    } else {
                        alert(data.message);
                    }
                } else {
                    alert(data.message || 'Error saving Sub Client.');
                }
            } else {
                alert('Sub Client saved successfully.');
                form.reset();
                GSTNoInput.disabled = true;
                changeButton.textContent = 'Change';
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error: ' + error.message);
        });
    };



    function hideClientDetails() {
        // Example implementation
        var clientDetailsContainer = document.getElementById('clientDetailsContainer');
        if (clientDetailsContainer) {
            clientDetailsContainer.style.display = 'none';
        }
    }

  document.addEventListener('DOMContentLoaded', function() {
  document.addEventListener('change', function(event) {
      var target = event.target;
      const formId = document.getElementById('Existing_client');
      console.log(formId);
      if (target && target.id === 'ClientDropdown' && formId.id === 'Existing_client') {
          var parentCompany = target.value; // Get selected client
          var subClientDropdown = target.closest('form').querySelector('#SubClientDropdown');

          subClientDropdown.innerHTML = '';
                               // Make an AJAX request to fetch sub-clients filtered by selected client
          var xhr = new XMLHttpRequest();
          xhr.open('GET', '/skyonnadmin/get_subclients/?parent_company=' + parentCompany, true);
          xhr.onload = function() {
              if (xhr.status === 200) {

                   subClientDropdown.innerHTML = '<option value="All Sub Clients">All Sub Clients</option>';
                                 // Parse response and add options to SubClient dropdown
                  var subClients = JSON.parse(xhr.responseText);
                  subClients.forEach(function(subClient) {
                      var option = document.createElement('option');
                      option.value = subClient;
                      option.text = subClient;
                      subClientDropdown.appendChild(option);
                  });
              } else {
                  console.error('Request failed. Status: ' + xhr.status);
              }
          };
          xhr.send();
      }
  });
});


  const subCompanyInput = document.getElementById('SubCompany');

    subCompanyInput.addEventListener('input', () => {
        subCompanyInput.value = subCompanyInput.value.replace(/\b\w/g, (char) => char.toUpperCase());
    });

<!--    document.addEventListener('DOMContentLoaded', function() {-->
<!--        // Define a variable to store the filtered data-->
<!--        let filteredData = [];-->

<!--        // Function to display filtered data based on selected tab-->
<!--        function displayFilteredData(department) {-->
<!--            // Clear the table body-->
<!--            let tableBody = document.querySelector('#originalEmployeeTable tbody');-->
<!--            tableBody.innerHTML = '';-->

<!--            // Filter the data based on department-->
<!--            let departmentData = filteredData.filter(function(item) {-->
<!--                return item.department.toLowerCase() === department;-->
<!--            });-->

<!--            // Append filtered data to the table-->
<!--            departmentData.forEach(function(item) {-->
<!--                let row = `<tr>-->
<!--                    <td>${item.name}</td>-->
<!--                    <td>${item.designation}</td>-->
<!--                    <td>${item.department}</td>-->
<!--                    <td>${item.phone}</td>-->
<!--                    <td>${item.email}</td>-->
<!--                    <td>${item.location}</td>-->
<!--                    <td>Action</td>-->
<!--                </tr>`;-->
<!--                tableBody.innerHTML += row;-->
<!--            });-->
<!--        }-->

<!--        // Event listener for clicking on department tabs-->
<!--        let departmentLinks = document.querySelectorAll('.department-link');-->
<!--        departmentLinks.forEach(function(link) {-->
<!--            link.addEventListener('click', function() {-->
<!--                let department = this.getAttribute('data-department');-->
<!--                displayFilteredData(department);-->
<!--            });-->
<!--        });-->
<!--        -->
<!--        -->

<!--        // Event listener for clicking on Get Details button-->
<!--document.addEventListener('click', function(event) {-->
<!--    if (event.target && event.target.id === 'getDetailsButton') {-->
<!--        console.log('getting filtered data')-->
<!--        let client = document.getElementById('ClientDropdown').value;-->
<!--        let subClient = document.getElementById('SubClientDropdown').value;-->

<!--        // Make AJAX request to get filtered data-->
<!--        let xhr = new XMLHttpRequest();-->
<!--        xhr.open('GET', '/skyonnadmin/get_filtered_data/?client=' + client + '&subClient=' + subClient, true);-->
<!--        xhr.onload = function() {-->
<!--            if (xhr.status === 200) {-->
<!--                // Parse the response and store filtered data-->
<!--                filteredData = JSON.parse(xhr.responseText);-->

<!--                // Display data based on selected tab-->
<!--                let activeTab = document.querySelector('.department-link.active');-->
<!--                if (activeTab) {-->
<!--                    let department = activeTab.getAttribute('data-department');-->
<!--                    displayFilteredData(department);-->
<!--                }-->
<!--            } else {-->
<!--                console.error('Request failed. Status: ' + xhr.status);-->
<!--            }-->
<!--        };-->
<!--        xhr.send();-->
<!--    }-->
<!--});-->
<!-- });-->

<!--    function showPopup() {-->
<!--            document.getElementById('popup').style.display = 'block';-->
<!--        }-->
<!--        function hidePopup() {-->
<!--            document.getElementById('popup').style.display = 'none';-->
<!--        }-->
<!--        function saveForm() {-->
<!--            if (validateForm()) {-->
<!--                document.getElementById('jobPostingForm').submit();-->
<!--                hidePopup();-->
<!--            }-->
<!--        }-->
<!--        function validateForm() {-->
<!--            var requiredFields = document.querySelectorAll('input[required], select[required], textarea[required]');-->
<!--            var isValid = true;-->
<!--            requiredFields.forEach(function(field) {-->
<!--                if (!field.value.trim()) {-->
<!--                    isValid = false;-->
<!--                    field.style.border = '2px solid red';-->
<!--                } else {-->
<!--                    field.style.border = '1px solid #ccc';-->
<!--                }-->
<!--            });-->
<!--            if (!isValid) {-->
<!--                alert('Please fill in all required fields.');-->
<!--            }-->
<!--            return isValid;-->
<!--        }-->

<!--    function limitNumberOfPostings(input) {-->
<!--        var maxPostings = 100;-->
<!--        if (input.value > maxPostings) {-->
<!--            input.value = maxPostings; // Set the value to the maximum allowed-->
<!--        }-->
<!--    }-->
<!--    function updateInputField() {-->
<!--    var selectedStatesInput = document.getElementById("selectedStatesInput");-->
<!--    var selectedStates = [];-->
<!--    var checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');-->
<!--    for (var i = 0; i < checkboxes.length; i++) {-->
<!--        selectedStates.push(checkboxes[i].value);-->
<!--    }-->
<!--    selectedStatesInput.value = selectedStates.join(", ");-->
<!--    // Close the dropdown after updating the input field-->
<!--    var dropdownContent = document.getElementById("checkboxContainer");-->
<!--    dropdownContent.style.display = "none";-->
<!--}-->

<!--function toggleOtherInputField() {-->
<!--    var otherCheckbox = document.getElementById("OtherCheckbox");-->
<!--    var selectedStatesInput = document.getElementById("selectedStatesInput");-->
<!--    var dropdownContent = document.getElementById("checkboxContainer");-->
<!--    if (otherCheckbox.checked) {-->
<!--        // Show the modal for adding a new location-->
<!--        showAddLocationModal();-->
<!--        dropdownContent.style.display = "none";-->
<!--    } else {-->
<!--        // If "Other" is unchecked, clear the input field, make it readonly again, and show dropdown content-->
<!--        selectedStatesInput.value = "";-->
<!--        selectedStatesInput.readOnly = true;-->
<!--        dropdownContent.style.display = "block";-->
<!--    }-->
<!--}-->

<!--function toggleDropdown() {-->
<!--    var dropdownContent = document.getElementById("checkboxContainer");-->
<!--    if (dropdownContent.style.display === "none") {-->
<!--        dropdownContent.style.display = "block";-->
<!--    } else {-->
<!--        dropdownContent.style.display = "none";-->
<!--    }-->
<!--}-->

<!--function showAddLocationModal() {-->
<!--    document.getElementById("addLocationModal").style.display = "block";-->
<!--}-->

<!--function closeAddLocationModal() {-->
<!--    document.getElementById("addLocationModal").style.display = "none";-->
<!--    document.getElementById("OtherCheckbox").checked = false;-->
<!--}-->

<!--function saveNewLocation() {-->
<!--    var newLocation = document.getElementById("newLocationInput").value.trim();-->
<!--    var selectedStatesInput = document.getElementById("selectedStatesInput");-->

<!--    if (newLocation) {-->
<!--        // Add new location to the dropdown-->
<!--        addLocationToDropdown(newLocation);-->

<!--        // Save new location to local storage-->
<!--        saveLocation(newLocation);-->

<!--        // Update the input field with the new location-->
<!--        var currentInput = selectedStatesInput.value;-->
<!--        selectedStatesInput.value = currentInput ? currentInput + ", " + newLocation : newLocation;-->

<!--        // Clear and reset the input field-->
<!--        document.getElementById("newLocationInput").value = "";-->
<!--        closeAddLocationModal();-->
<!--    } else {-->
<!--        alert("Please enter a location.");-->
<!--    }-->
<!--}-->

<!--function addLocationToDropdown(location) {-->
<!--    var checkboxContainer = document.getElementById("checkboxItems");-->
<!--    if (!checkboxContainer) {-->
<!--        return;-->
<!--    }-->

<!--    var newCheckbox = document.createElement("input");-->
<!--    newCheckbox.type = "checkbox";-->
<!--    newCheckbox.value = location;-->
<!--    newCheckbox.style.marginLeft = "-50px";-->
<!--    newCheckbox.id = "checkbox_" + location.replace(/\s+/g, '_');-->
<!--    newCheckbox.name = "checkbox_" + location.replace(/\s+/g, '_');-->
<!--    newCheckbox.onchange = updateInputField;-->

<!--    var newCheckboxLabel = document.createElement("label");-->
<!--    newCheckboxLabel.style.marginLeft = "-48px";-->
<!--    newCheckboxLabel.setAttribute("for", newCheckbox.id);-->
<!--    newCheckboxLabel.appendChild(document.createTextNode(" " + location));-->

<!--    checkboxContainer.appendChild(newCheckbox);-->
<!--    checkboxContainer.appendChild(newCheckboxLabel);-->
<!--    checkboxContainer.appendChild(document.createElement("br"));-->
<!--}-->

<!--function saveLocation(location) {-->
<!--    var locations = JSON.parse(localStorage.getItem('locations')) || [];-->
<!--    locations.push(location);-->
<!--    localStorage.setItem('locations', JSON.stringify(locations));-->
<!--}-->

<!--function loadLocations() {-->
<!--    var locations = JSON.parse(localStorage.getItem('locations')) || [];-->
<!--    locations.forEach(function(location) {-->
<!--        addLocationToDropdown(location);-->
<!--    });-->
<!--}-->

<!--document.addEventListener('DOMContentLoaded',function() {-->
<!--   document.addEventListener('change',function(event) {-->
<!--     var target = event.target;-->
<!--     if (target && target.id === 'Client') {-->
<!--        var client = target.value;-->

<!--       let xhr= new XMLHttpRequest();-->
<!--       xhr.open('GET',`/get_locations/?Client=${client}`,true);-->
<!--       xhr.onload = function() {-->
<!--            if (xhr.status === 200) {-->
<!--                const locations = JSON.parse(xhr.responseText);-->

<!--                updateCheckboxItems(locations);-->
<!--            } else {-->
<!--                console.error('Request failed. Status: ' + xhr.status);-->
<!--            }-->
<!--       };-->
<!--       xhr.send()-->
<!--     }-->

<!--   function updateCheckboxItems(locations) {-->
<!--      const checkboxItems = document.getElementById('checkboxItems');-->

<!--      checkboxItems.innerHTML = `-->
<!--        <input type="checkbox" id="telanganaCheckbox" name="telanganaCheckbox" value="Telangana" onchange="updateInputField()" style="margin-left: -50px;">-->
<!--        <label for="telanganaCheckbox" style="margin-left: -50px;">Telangana</label><br>-->
<!--        <input type="checkbox" id="andhraCheckbox" name="andhraCheckbox" value="Andhra Pradesh" onchange="updateInputField()" style="margin-left: -50px;">-->
<!--        <label for="andhraCheckbox" style="margin-left: -50px;">Andhra Pradesh</label><br>-->
<!--        <input type="checkbox" id="gujaratCheckbox" name="gujaratCheckbox" value="Gujarat" onchange="updateInputField()" style="margin-left: -50px;">-->
<!--        <label for="gujaratCheckbox" style="margin-left: -50px;">Gujarat</label><br>-->
<!--      `;-->

<!--      locations.forEach(function(location) {-->
<!--         const existingLocation = checkboxItems.querySelector(`input[value="${location}"]`)-->

<!--         if (!existingLocation) {-->
<!--            // Create a checkbox and label for each location-->
<!--            const checkbox = document.createElement('input');-->
<!--            checkbox.type = 'checkbox';-->
<!--            checkbox.name = location;-->
<!--            checkbox.value = location;-->
<!--            checkbox.style.marginLeft = '-50px';-->
<!--            checkbox.onchange = updateInputField;-->

<!--            const label = document.createElement('label');-->
<!--            label.textContent = location;-->
<!--            label.style.marginLeft = '-45px';-->
<!--            label.htmlFor = location;-->

<!--            // Append checkbox and label to the container-->
<!--            checkboxItems.appendChild(checkbox);-->
<!--            checkboxItems.appendChild(label);-->
<!--            checkboxItems.appendChild(document.createElement('br'));-->
<!--         }-->
<!--      });-->
<!--   }-->
<!--   });-->
<!--});-->



<!--function showPopup() {-->
<!--    document.getElementById('addContactPopup').style.display = 'flex';-->
<!--}-->

<!--function hidePopup() {-->
<!--    document.getElementById('addContactPopup').style.display = 'none';-->
<!--}-->

<!--function showSuccessPopup() {-->
<!--    document.getElementById('successPopup').style.display = 'flex';-->
<!--}-->

<!--function hideSuccessPopup() {-->
<!--    document.getElementById('successPopup').style.display = 'none';-->
<!--}-->


<!--        // Function to validate the job posting form (to be implemented)-->
<!--        function saveJobPosting() {-->
<!--            // Add your form validation and submission logic here-->
<!--            alert('Job posting saved!');-->
<!--        }-->



<!--function saveJobPosting() {-->
<!--    const form = document.getElementById('jobPostingForm');-->
<!--    const orderedFieldIds = [-->
<!--        'Client', 'JobID', 'selectedStatesInput', 'SPOC', 'SPOC2',-->
<!--        'NoOfPosting', 'StartDate', 'CloseDate', 'Type', 'Experience',-->
<!--        'BudgetMin', 'BudgetMax', 'Header', 'JobDescription', 'SpecialInstructions', 'JD'-->
<!--    ];-->

<!--    let isValid = true;-->
<!--    let firstInvalidField = null;-->

<!--    // Clear any previous custom validation messages and reset border colors-->
<!--    orderedFieldIds.forEach(id => {-->
<!--        const field = document.getElementById(id);-->
<!--        if (field) {-->
<!--            field.setCustomValidity(''); // Clear previous validation message-->
<!--            field.style.borderColor = ''; // Reset border color-->
<!--        }-->
<!--    });-->

<!--    // Iterate over each field in the specified order to validate-->
<!--    for (let id of orderedFieldIds) {-->
<!--        const field = document.getElementById(id);-->

<!--        if (field) {-->
<!--            if (!field.value.trim()) {-->
<!--                isValid = false;-->
<!--                field.setCustomValidity('Please fill out this field.');-->

<!--                // Show the validation message for this field-->
<!--                field.reportValidity();-->

<!--                // Focus the first invalid field-->
<!--                if (!firstInvalidField) {-->
<!--                    firstInvalidField = field;-->
<!--                }-->

<!--                // Exit the loop after finding the first invalid field-->
<!--                break;-->
<!--            } else {-->
<!--                // If the field is valid, reset its border color-->
<!--                field.style.borderColor = '';-->
<!--                field.setCustomValidity('');-->
<!--            }-->
<!--        }-->
<!--    }-->


<!--    if (!isValid) {-->
<!--        // Focus on the first invalid field according to the specified order-->
<!--        if (firstInvalidField) {-->
<!--            firstInvalidField.focus();-->
<!--        }-->

<!--        console.log("Validation failed. Please fill out the required fields.");-->
<!--        return;-->
<!--    }-->

<!--    // Proceed with saving data if all fields are valid-->
<!--    const formData = new FormData(form);-->
<!--    const url = form.getAttribute('action');-->

<!--    console.log("Submitting form to:", url);-->
<!--    console.log("Form data:", [...formData.entries()]); // Log the form data-->

<!--    fetch(url, {-->
<!--        method: 'POST',-->
<!--        body: formData,-->
<!--        headers: {-->
<!--            'X-CSRFToken': '{{ csrf_token }}', // Assuming you have CSRF token available-->
<!--        },-->
<!--    })-->
<!--    .then(response => {-->
<!--        if (!response.ok) {-->
<!--            throw new Error('Failed to save job posting.');-->
<!--        }-->
<!--        return response.json();-->
<!--    })-->
<!--    .then(data => {-->
<!--        console.log('Success:', data);-->
<!--        alert('Job saved successfully.');-->
<!--    })-->
<!--    .catch(error => {-->
<!--        console.error('Error:', error);-->
<!--        alert('Error: ' + error.message);-->
<!--    })-->
<!--    .finally(() => {-->
<!--        // Clear all fields in the form whether success or error-->
<!--        form.reset();-->

<!--        // Reset field borders to their default state-->
<!--        orderedFieldIds.forEach(id => {-->
<!--            const field = document.getElementById(id);-->
<!--            if (field) {-->
<!--                field.style.borderColor = 'initial'; // Reset to default border color-->
<!--            }-->
<!--        });-->
<!--    });-->
<!--}-->



<!--function validateDates() {-->
<!--        var startDate = new Date(document.getElementById("StartDate").value);-->
<!--        var closeDate = new Date(document.getElementById("CloseDate").value);-->

<!--        if (closeDate <= startDate) {-->
<!--            alert("Close Date must be greater than Start Date.");-->
<!--            document.getElementById("CloseDate").value = "";-->
<!--        }-->
<!--    }-->

<!--function validateBudget() {-->
<!--    var budgetMin = parseInt(document.getElementById("BudgetMin").value);-->
<!--    var budgetMax = parseInt(document.getElementById("BudgetMax").value);-->
<!--    var budgetMaxInput = document.getElementById("BudgetMax");-->
<!--    var errorPopup = document.getElementById("budgetMaxErrorPopup");-->

<!--    // Check if BudgetMin is less than or equal to 10000-->
<!--    if (budgetMin <= 0) {-->
<!--        // Show the error popup for BudgetMin-->
<!--        errorPopup.textContent = "Budget Min must be greater than max.";-->
<!--        errorPopup.classList.add("show");-->

<!--        // Optionally, you can set styles to visually indicate the error-->
<!--        var budgetMinInput = document.getElementById("BudgetMin");-->

<!--        budgetMinInput.focus(); // Focus back on BudgetMin for correction-->
<!--        return; // Exit function early to prevent further validation-->
<!--    } else {-->
<!--        // Hide the error popup for BudgetMin-->
<!--        errorPopup.classList.remove("show");-->
<!--        var budgetMinInput = document.getElementById("BudgetMin");-->
<!--        budgetMinInput.style.borderColor = "";-->
<!--        budgetMinInput.style.color = "";-->
<!--    }-->

<!--    // Check if BudgetMax is less than or equal to BudgetMin-->
<!--    if (budgetMax <= budgetMin) {-->
<!--        // Show the error popup for BudgetMax-->
<!--        errorPopup.textContent = "Budget Max must be greater than Budget Min.";-->
<!--        errorPopup.classList.add("show");-->

<!--        // Optionally, you can set styles to visually indicate the error-->


<!--        budgetMaxInput.focus(); // Focus back on BudgetMax for correction-->
<!--    } else {-->
<!--        // Hide the error popup for BudgetMax-->
<!--        errorPopup.classList.remove("show");-->
<!--        budgetMaxInput.style.borderColor = "";-->
<!--        budgetMaxInput.style.color = "";-->
<!--    }-->
<!--}-->

<!--// Attach the validation function to the input events-->
<!--document.getElementById("BudgetMin").addEventListener("input", validateBudget);-->
<!--document.getElementById("BudgetMin").addEventListener("blur", validateBudget);-->
<!--document.getElementById("BudgetMax").addEventListener("input", validateBudget);-->
<!--document.getElementById("BudgetMax").addEventListener("blur", validateBudget);-->



  document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.querySelector("input[type='text']");
    searchInput.addEventListener("input", debounce(function() {
        const query = this.value.trim();

        // Modify the URL in the address bar without reloading the page
        const newUrl = `${window.location.origin}${window.location.pathname}?query=${encodeURIComponent(query)}`;
        history.pushState({ path: newUrl }, '', newUrl);

        fetch(`./?query=${encodeURIComponent(query)}`) // Adjusted to relative path
            .then(response => response.text())
            .then(html => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, "text/html");
                const newBody = doc.querySelector("tbody");
                const oldBody = document.querySelector("table tbody");
                if (oldBody && newBody) {
                    oldBody.parentNode.replaceChild(newBody, oldBody);
                }
            })
            .catch(error => console.error('Error fetching filtered job postings:', error));
    }, 500));
});

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        }, wait);
        if (immediate && !timeout) func.apply(context, args);
    };
};




<!--function alljobposting(){-->
<!--document.addEventListener('DOMContentLoaded', function() {-->
<!--    const searchInput = document.querySelector("input[type='text']");-->
<!--    searchInput.addEventListener("input", debounce(function() {-->
<!--        const query = this.value.trim();-->

<!--        // Modify the URL in the address bar without reloading the page-->
<!--        const newUrl = `${window.location.origin}${window.location.pathname}?query=${encodeURIComponent(query)}`;-->
<!--        history.pushState({ path: newUrl }, '', newUrl);-->

<!--        fetch(`./?query=${encodeURIComponent(query)}`) // Adjusted to relative path-->
<!--            .then(response => response.text())-->
<!--            .then(html => {-->
<!--                const parser = new DOMParser();-->
<!--                const doc = parser.parseFromString(html, "text/html");-->
<!--                const newBody = doc.querySelector("tbody");-->
<!--                const oldBody = document.querySelector("table tbody");-->
<!--                if (oldBody && newBody) {-->
<!--                    oldBody.parentNode.replaceChild(newBody, oldBody);-->
<!--                }-->
<!--            })-->
<!--            .catch(error => console.error('Error fetching filtered job postings:', error));-->
<!--    }, 500));-->
<!--});-->

<!--function debounce(func, wait, immediate) {-->
<!--    var timeout;-->
<!--    return function() {-->
<!--        var context = this, args = arguments;-->
<!--        clearTimeout(timeout);-->
<!--        timeout = setTimeout(function() {-->
<!--            timeout = null;-->
<!--            if (!immediate) func.apply(context, args);-->
<!--        }, wait);-->
<!--        if (immediate && !timeout) func.apply(context, args);-->
<!--    };-->
<!--};-->
<!--    }-->

     function searchJob() {
            var input, filter, table, tr, td, i, txtValue;
            input = document.getElementById("searchInput");
            filter = input.value.toUpperCase();
            table = document.querySelector("table");
            tr = table.getElementsByTagName("tr");
            for (i = 1; i < tr.length; i++) {
                var found = false;
                td = tr[i].getElementsByTagName("td")[1]; // Get the second column (JobID)
                if (td) {
                    txtValue = td.textContent || td.innerText;
                    if (txtValue.toUpperCase().indexOf(filter) > -1) {
                        found = true;
                    }
                }
                tr[i].style.display = found ? "" : "none";
            }
        }


function goBack() {
    hidePopup(); // Assuming you have a function to hide the popup
    // Optionally, show another section or perform other actions
}



   function toggleForm(formId) {
            var forms = ['Existing_employeeform', 'add_employeeform'];
            forms.forEach(function(id) {
                var form = document.getElementById(id);
                if (form && id === formId) {
                    form.style.display = form.style.display === 'block' ? 'none' : 'block';
                } else if (form) {
                    form.style.display = 'none';
                }
            });
   }

 function validatePhoneNumbers() {
        var phoneNo1 = document.getElementById('PhoneNo1').value;
        var phoneNo2 = document.getElementById('PhoneNo2').value;

        if (phoneNo1 === '' && phoneNo2 === '') {
            alert("Please enter either Mobile No or Land No.");
            return false;  // Prevent form submission
        }

        // Allow form submission if one of the fields is filled
        return true;
    }
















</script>

    </section>

 </div>
</body>
</html>