<!DOCTYPE html>
<html lang="en">
<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.4.2/css/all.min.css" integrity="sha512-z3gLpd7yknf1YoNbCzqRKc4qyor8gaKU1qmn+CShxbuBusANI9QpRohGBreCFkKxLhei6S9CQXFEbbKuqLg0DA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap');
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Roboto', sans-serif;
}
 body {
            height: 100vh;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }
.header {
    height: 60px;
    width: 100%;
    display: flex;
    align-items: center;
    border-bottom: 1px solid black;

}
 h2{
color: red;
margin-left:400px ;
white-space: nowrap;
margin-top: 10px;
}
.search--notification--profile {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: calc(100% - 100px);
    padding: 0 40px;
    margin-left: -10px;
}
.search {
    width: 300px;
    padding: 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.search-container {
    display: flex;
    align-items: center;
    border: 1px solid black;
    border-radius: 5px;
    padding: 0 5px;
}
.search input {
    outline: none;
    border: none;
    text-indent: 15px;
    width: 100%;
    height: 40px;
}
.search button {
    outline: none;
    border: none;
    padding: 0;
    display: flex;
    align-items: center;
    justify-content: center;
}
.main {
    position: relative;
    width: 100%;
    min-height: calc(100vh - 60px);
}

.sidebar {
    position: fixed; /* Fix the sidebar */
    top: 60px; /* Position it below the header */
    left: 0;
    height: calc(100vh - 60px); /* Adjust height to account for header */
    width: 250px;
    background-color: #fff;
    padding: 30px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    border-right: 1px solid black;
    overflow-y: auto; /* Add scrolling for the sidebar if content overflows */
}

.sidebar.active {
    width: 103px;
}
.sidebar.active .sidebar--item {
    display: none;
}
li {
    list-style: none;
}
a {
    text-decoration: none;
}
.sidebar--items a,
.sidebar--bottom-items a {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    font-size: 1.1rem;
    color:blue;
    padding: 10px;
    border-radius: 10px;
}
.sidebar--items a:hover,
.sidebar--bottom-items a:hover {
    color: red;
}
.sidebar--items a.active {
    color: red; /* Adjust the color as needed */
     font-weight: bold;
}

#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 */
}}

    </style>
    <title> Admin Dashboard</title>
</head>
<body>
    <section class="header">
            <h1 style="color: lightskyblue; margin-top: 10px; margin-left: 50px; text-decoration: underline;">Home</h1>
            <h2>Admin <span>Dashboard</span></h2>
        <div class="search--notification--profile">
            <div class="search">
                <div class="search-container">
                    <input type="text" placeholder="Search">
                    <button><i class="ri-search-2-line"></i></button>
                </div>
            </div>
            </div>
                <div class="bell" style="margin-right: 40px;">
    <i class="fa-solid fa-bell"></i>
</div>
<div class="profile" style="margin-right: 40px;">
    <i class="fa-solid fa-user"></i>
</div>
<h3 style="margin-right: 40px;">Laxmi</h3>
<a href="/skyonnadmin/admin_logout/" style="margin-right: 350px; color: blue; font-size: larger; text-decoration: underline;">LogOut</a>
    </section>
    <section class="main">
        <div class="sidebar">
            <ul class="sidebar--items">
              <li><a href="#" class="sidebar-link" onclick="showClientDetails(); activateSidebarLink(this)">Client Details</a></li>
<li>
    <a href="#" class="sidebar-link" onclick="loadPage('/new_job_postings/');  hideClientDetails(); activateSidebarLink(this)">
        <span class="sidebar--item"> Internal Team Details</span>
    </a>
</li>
<li>
    <a href="#" class="sidebar-link" onclick="loadPage('/new_job_postings/');  hideClientDetails(); activateSidebarLink(this)">
        <span class="sidebar--item">New Job Postings</span>
    </a>
</li>
                <li>
                    <a href="/all_job_postings/" class="sidebar-link" onclick="activateLink(this)" >
                        <span class="sidebar--item">All Jobs Postings</span>
                    </a>
                </li>
                <li>
                    <a href="#" class="sidebar-link" onclick="loadPage('/new_job_postings/');  hideClientDetails(); activateSidebarLink(this)">
                        <span class="sidebar--item">Messages</span>
                    </a>
                </li>
                <li>
                    <a href="#" class="sidebar-link" onclick="loadPage('/new_job_postings/');  hideClientDetails(); activateSidebarLink(this)">
                        <span class="sidebar--item">Pending Process</span>
                    </a>
                </li>
                <li>
                     <a href="#" class="sidebar-link" onclick="loadPage('/new_job_postings/');  hideClientDetails(); activateSidebarLink(this)">
                        <span class="sidebar--item">Submitted Resumes</span>
                    </a>
                </li>
                <li>
                   <a href="#" class="sidebar-link" onclick="loadPage('/new_job_postings/');  hideClientDetails(); activateSidebarLink(this)">
                        <span class="sidebar--item">Add a New SPOC</span>
                    </a>
                </li>
                <li>
                     <a href="#" class="sidebar-link" onclick="loadPage('/new_job_postings/');  hideClientDetails(); activateSidebarLink(this)">
                        <span class="sidebar--item">Activity Report</span>
                    </a>
                </li>
            </ul>
        </div>
        <div id="clientDetailsContainer" style="display: none;">
            <ul>
                <div class="nav" >

                     <li><a href="#" class="btn" onclick="activateLink(this); loadPage('/skyonnadmin/add_client/','SKYA001')">Add New Client</a></li>
                    <li><a href="#" class="btn" onclick="activateLink(this); loadPage('/skyonnadmin/add_subclient/','SKYA001')">Add Sub Clients/Locations</a></li>

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

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

      <script>
<!--  document.getElementById('Phone_number').addEventListener('input', function(event) {-->
<!--            const phoneNumberField = event.target;-->
<!--            const value = phoneNumberField.value;-->
<!--            // Check if the value is all zeros-->
<!--            const isAllZeros = /^0+$/.test(value);-->
<!--            // Check if the value matches the required pattern (starts with 6-9 and is 10 digits long)-->
<!--            const matchesPattern = /^(?!0{10})[6-9]\d{9}$/.test(value);-->

<!--            if (isAllZeros) {-->
<!--                phoneNumberField.setCustomValidity('Phone number cannot be all zeros.');-->
<!--                phoneNumberField.style.borderColor = 'red';-->
<!--            } else if (matchesPattern) {-->
<!--                phoneNumberField.setCustomValidity('');-->
<!--                phoneNumberField.style.borderColor = 'green';-->
<!--            } else {-->
<!--                phoneNumberField.setCustomValidity('Invalid phone number. It must start with a digit from 6 to 9 and be 10 digits long.');-->
<!--                phoneNumberField.style.borderColor = 'red';-->
<!--            }-->

<!--            phoneNumberField.reportValidity();-->
<!--        });-->

 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 renderTeamDetails(filteredData) {
   let tableBody = document.getElementById('TableContainer');
   tableBody.innerHTML = `
   <ul style="margin-left: 400px;">
       <li><a href="#" data-department="HIRING MANAGERS">HIRING MANAGERS</a></li>
       <li><a href="#" data-department="ACCOUNT DEPARTMENT">ACCOUNT 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>
   </ul>`;

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

   if (filteredData.contacts.length === 0) {
       AddContactTableHTML += '<thead><tr><th>No details found</th></tr></thead>';
   } else {
       let AddContactTable = Object.keys(filteredData.contacts[0]);

       AddContactTableHTML += '<thead><tr>';
       AddContactTable.slice(1).forEach(function(column) { // Add table headers
           AddContactTableHTML += `<th>${capitalizeFirstLetter(column)}</th>`;
       });
       AddContactTableHTML += '</tr></thead><tbody>';

       filteredData.contacts.forEach(function(item) { // Populate table rows dynamically
           AddContactTableHTML += '<tr>';
           AddContactTable.slice(1).forEach(function(column) {
               AddContactTableHTML += `<td>${item[column]}</td>`;
           });
           AddContactTableHTML += '</tr>';
       });
       AddContactTableHTML += '</tbody>';
   }

   AddContactTableHTML += '</table></div>';
   tableBody.innerHTML += AddContactTableHTML;

   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">HIRING MANAGERS</a></li>
                <li><a href="#" data-department="ACCOUNT DEPARTMENT">ACCOUNT 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>
             </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(Data[0]).slice(1).forEach(function(column) {                    // Add table headers
               DepartmentTableHTML += `<th>${capitalizeFirstLetter(column)}</th>`;
           });
           DepartmentTableHTML += '</tr></thead><tbody>';

           Data.forEach(function(item) {              // Populate table rows dynamically
               DepartmentTableHTML +='<tr>' ;
               Object.values(item).slice(1).forEach(function(value) {
                  DepartmentTableHTML +=`<td>${value}</td>`;
               });
               DepartmentTableHTML +='</tr>';
           })
        }
        DepartmentTableHTML += '</tbody></table></div>';
        tableContainer.innerHTML += DepartmentTableHTML;
     }


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 editEmployee(button) {
        var row = button.closest('tr');
        Array.from(row.cells).forEach(cell => cell.contentEditable = true);
        button.textContent = 'Save';
        button.onclick = function() { saveEmployee(this); };
    }

    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': '8a73pMpoMUvdfCvcH5wGBfAHjuaDhtRv8QLQ8HRujeXazFcs0hwBJDqN8sDOqG72'
            },
            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 tableBody = document.getElementById('TableContainer')
       tableBody.innerHTML= '';

       if (filteredData.client_details.length > 0 && filteredData.sub_company_details.length > 0) {
          let clientTable = Object.keys(filteredData.client_details[0]);
          let clientTableHTML = '<div id="TableName"><table border="1">';
          clientTableHTML += '<caption><b>Main client</b></caption>'
          clientTableHTML += '<thead><tr>';

          clientTable.slice(1).forEach(function(column) {                    // Add table headers
             clientTableHTML += `<th>${capitalizeFirstLetter(column)}</th>`;
          });
          clientTableHTML += '</tr></thead><tbody>';

          filteredData.client_details.forEach(function(item) {              // Populate table rows dynamically
              clientTableHTML +='<tr>' ;
              clientTable.slice(1).forEach(function(column) {
                 clientTableHTML +=`<td>${item[column]}</td>`;
              });
              clientTableHTML +='</tr>';
          });
          clientTableHTML += '</tbody></table></div>';
          tableBody.innerHTML += clientTableHTML;


          let SubClientTable = Object.keys(filteredData.sub_company_details[0]);
          let SubClientTableHTML = '<div id="TableName"><table border="1">';
          SubClientTableHTML += '<caption><b>Sub client</b></caption>'
          SubClientTableHTML += '<thead><tr>';
          SubClientTable.slice(1).forEach(function(column) {                    // Add table headers
             SubClientTableHTML += `<th>${capitalizeFirstLetter(column)}</th>`;
          });
          SubClientTableHTML += '</tr></thead><tbody>';

          filteredData.sub_company_details.forEach(function(item) {              // Populate table rows dynamically
              SubClientTableHTML +='<tr>' ;
              SubClientTable.slice(1).forEach(function(column) {
                 SubClientTableHTML +=`<td>${item[column]}</td>`;
              });
              SubClientTableHTML +='</tr>';
          });
          SubClientTableHTML += '</tbody></table></div>';
          tableBody.innerHTML += SubClientTableHTML;
       }
       else {
          let clientTable = Object.keys(filteredData.client_details[0]);
          let clientTableHTML = '<div id="TableName"><table border="1">';
          clientTableHTML += '<caption><b>Main client</b></caption>'
          clientTableHTML += '<thead><tr>';

          clientTable.slice(1).forEach(function(column) {                    // Add table headers
             clientTableHTML += `<th>${capitalizeFirstLetter(column)}</th>`;
          });
          clientTableHTML += '</tr></thead><tbody>';

          filteredData.client_details.forEach(function(item) {              // Populate table rows dynamically
              clientTableHTML +='<tr>' ;
              clientTable.slice(1).forEach(function(column) {
                 clientTableHTML +=`<td>${item[column]}</td>`;
              });
              clientTableHTML +='</tr>';
          });
          clientTableHTML += '</tbody></table></div>';
          tableBody.innerHTML += clientTableHTML;
       }
    }



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

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


<!--    function saveJobPosting() {-->
<!--        const form = document.getElementById('jobPostingForm');-->
<!--        const formData = new FormData(form);-->
<!--        // Ensure this retrieves the correct URL-->
<!--        const url = form.getAttribute('action');-->
<!--        console.log('CSRF Token:', '8a73pMpoMUvdfCvcH5wGBfAHjuaDhtRv8QLQ8HRujeXazFcs0hwBJDqN8sDOqG72');-->
<!--        console.log('Form action URL:', url);-->

<!--        fetch(url, {-->
<!--                method: 'POST',-->
<!--                body: formData,-->
<!--                headers: {-->
<!--                    'X-CSRFToken': '8a73pMpoMUvdfCvcH5wGBfAHjuaDhtRv8QLQ8HRujeXazFcs0hwBJDqN8sDOqG72', // Assuming you have CSRF token available-->
<!--                },-->
<!--            })-->
<!--            .then(response => {-->
<!--                if (!response.ok) {-->
<!--                    throw new Error('Network response was not ok');-->
<!--                }-->
<!--                return response.json();-->
<!--            })-->
<!--            .then(data => {-->
<!--                console.log('Success:', data);-->
<!--                alert('Job posting saved successfully.');-->
<!--                form.reset();-->
<!--            })-->
<!--            .catch(error => {-->
<!--                console.error('Error:', error);-->
<!--                alert('An error occurred while saving the job posting.');-->
<!--            });-->
<!--    }-->




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 = 'red';
            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 = 'red';
                        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 = 'red';
                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': '8a73pMpoMUvdfCvcH5wGBfAHjuaDhtRv8QLQ8HRujeXazFcs0hwBJDqN8sDOqG72',
            },
        })
        .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 = 'red';
                        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);
        });
    };


  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;

            // Highlight the empty field with a red border
            field.style.borderColor = '';

            // Set a custom validation message
            field.setCustomValidity('Please fill out this field.');

            // Show the validation message for this field
            field.reportValidity();

            // Focus the first invalid field
            field.focus();

            // Exit the loop after finding the first invalid field
            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': '8a73pMpoMUvdfCvcH5wGBfAHjuaDhtRv8QLQ8HRujeXazFcs0hwBJDqN8sDOqG72', // 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;          //when form is not called it will not attach form fields

    const SubCompanyInput = document.getElementById('SubCompany');
    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 = 'red';
            field.setCustomValidity('Please fill out this field.');
            field.reportValidity();
            field.focus();
            return false;
        } else {
            field.style.borderColor = 'black';
            field.setCustomValidity('');
            return true;
        }
    };

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

    SubCompanyInput.addEventListener('blur', () => {
        if (validateField(SubCompanyInput)) {
            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 = 'red';
                        SubCompanyInput.setCustomValidity('Sub company already exists.');
                        SubCompanyInput.reportValidity();
                    } else {
                        SubCompanyInput.style.borderColor = 'green';
                    }
                } else {
                    console.error('Request failed. Status: ' + xhr.status);
                }
            };
            xhr.send();
        }
    });
  });
});

    window.saveSubClient = function() {
        let isValid = true;
        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 = 'red';
                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': '8a73pMpoMUvdfCvcH5wGBfAHjuaDhtRv8QLQ8HRujeXazFcs0hwBJDqN8sDOqG72',
            },
        })
        .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 = 'red';
                        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();
            }
        })
        .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;
        if (target && target.id === 'ClientDropdown') {
            var parentCompany = target.value; // Get selected client
            var subClientDropdown = target.closest('form').querySelector('#SubClientDropdown');
            var formId = target.closest('form').id;

            // 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) {
                    // Clear existing options
                    subClientDropdown.innerHTML = '<option value="">Select Sub Client</option>';

                     if (formId === 'Existing_client') {
                        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();
        }
    });
});


    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() {
            console.log("showPopup() called");
            document.getElementById('addContactPopup').style.display = 'flex';
        }

        // Function to hide the popup
        function hidePopup() {
            document.getElementById('addContactPopup').style.display = 'none';
        }

        // Function to handle form submission inside the popup (to be implemented)
        function saveAddNewContact() {
            // Add your form submission logic here
            alert('New contact saved!');
            hidePopup(); // Hide the popup after saving
        }

        // 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 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 = "";
        }
    }
  messages.

function saveJobPosting() {
        var requiredFields = document.querySelectorAll('#Client,#JobID, #StartDate, #CloseDate, #BudgetMin, #BudgetMax, #JobDescription, #Type');
        var isValid = true;

        for (let field of requiredFields) {
            if (!field.value.trim()) {
                isValid = false;
                field.style.borderColor = 'red';
                field.setCustomValidity('Please fill out this field.');
                field.reportValidity();
                field.focus();
            } else {
                // Reset border to black if field is filled
                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;
        }

        // Proceed with saving data if all fields are valid
        alert("Data saved successfully!");
        // Example: You can make an AJAX call to save the data to the server
        // Example: document.getElementById("yourFormId").submit();
    }

        function validateBudget() {
    var budgetMin = parseFloat(document.getElementById("BudgetMin").value);
    var budgetMax = parseFloat(document.getElementById("BudgetMax").value);
    console.log("Budget Min:", budgetMin);
    console.log("Budget Max:", budgetMax);
    var budgetError = document.getElementById("budgetError");
    if (budgetMin > budgetMax) {
        budgetError.style.display = "inline"; // Show error message
    } else {
        budgetError.style.display = "none"; // Hide error message
    }
}
    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) {
        // If "Other" is checked, make the input field editable and hide dropdown content
        selectedStatesInput.readOnly = false;
        selectedStatesInput.focus();
        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 validateBudget() {
    var budgetMin = parseFloat(document.getElementById("BudgetMin").value);
    var budgetMax = parseFloat(document.getElementById("BudgetMax").value);
    console.log("Budget Min:", budgetMin);
    console.log("Budget Max:", budgetMax);
    var budgetError = document.getElementById("budgetError");
    if (budgetMin > budgetMax) {
        budgetError.style.display = "inline"; // Show error message
    } else {
        budgetError.style.display = "none"; // Hide error message
    }
}
const startDateInput = document.getElementById('StartDate');
    const CloseDateInput = document.getElementById('CloseDate');
    const CloseDateError = document.getElementById('CloseDateError');
    CloseDateInput.addEventListener('change', function() {
        const startDate = new Date(startDateInput.value);
        const CloseDate = new Date(CloseDateInput.value);
        if (CloseDate <= startDate) {
            CloseDateError.style.display = 'block';
            CloseDateInput.value = ''; // Clear the invalid end date
        } else {
            CloseDateError.style.display = 'none';
        }
    });


        function saveAdd_new_contact() {
        const form = document.getElementById('Add_new_contact');
        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;

            // Highlight the empty field with a red border
            field.style.borderColor = 'red';

            // Set a custom validation message
            field.setCustomValidity('Please fill out this field.');

            // Show the validation message for this field
            field.reportValidity();

            // Focus the first invalid field
            field.focus();

            // Exit the loop after finding the first invalid field
            break;
        } else {
            // If field is filled, reset border to black
            field.style.borderColor = 'black';
        }
    }

    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': '8a73pMpoMUvdfCvcH5wGBfAHjuaDhtRv8QLQ8HRujeXazFcs0hwBJDqN8sDOqG72', // Assuming you have CSRF token available
        },
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'error') {
            // Check if the response contains a specific field error
            if (data.field && data.message) {
                const errorField = form.querySelector(`[name=${data.field}]`);
                if (errorField) {
                    // Highlight the error field with a red border
                    errorField.style.borderColor = 'red';
                    errorField.setCustomValidity(data.message);
                    errorField.reportValidity();
                    errorField.focus();
                    // Clear only the problematic field's value
                    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 Add_new_contact');
            }
        } else {
            console.log('Success:', data);
            alert('Add_new_contact saved successfully.');
            form.reset();
            // Reset the border colors to default after a successful save
            requiredFields.forEach(field => field.style.borderColor = '');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error: ' + error.message);
    });
}

// Attach the real-time validation to each required field
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('Add_new_contact');
    const requiredFields = form.querySelectorAll('input[required], select[required]');

    requiredFields.forEach(field => {
        field.addEventListener('input', () => {
            if (field.value.trim()) {
                field.style.borderColor = 'black'; // Valid input
                field.setCustomValidity(''); // Clear any custom validation message
            } else {
                field.style.borderColor = 'red'; // Invalid input
                field.setCustomValidity('Please fill out this field.'); // Set custom validation message
            }
        });
    });

    // Attach Add_new_contact function to the save button
    document.getElementById('saveButton').addEventListener('click', Add_new_contact);
});





</script>

    </section>


</body>
</html>